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_dron_write_semantics.py · 57.7 KB · 1094 lines
| 1 | """DRON write semantics: what the engine does with one create, update or delete. |
| 2 | |
| 3 | docs/dron-write-semantics.md states, statement by numbered statement (S1, S2, |
| 4 | ...), the order of every check that can refuse a write, what a refusal |
| 5 | leaves behind, what blank and null mean, when derived values are computed, |
| 6 | what a partial update means and which clock a comparison reads. It is written |
| 7 | for someone building a second engine, so it says what THIS engine does today, |
| 8 | including the parts listed under "Open questions" that may change. |
| 9 | |
| 10 | Each test below names the statements it pins in its docstring ("Pins S12, |
| 11 | S40."). Statements an older test already pins are listed, with that test's |
| 12 | name, in the table at the end of the document; |
| 13 | test_every_statement_in_the_document_is_pinned holds the two together, so a |
| 14 | statement added to the page without a test, or a cited test that is renamed, |
| 15 | fails here. |
| 16 | |
| 17 | Everything runs against the real server (scripts/try_package.Sandbox: the ASGI |
| 18 | app in this process, permission enforcement on) with a toy package written |
| 19 | into tmp_path, so what is pinned is the engine, not any shipped app: |
| 20 | |
| 21 | tags (id, name) a plain relation target |
| 22 | parents (id, label, owner_id, total = sum of specs.qty) |
| 23 | locked check parent_gate: no update while label is frozen-total |
| 24 | specs every declaration the write path reads: required, defaults, |
| 25 | bounds, required_when, a guarded state machine, relations (one |
| 26 | with requires), a field permission, formulas (one with its own |
| 27 | bound), unique, locked_when, a locked check and a pre-write hook |
| 28 | |
| 29 | The hook and the checks decide from the record's title ("hook-refuse", |
| 30 | "check-refuse", ...), so one request can break two rules at once and the test |
| 31 | can say which refusal wins. Behaviour the page lists under "Open questions" |
| 32 | is pinned as it is today when that is safe to pin. Where today's outcome is |
| 33 | unsafe, the test asserts the safe outcome and is a strict xfail: the gap is |
| 34 | on record, and a fix turns it into a pass that fails the run until this file |
| 35 | and the page change with it. |
| 36 | """ |
| 37 | |
| 38 | from __future__ import annotations |
| 39 | |
| 40 | import json |
| 41 | import os |
| 42 | import re |
| 43 | import sys |
| 44 | import threading |
| 45 | import time |
| 46 | from datetime import datetime, timezone |
| 47 | from pathlib import Path |
| 48 | |
| 49 | import pytest |
| 50 | |
| 51 | import object_attention |
| 52 | import object_permissions |
| 53 | import object_records |
| 54 | import object_schemas |
| 55 | import object_server |
| 56 | from scripts.try_package import Sandbox |
| 57 | |
| 58 | ROOT = Path(__file__).resolve().parents[1] |
| 59 | DOC = ROOT / "docs" / "dron-write-semantics.md" |
| 60 | SPECS = "/collections/specs/records" |
| 61 | PARENTS = "/collections/parents/records" |
| 62 | TAGS = "/collections/tags/records" |
| 63 | |
| 64 | HOOK = '''\ |
| 65 | import os |
| 66 | |
| 67 | import object_records |
| 68 | |
| 69 | |
| 70 | def _base(): |
| 71 | return os.environ["DBBASIC_DATA_DIR"] |
| 72 | |
| 73 | |
| 74 | def BEFORE_WRITE(request): |
| 75 | record = request["record"] or {} |
| 76 | title = str(record.get("title") or "") |
| 77 | action = request["action"] |
| 78 | # A writer that lands between this request's permission check and its |
| 79 | # write lock: a storage-level update, made from here so the interleaving |
| 80 | # is exact rather than a race the test has to win. |
| 81 | if action == "update" and "race-approve" in title: |
| 82 | object_records.update_collection_record( |
| 83 | "specs", record["id"], {"status": "approved", "note": "n"}, |
| 84 | base_dir=_base(), actor="racer") |
| 85 | if action == "update" and "race-give" in title: |
| 86 | object_records.update_collection_record( |
| 87 | "specs", record["id"], {"owner_id": "bob"}, base_dir=_base(), actor="racer") |
| 88 | if action == "delete" and "race-give" in title: |
| 89 | object_records.update_collection_record( |
| 90 | "specs", record["id"], {"owner_id": "bob"}, base_dir=_base(), actor="racer") |
| 91 | if action == "delete" and "hook-keep" in title: |
| 92 | return {"error": "the hook keeps this row", "status": 422} |
| 93 | if action != "delete" and "hook-refuse" in title: |
| 94 | return {"error": "the hook refuses", "status": 422} |
| 95 | if action == "create" and "hook-forty" in title: |
| 96 | return {"record": {**record, "qty": "40"}} |
| 97 | return None |
| 98 | |
| 99 | |
| 100 | def LOCKED_CHECK(request): |
| 101 | record = request["record"] or {} |
| 102 | title = str(record.get("title") or "") |
| 103 | if request["action"] == "delete": |
| 104 | return {"error": "the check keeps this row"} if "check-keep" in title else None |
| 105 | if "check-refuse" in title: |
| 106 | return {"error": "the check refuses"} |
| 107 | return None |
| 108 | |
| 109 | |
| 110 | def PARENT_CHECK(request): |
| 111 | existing = request["existing"] or {} |
| 112 | if request["action"] == "update" and existing.get("label") == "frozen-total": |
| 113 | return {"error": "this parent's totals are frozen"} |
| 114 | return None |
| 115 | ''' |
| 116 | |
| 117 | SPEC_FIELDS = [ |
| 118 | {"name": "id"}, |
| 119 | {"name": "title", "type": "text", "required": True}, |
| 120 | {"name": "code", "type": "text"}, |
| 121 | {"name": "status", "type": "enum", "enum": ["draft", "approved", "archived"], "default": "draft", |
| 122 | "transitions": { |
| 123 | "draft": ["approved", {"to": "archived", "when": {"owner_id": "$user_id"}}], |
| 124 | "approved": ["archived", {"to": "draft", "when": {"lvl": "high"}}], |
| 125 | "archived": [], |
| 126 | }}, |
| 127 | {"name": "qty", "type": "integer", "validation": {"min": 0, "max": 100}}, |
| 128 | {"name": "price", "type": "number", "validation": {"exclusive_min": 0}}, |
| 129 | {"name": "note", "type": "text", "validation": {"required_when": {"status": "approved"}}}, |
| 130 | {"name": "parent_id", "type": "text", "relation": {"collection": "parents", "requires": "update"}}, |
| 131 | {"name": "tag_id", "type": "text", "relation": {"collection": "tags"}}, |
| 132 | {"name": "owner_id", "type": "text"}, |
| 133 | {"name": "secret", "type": "text", "permissions": {"default": "read"}}, |
| 134 | {"name": "lvl", "type": "text", "default": "low"}, |
| 135 | {"name": "day", "type": "date"}, |
| 136 | {"name": "when_at", "type": "datetime"}, |
| 137 | {"name": "flag", "type": "boolean"}, |
| 138 | {"name": "created_at", "type": "datetime", "read_only": True}, |
| 139 | {"name": "double_qty", "type": "computed", "formula": "qty * 2"}, |
| 140 | {"name": "headroom", "type": "computed", "formula": "100 - qty", "validation": {"min": 10}}, |
| 141 | ] |
| 142 | |
| 143 | OWN_SPECS = {"effect": "allow", "principal": "registered", "actions": ["create", "read", "update", "delete"], |
| 144 | "collection": "specs", "row_filter": {"owner_id": "$user_id"}, "reason": "own rows"} |
| 145 | OWN_PARENTS = {"effect": "allow", "principal": "registered", "actions": ["create", "read", "update"], |
| 146 | "collection": "parents", "row_filter": {"owner_id": "$user_id"}, "reason": "own parents"} |
| 147 | ALL_TAGS = {"effect": "allow", "principal": "registered", "actions": ["create", "read"], |
| 148 | "collection": "tags", "reason": "shared tags"} |
| 149 | |
| 150 | |
| 151 | def write_package(root: Path, *, rules=()) -> Path: |
| 152 | package = root / "app-specs" |
| 153 | for folder in ("schemas", "permissions", "objects/hook"): |
| 154 | (package / folder).mkdir(parents=True, exist_ok=True) |
| 155 | (package / "objects" / "hook" / "specs.py").write_text(HOOK) |
| 156 | schemas = { |
| 157 | "tags": {"name": "tags", "version": 1, "fields": [{"name": "id"}, {"name": "name", "type": "text"}]}, |
| 158 | "parents": {"name": "parents", "version": 1, "fields": [ |
| 159 | {"name": "id"}, {"name": "label", "type": "text"}, {"name": "owner_id", "type": "text"}, |
| 160 | {"name": "total", "type": "computed", |
| 161 | "rollup": {"collection": "specs", "fk_field": "parent_id", "op": "sum", "field": "qty"}}, |
| 162 | ], "locked_checks": [{"name": "parent_gate", "object": "hook_specs", "function": "PARENT_CHECK", |
| 163 | "lock": "parents"}]}, |
| 164 | "specs": {"name": "specs", "version": 1, "fields": SPEC_FIELDS, |
| 165 | "unique": [{"fields": ["code"], "ignore_case": True}], |
| 166 | "locked_when": [{"when": {"status": "approved"}, "except": ["status", "note"]}], |
| 167 | "locked_checks": [{"name": "gate", "object": "hook_specs", "reads": ["parents"], |
| 168 | "lock": "specs"}], |
| 169 | "hooks": {"before_write": "hook_specs"}}, |
| 170 | } |
| 171 | for name, schema in schemas.items(): |
| 172 | (package / "schemas" / f"{name}.json").write_text(json.dumps(schema)) |
| 173 | (package / "permissions" / "rules.json").write_text(json.dumps( |
| 174 | {"rules": [OWN_SPECS, OWN_PARENTS, ALL_TAGS, *rules]})) |
| 175 | (package / "dbbasic-package.json").write_text(json.dumps({ |
| 176 | "id": "app-specs", "name": "Specs", "version": "0.1.0", |
| 177 | "objects": [{"id": "hook_specs", "path": "objects/hook/specs.py"}], |
| 178 | "schemas": [{"collection": name, "path": f"schemas/{name}.json"} for name in schemas], |
| 179 | "permissions": [{"path": "permissions/rules.json"}], |
| 180 | })) |
| 181 | return root |
| 182 | |
| 183 | |
| 184 | def sandbox(tmp_path, *, rules=(), enforce=True) -> Sandbox: |
| 185 | return Sandbox(["app-specs"], packages_dir=write_package(tmp_path / "packages", rules=rules), |
| 186 | enforce=enforce) |
| 187 | |
| 188 | |
| 189 | def people(box, *names): |
| 190 | for name in names: |
| 191 | box.add_user(name) |
| 192 | |
| 193 | |
| 194 | def stored(box, collection, record_id): |
| 195 | return object_records.get_collection_record(collection, record_id, base_dir=box.data_dir) |
| 196 | |
| 197 | |
| 198 | def refusal(answer): |
| 199 | """(status, code or None) of a refused call.""" |
| 200 | status, body = answer |
| 201 | return status, (body.get("code") if isinstance(body, dict) else None) |
| 202 | |
| 203 | |
| 204 | # --- 1. values: missing, null, blank ------------------------------------------- |
| 205 | |
| 206 | |
| 207 | def test_null_is_blank_and_numbers_and_booleans_are_stored_as_their_text(tmp_path): |
| 208 | """Pins S1.""" |
| 209 | with sandbox(tmp_path) as box: |
| 210 | people(box, "ann") |
| 211 | status, body = box.call("ann", "POST", SPECS, {"id": "a", "title": True, "qty": None, "flag": False}) |
| 212 | assert status == 201 |
| 213 | assert (body["record"]["title"], body["record"]["qty"], body["record"]["flag"]) == ("True", "", "false") |
| 214 | # 1.0 is the text "1.0", which is not an integer. |
| 215 | assert box.call("ann", "POST", SPECS, {"id": "b", "title": "t", "qty": 1.0})[1]["error"] == \ |
| 216 | "Record field 'qty' must be an integer" |
| 217 | status, body = box.call("ann", "POST", SPECS, {"id": "c", "title": {"a": 1}}) |
| 218 | assert (status, body["error"]) == (400, "Record field value must be scalar or null: title") |
| 219 | for sent in ({}, {"id": None}, {"id": ""}): |
| 220 | status, body = box.call("ann", "POST", SPECS, {"title": "t", **sent}) |
| 221 | assert status == 201 and re.fullmatch(r"[0-9a-f-]{36}", body["record"]["id"]), body |
| 222 | |
| 223 | |
| 224 | def test_defaults_fill_a_missing_null_or_empty_value_on_create_and_never_on_update(tmp_path): |
| 225 | """Pins S2.""" |
| 226 | with sandbox(tmp_path) as box: |
| 227 | people(box, "ann") |
| 228 | for record_id, sent in (("a", {}), ("b", {"lvl": None}), ("c", {"lvl": ""})): |
| 229 | status, body = box.call("ann", "POST", SPECS, {"id": record_id, "title": "t", **sent}) |
| 230 | assert (status, body["record"]["lvl"]) == (201, "low") |
| 231 | assert box.call("ann", "POST", SPECS, {"id": "d", "title": "t", "lvl": " "})[1]["record"]["lvl"] == " " |
| 232 | status, body = box.call("ann", "PUT", f"{SPECS}/c", {"lvl": None}) |
| 233 | assert (status, body["record"]["lvl"]) == (200, "") |
| 234 | assert box.call("ann", "PUT", f"{SPECS}/c", {"title": "u"})[1]["record"]["lvl"] == "" |
| 235 | |
| 236 | |
| 237 | def test_required_refuses_missing_null_and_empty_and_accepts_spaces(tmp_path): |
| 238 | """Pins S3 (required).""" |
| 239 | with sandbox(tmp_path) as box: |
| 240 | people(box, "ann") |
| 241 | for sent in ({}, {"title": None}, {"title": ""}): |
| 242 | assert box.call("ann", "POST", SPECS, {"id": "a", **sent}) == \ |
| 243 | (400, {"status": "error", "error": "Record field 'title' is required"}) |
| 244 | assert box.call("ann", "POST", SPECS, {"id": "a", "title": " "})[0] == 201 |
| 245 | assert box.call("ann", "PUT", f"{SPECS}/a", {"title": None})[0] == 400 |
| 246 | |
| 247 | |
| 248 | def test_required_when_treats_spaces_as_blank(tmp_path): |
| 249 | """Pins S3 (required_when).""" |
| 250 | with sandbox(tmp_path) as box: |
| 251 | people(box, "ann") |
| 252 | box.call("ann", "POST", SPECS, {"id": "a", "title": "t"}) |
| 253 | for note in (None, "", " "): |
| 254 | status, body = box.call("ann", "PUT", f"{SPECS}/a", {"status": "approved", "note": note}) |
| 255 | assert (status, body["error"]) == (400, "Record field 'note' is required when status is approved") |
| 256 | assert box.call("ann", "PUT", f"{SPECS}/a", {"status": "approved", "note": "n"})[0] == 200 |
| 257 | |
| 258 | |
| 259 | def test_bounds_leave_a_blank_value_to_required_and_spaces_are_a_type_error(tmp_path): |
| 260 | """Pins S3 (bounds).""" |
| 261 | with sandbox(tmp_path) as box: |
| 262 | people(box, "ann") |
| 263 | assert box.call("ann", "POST", SPECS, {"id": "a", "title": "t", "qty": "", "price": ""})[0] == 201 |
| 264 | assert box.call("ann", "POST", SPECS, {"id": "b", "title": "t", "price": " "})[1]["error"] == \ |
| 265 | "Record field 'price' must be a number" |
| 266 | assert box.call("ann", "POST", SPECS, {"id": "b", "title": "t", "qty": " "})[1]["error"] == \ |
| 267 | "Record field 'qty' must be an integer" |
| 268 | assert box.call("ann", "POST", SPECS, {"id": "b", "title": "t", "price": "0"})[1]["error"] == \ |
| 269 | "Record field 'price' must be greater than 0" |
| 270 | |
| 271 | |
| 272 | def test_a_relation_of_spaces_is_not_an_id_and_an_empty_one_is_no_pointer(tmp_path): |
| 273 | """Pins S3 (relation).""" |
| 274 | with sandbox(tmp_path) as box: |
| 275 | people(box, "ann") |
| 276 | assert box.call("ann", "POST", SPECS, {"id": "a", "title": "t", "tag_id": ""})[0] == 201 |
| 277 | for pointer in ("tag_id", "parent_id"): |
| 278 | status, body = box.call("ann", "POST", SPECS, {"id": "b", "title": "t", pointer: " "}) |
| 279 | assert (status, body["error"]) == (400, f"Record field '{pointer}' relation value is not a valid record id") |
| 280 | |
| 281 | |
| 282 | def _with_schema(box, edit, change): |
| 283 | """Make a storage write under an edited specs schema, then put the schema |
| 284 | back: the way a row written before a declaration existed looks.""" |
| 285 | schema = json.loads(json.dumps(object_schemas.get_schema("specs", base_dir=box.data_dir))) |
| 286 | edited = json.loads(json.dumps(schema)) |
| 287 | edit(edited) |
| 288 | object_schemas.replace_schema("specs", edited, base_dir=box.data_dir) |
| 289 | try: |
| 290 | change() |
| 291 | finally: |
| 292 | object_schemas.replace_schema("specs", schema, base_dir=box.data_dir) |
| 293 | |
| 294 | |
| 295 | def _without_transitions(box, change): |
| 296 | def plain(schema): |
| 297 | for field in schema["fields"]: |
| 298 | field.pop("transitions", None) |
| 299 | _with_schema(box, plain, change) |
| 300 | |
| 301 | |
| 302 | def test_a_unique_key_of_spaces_is_no_key(tmp_path): |
| 303 | """Pins S3 (unique).""" |
| 304 | with sandbox(tmp_path) as box: |
| 305 | people(box, "ann") |
| 306 | for record_id in ("a", "b"): |
| 307 | assert box.call("ann", "POST", SPECS, {"id": record_id, "title": "t", "code": " "})[0] == 201 |
| 308 | |
| 309 | |
| 310 | def test_a_blank_state_may_move_to_any_state_but_no_state_may_move_to_blank(tmp_path): |
| 311 | """Pins S3 (transitions).""" |
| 312 | with sandbox(tmp_path) as box: |
| 313 | people(box, "ann") |
| 314 | box.call("ann", "POST", SPECS, {"id": "a", "title": "t"}) |
| 315 | assert box.call("ann", "PUT", f"{SPECS}/a", {"status": ""})[1]["error"] == \ |
| 316 | "Record field 'status' cannot move from 'draft' to '' (allowed: approved, archived)" |
| 317 | _without_transitions(box, lambda: object_records.update_collection_record( |
| 318 | "specs", "a", {"status": ""}, base_dir=box.data_dir)) |
| 319 | assert stored(box, "specs", "a")["status"] == "" |
| 320 | # archived lists no moves out; the move into it is judged from blank. |
| 321 | assert box.call("ann", "PUT", f"{SPECS}/a", {"status": "archived"})[0] == 200 |
| 322 | assert box.call("ann", "PUT", f"{SPECS}/a", {"status": "draft"})[1]["error"] == \ |
| 323 | "Record field 'status' cannot move from 'archived' to 'draft' (allowed: none)" |
| 324 | |
| 325 | |
| 326 | def test_values_are_stored_as_sent_except_booleans(tmp_path): |
| 327 | """Pins S4.""" |
| 328 | with sandbox(tmp_path) as box: |
| 329 | people(box, "ann") |
| 330 | status, body = box.call("ann", "POST", SPECS, {"id": "a", "title": "t", "price": " 5 ", "qty": "+15", |
| 331 | "flag": "Yes"}) |
| 332 | assert status == 201 |
| 333 | assert (body["record"]["price"], body["record"]["qty"], body["record"]["flag"]) == (" 5 ", "+15", "true") |
| 334 | assert body["record"]["double_qty"] == "30" |
| 335 | |
| 336 | |
| 337 | def test_a_key_the_schema_does_not_declare_is_stored_unchecked(tmp_path): |
| 338 | """Pins S5.""" |
| 339 | with sandbox(tmp_path) as box: |
| 340 | people(box, "ann") |
| 341 | assert box.call("ann", "POST", SPECS, {"id": "a", "title": "t", "colour": "red"})[0] == 201 |
| 342 | assert stored(box, "specs", "a")["colour"] == "red" |
| 343 | |
| 344 | |
| 345 | def test_date_and_datetime_accept_what_the_host_python_parses(tmp_path): |
| 346 | """Pins S6. The compact date is the open question: the verdict depends on |
| 347 | the Python the engine runs on.""" |
| 348 | with sandbox(tmp_path) as box: |
| 349 | people(box, "ann") |
| 350 | accepted = [("day", "2026-01-01"), ("when_at", "2026-01-01"), ("when_at", "2026-01-01T10:00:00"), |
| 351 | ("when_at", "2026-01-01T10:00:00Z"), ("when_at", "2026-01-01T10:00:00+05:00"), |
| 352 | ("when_at", "2026-01-01 10:00")] |
| 353 | for number, (field, value) in enumerate(accepted): |
| 354 | status, body = box.call("ann", "POST", SPECS, {"id": f"a{number}", "title": "t", field: value}) |
| 355 | assert (status, body["record"][field]) == (201, value), (field, value) |
| 356 | assert box.call("ann", "POST", SPECS, {"id": "b", "title": "t", "day": "2026-01-01T10:00:00"})[1]["error"] \ |
| 357 | == "Record field 'day' must be a date" |
| 358 | compact = box.call("ann", "POST", SPECS, {"id": "c", "title": "t", "day": "20260101"})[0] |
| 359 | assert compact == (201 if sys.version_info >= (3, 11) else 400) |
| 360 | |
| 361 | |
| 362 | # --- 2-4. the order of a create, an update and a delete --------------------------- |
| 363 | |
| 364 | |
| 365 | def test_a_malformed_create_body_is_refused_before_anyone_is_asked(tmp_path): |
| 366 | """Pins S10.""" |
| 367 | with sandbox(tmp_path) as box: |
| 368 | for body, error in (([1], "JSON body must be an object"), ({}, "Record payload must not be empty"), |
| 369 | ({"title": [1]}, "Record field value must be scalar or null: title"), |
| 370 | ({" title": "x"}, "Record field name has whitespace: ' title'")): |
| 371 | assert box.call("anon", "POST", SPECS, body) == (400, {"status": "error", "error": error}) |
| 372 | assert refusal(box.call("anon", "POST", SPECS, {"title": "x"})) == (403, "forbidden") |
| 373 | # An update asks the collection-level question first, so the same body is a 403. |
| 374 | assert refusal(box.call("anon", "PUT", f"{SPECS}/a", [1])) == (403, "forbidden") |
| 375 | |
| 376 | |
| 377 | def test_a_policy_that_cannot_be_read_refuses_every_write(tmp_path): |
| 378 | """Pins S11.""" |
| 379 | with sandbox(tmp_path) as box: |
| 380 | people(box, "ann") |
| 381 | box.call("ann", "POST", SPECS, {"id": "a", "title": "t"}) |
| 382 | (box.data_dir / "permissions" / "policy.json").write_text("{not json") |
| 383 | for method, path, body in (("POST", SPECS, {"id": "b", "title": "t"}), ("PUT", f"{SPECS}/a", {"title": "u"}), |
| 384 | ("DELETE", f"{SPECS}/a", None)): |
| 385 | assert box.call("ann", method, path, body)[0] == 503, method |
| 386 | assert stored(box, "specs", "a")["title"] == "t" |
| 387 | |
| 388 | |
| 389 | def test_with_enforcement_off_only_the_admin_token_writes(tmp_path): |
| 390 | """Pins S12, S14 (the admin token and a field it may not edit).""" |
| 391 | with sandbox(tmp_path, enforce=False) as box: |
| 392 | people(box, "ann") |
| 393 | assert box.call("ann", "POST", SPECS, {"id": "a", "title": "t"}) == \ |
| 394 | (401, {"status": "error", "error": "Unauthorized"}) |
| 395 | assert box.call("admin", "POST", SPECS, {"id": "a", "title": "t", "secret": "s"})[0] == 201 |
| 396 | |
| 397 | |
| 398 | def test_under_enforcement_a_field_permission_binds_the_admin_token_too(tmp_path): |
| 399 | """Pins S14. Open question: the same request is accepted with enforcement off.""" |
| 400 | with sandbox(tmp_path) as box: |
| 401 | status, body = box.call("admin", "POST", SPECS, {"id": "a", "title": "t", "secret": "s"}) |
| 402 | assert (status, body["code"], body["denied_fields"]) == (403, "forbidden", ["secret"]) |
| 403 | |
| 404 | |
| 405 | # Which refusal wins when a create breaks two rules: (who, body, status, code, |
| 406 | # the start of the error). The list is in pipeline order. |
| 407 | CREATE_PRECEDENCE = [ |
| 408 | ("permission before field permission", "bob", {"id": "x", "title": "t", "owner_id": "ann", "secret": "s"}, |
| 409 | 403, "forbidden", "no matching role rule"), |
| 410 | ("field permission before requires", "ann", {"id": "x", "title": "t", "secret": "s", "parent_id": "pb"}, |
| 411 | 403, "forbidden", "Record field 'secret' is not editable"), |
| 412 | ("requires before the hook", "ann", {"id": "x", "title": "hook-refuse", "parent_id": "pb"}, |
| 413 | 400, None, "Record field 'parent_id' references a missing record"), |
| 414 | ("the hook before validation", "ann", {"id": "x", "title": "hook-refuse", "qty": "abc"}, |
| 415 | 422, "hook_rejected", "the hook refuses"), |
| 416 | ("the first declared field first", "ann", {"id": "x", "title": "", "qty": "abc"}, |
| 417 | 400, None, "Record field 'title' is required"), |
| 418 | ("every field's own checks before required_when", "ann", |
| 419 | {"id": "x", "title": "t", "status": "approved", "day": "soon"}, |
| 420 | 400, None, "Record field 'day' must be a date"), |
| 421 | ("a value before a computed value", "ann", {"id": "x", "title": "t", "qty": "95", "price": "0"}, |
| 422 | 400, None, "Record field 'price' must be greater than 0"), |
| 423 | ("validation before a duplicate id", "ann", {"id": "taken", "title": "t", "qty": "abc"}, |
| 424 | 400, None, "Record field 'qty' must be an integer"), |
| 425 | ("an unstorable value before a type", "ann", {"id": "x", "title": "t\x00", "qty": "abc"}, |
| 426 | 400, None, "Record field 'title' contains a NUL byte"), |
| 427 | ("validation before unique", "ann", {"id": "x", "title": "", "code": "k1"}, |
| 428 | 400, None, "Record field 'title' is required"), |
| 429 | ("a duplicate id before unique", "ann", {"id": "taken", "title": "t", "code": "K1 "}, |
| 430 | 409, None, "Record already exists: specs/taken"), |
| 431 | ("unique before the locked check", "ann", {"id": "x", "title": "check-refuse", "code": "K1"}, |
| 432 | 409, "unique_violation", "Another specs record already has this code"), |
| 433 | ("the locked check last", "ann", {"id": "x", "title": "check-refuse"}, |
| 434 | 409, "check_refused", "the check refuses"), |
| 435 | ] |
| 436 | |
| 437 | |
| 438 | @pytest.mark.parametrize("label,who,body,status,code,error", CREATE_PRECEDENCE, ids=[c[0] for c in CREATE_PRECEDENCE]) |
| 439 | def test_which_refusal_wins_on_a_create(tmp_path, label, who, body, status, code, error): |
| 440 | """Pins S12, S13, S14, S15, S16, S17, S18, S40, S41, S61.""" |
| 441 | with sandbox(tmp_path) as box: |
| 442 | people(box, "ann", "bob") |
| 443 | box.call("bob", "POST", PARENTS, {"id": "pb", "label": "B", "owner_id": "bob"}) |
| 444 | assert box.call("ann", "POST", SPECS, {"id": "taken", "title": "t", "code": "k1"})[0] == 201 |
| 445 | answer_status, answer = box.call(who, "POST", SPECS, body) |
| 446 | assert (answer_status, answer.get("code")) == (status, code), answer |
| 447 | assert answer["error"].startswith(error), answer["error"] |
| 448 | if code == "check_refused": |
| 449 | assert answer["check"] == "gate" |
| 450 | if code == "unique_violation": |
| 451 | assert (answer["fields"], answer["scope"]) == (["code"], []) |
| 452 | |
| 453 | |
| 454 | def test_the_hook_sees_the_record_before_computed_fields_and_validation(tmp_path): |
| 455 | """Pins S16, S70: the hook's transform is what is computed and validated.""" |
| 456 | with sandbox(tmp_path) as box: |
| 457 | people(box, "ann") |
| 458 | status, body = box.call("ann", "POST", SPECS, {"id": "a", "title": "hook-forty", "qty": "1"}) |
| 459 | assert (status, body["record"]["qty"], body["record"]["double_qty"]) == (201, "40", "80") |
| 460 | |
| 461 | |
| 462 | UPDATE_PRECEDENCE = [ |
| 463 | ("collection permission before the lookup", "anon", "missing", {"qty": "1"}, 403, "forbidden", |
| 464 | "no matching role rule"), |
| 465 | ("a missing record before the body's values", "ann", "missing", {"qty": "abc"}, 404, None, |
| 466 | "Record not found: specs/missing"), |
| 467 | ("the stored row's permission", "bob", "locked", {"qty": "1"}, 403, "forbidden", "no matching role rule"), |
| 468 | ("a stale revision before validation", "ann", "locked", {"expected_rev": "stale", "qty": "abc"}, 409, "conflict", |
| 469 | "Record specs/locked has changed since it was read"), |
| 470 | ("validation before locked_when", "ann", "locked", {"qty": "abc"}, 400, None, |
| 471 | "Record field 'qty' must be an integer"), |
| 472 | ("an enum value before its transition", "ann", "locked", {"status": "gone"}, 400, None, |
| 473 | "Record field 'status' must be one of"), |
| 474 | ("a transition before locked_when", "ann", "locked", {"status": "draft", "qty": "5"}, 403, "forbidden", |
| 475 | "Record field 'status' cannot move from 'approved' to 'draft' for this subject"), |
| 476 | ("a type before an unstorable value", "ann", "locked", {"title": "t\x00", "qty": "abc"}, 400, None, |
| 477 | "Record field 'qty' must be an integer"), |
| 478 | ("locked_when before unique", "ann", "locked", {"code": "k1"}, 409, "record_locked", |
| 479 | "This specs record is locked while status is approved: code cannot be changed."), |
| 480 | ("unique before the locked check", "ann", "open", {"title": "check-refuse", "code": "K1"}, 409, |
| 481 | "unique_violation", "Another specs record already has this code"), |
| 482 | ("the locked check last", "ann", "open", {"title": "check-refuse"}, 409, "check_refused", "the check refuses"), |
| 483 | ("the id may not change", "ann", "open", {"id": "other"}, 400, None, "Record id cannot be changed"), |
| 484 | ] |
| 485 | |
| 486 | |
| 487 | @pytest.mark.parametrize("label,who,record_id,body,status,code,error", UPDATE_PRECEDENCE, |
| 488 | ids=[c[0] for c in UPDATE_PRECEDENCE]) |
| 489 | def test_which_refusal_wins_on_an_update(tmp_path, label, who, record_id, body, status, code, error): |
| 490 | """Pins S20, S21, S22, S27, S40, S61.""" |
| 491 | with sandbox(tmp_path) as box: |
| 492 | people(box, "ann", "bob") |
| 493 | box.call("ann", "POST", SPECS, {"id": "taken", "title": "t", "code": "k1"}) |
| 494 | box.call("ann", "POST", SPECS, {"id": "open", "title": "t"}) |
| 495 | # Approved, so frozen but for status and note; its lvl is low, so the |
| 496 | # guarded move back to draft fails. |
| 497 | box.call("ann", "POST", SPECS, {"id": "locked", "title": "t", "code": "lk"}) |
| 498 | assert box.call("ann", "PUT", f"{SPECS}/locked", {"status": "approved", "note": "n"})[0] == 200 |
| 499 | answer_status, answer = box.call(who, "PUT", f"{SPECS}/{record_id}", body) |
| 500 | assert (answer_status, answer.get("code")) == (status, code), answer |
| 501 | assert answer["error"].startswith(error), answer["error"] |
| 502 | |
| 503 | |
| 504 | def test_an_empty_update_is_refused_and_the_urls_own_id_may_be_sent(tmp_path): |
| 505 | """Pins S22.""" |
| 506 | with sandbox(tmp_path) as box: |
| 507 | people(box, "ann") |
| 508 | box.call("ann", "POST", SPECS, {"id": "a", "title": "t"}) |
| 509 | assert box.call("ann", "PUT", f"{SPECS}/a", {}) == \ |
| 510 | (400, {"status": "error", "error": "Record payload must not be empty"}) |
| 511 | assert box.call("ann", "PUT", f"{SPECS}/a", {"id": "a", "title": "u"})[1]["record"]["title"] == "u" |
| 512 | |
| 513 | |
| 514 | def test_a_guarded_move_is_judged_on_the_stored_row_and_the_admin_token_is_not_exempt(tmp_path): |
| 515 | """Pins S27 (guards). Open question: the admin token, which every rule |
| 516 | lets through, is refused a guarded move that does not name it.""" |
| 517 | with sandbox(tmp_path) as box: |
| 518 | people(box, "ann") |
| 519 | box.call("ann", "POST", SPECS, {"id": "a", "title": "t"}) |
| 520 | status, body = box.call("admin", "PUT", f"{SPECS}/a", {"status": "archived"}) |
| 521 | assert (status, body["code"]) == (403, "forbidden") |
| 522 | assert box.call("ann", "PUT", f"{SPECS}/a", {"status": "archived"})[0] == 200 |
| 523 | |
| 524 | |
| 525 | def test_a_create_may_start_in_any_state_and_a_storage_writer_skips_guards_not_the_map(tmp_path): |
| 526 | """Pins S27 (transitions on create), S55.""" |
| 527 | with sandbox(tmp_path) as box: |
| 528 | people(box, "ann") |
| 529 | assert box.call("ann", "POST", SPECS, {"id": "a", "title": "t", "status": "archived"})[0] == 201 |
| 530 | object_records.create_collection_record("specs", {"id": "b", "title": "t", "owner_id": "ann"}, |
| 531 | base_dir=box.data_dir) |
| 532 | assert object_records.update_collection_record( |
| 533 | "specs", "b", {"status": "archived"}, base_dir=box.data_dir)["status"] == "archived" |
| 534 | with pytest.raises(object_records.InvalidRecordPayloadError, match="cannot move from 'archived'"): |
| 535 | object_records.update_collection_record("specs", "b", {"status": "draft"}, base_dir=box.data_dir) |
| 536 | |
| 537 | |
| 538 | def test_a_caller_with_a_row_filtered_grant_can_tell_a_missing_id_from_a_forbidden_one(tmp_path): |
| 539 | """Pins S21. Open question: a read answers 404 for both.""" |
| 540 | with sandbox(tmp_path) as box: |
| 541 | people(box, "ann", "bob") |
| 542 | box.call("ann", "POST", SPECS, {"id": "a", "title": "t"}) |
| 543 | assert refusal(box.call("bob", "PUT", f"{SPECS}/a", {"qty": "1"})) == (403, "forbidden") |
| 544 | assert refusal(box.call("bob", "PUT", f"{SPECS}/nope", {"qty": "1"})) == (404, None) |
| 545 | assert refusal(box.call("bob", "DELETE", f"{SPECS}/a")) == (403, "forbidden") |
| 546 | assert refusal(box.call("bob", "DELETE", f"{SPECS}/nope")) == (404, None) |
| 547 | assert refusal(box.call("bob", "GET", f"{SPECS}/a")) == (404, None) |
| 548 | |
| 549 | |
| 550 | def test_a_delete_asks_the_hook_before_locked_when_and_the_locked_check_last(tmp_path): |
| 551 | """Pins S30, S40 (delete).""" |
| 552 | with sandbox(tmp_path) as box: |
| 553 | people(box, "ann") |
| 554 | box.call("ann", "POST", SPECS, {"id": "a", "title": "hook-keep"}) |
| 555 | box.call("ann", "PUT", f"{SPECS}/a", {"status": "approved", "note": "n"}) |
| 556 | assert refusal(box.call("ann", "DELETE", f"{SPECS}/a")) == (422, "hook_rejected") |
| 557 | box.call("ann", "POST", SPECS, {"id": "b", "title": "t"}) |
| 558 | box.call("ann", "PUT", f"{SPECS}/b", {"status": "approved", "note": "n"}) |
| 559 | status, body = box.call("ann", "DELETE", f"{SPECS}/b") |
| 560 | assert (status, body["code"], body["fields"]) == (409, "record_locked", []) |
| 561 | box.call("ann", "POST", SPECS, {"id": "c", "title": "check-keep"}) |
| 562 | status, body = box.call("ann", "DELETE", f"{SPECS}/c") |
| 563 | assert (status, body["code"], body["check"]) == (409, "check_refused", "gate") |
| 564 | |
| 565 | |
| 566 | # --- 5. inside and outside the lock ------------------------------------------------ |
| 567 | |
| 568 | |
| 569 | def test_locked_when_is_judged_on_the_row_under_the_lock(tmp_path): |
| 570 | """Pins S53. A storage-level writer approves the row between this |
| 571 | request's gates and its write lock (the hook makes that write, so the |
| 572 | interleaving is exact, not a race the test has to win). The request is |
| 573 | refused as a changed row, its retry as an edit to the approved row.""" |
| 574 | with sandbox(tmp_path) as box: |
| 575 | people(box, "ann") |
| 576 | box.call("ann", "POST", SPECS, {"id": "a", "title": "t", "qty": "1"}) |
| 577 | status, body = box.call("ann", "PUT", f"{SPECS}/a", {"title": "race-approve", "qty": "2"}) |
| 578 | assert (status, body["code"]) == (409, "conflict") |
| 579 | assert stored(box, "specs", "a")["status"] == "approved" |
| 580 | status, body = box.call("ann", "PUT", f"{SPECS}/a", {"qty": "2"}) |
| 581 | assert (status, body["code"]) == (409, "record_locked") |
| 582 | assert stored(box, "specs", "a")["qty"] == "1" |
| 583 | |
| 584 | |
| 585 | def test_a_row_that_changes_after_its_gates_is_refused_as_a_conflict(tmp_path): |
| 586 | """Pins S52, S61. A storage-level writer gives ann's row to bob between |
| 587 | the gates of ann's request and its write lock (from the hook, so the |
| 588 | interleaving is exact). Neither her update nor her delete lands; both |
| 589 | are a retryable 409 conflict, and her retry is judged on bob's row.""" |
| 590 | with sandbox(tmp_path) as box: |
| 591 | people(box, "ann", "bob") |
| 592 | box.call("ann", "POST", SPECS, {"id": "b", "title": "t", "qty": "1"}) |
| 593 | status, body = box.call("ann", "PUT", f"{SPECS}/b", {"title": "race-give", "qty": "2"}) |
| 594 | assert stored(box, "specs", "b")["owner_id"] == "bob" |
| 595 | assert (status, body.get("code"), stored(box, "specs", "b")["qty"]) == (409, "conflict", "1") |
| 596 | assert body["error"] == "Record specs/b changed while this request was being checked; read it again and retry." |
| 597 | assert refusal(box.call("ann", "PUT", f"{SPECS}/b", {"qty": "2"})) == (403, "forbidden") |
| 598 | |
| 599 | box.call("ann", "POST", SPECS, {"id": "d", "title": "race-give"}) |
| 600 | assert refusal(box.call("ann", "DELETE", f"{SPECS}/d")) == (409, "conflict") |
| 601 | assert stored(box, "specs", "d")["owner_id"] == "bob" |
| 602 | assert refusal(box.call("ann", "DELETE", f"{SPECS}/d")) == (403, "forbidden") |
| 603 | |
| 604 | |
| 605 | def test_a_write_is_refused_when_the_row_under_the_lock_is_not_the_judged_row(tmp_path): |
| 606 | """Pins S52 at storage: judged_rev is checked under the lock for update and |
| 607 | delete, and a refusal writes nothing.""" |
| 608 | with sandbox(tmp_path) as box: |
| 609 | object_records.create_collection_record("specs", {"id": "a", "title": "t", "owner_id": "ann"}, |
| 610 | base_dir=box.data_dir) |
| 611 | judged = object_records.compute_record_rev(stored(box, "specs", "a")) |
| 612 | object_records.update_collection_record("specs", "a", {"qty": "5"}, base_dir=box.data_dir) |
| 613 | with pytest.raises(object_records.RecordChangedError): |
| 614 | object_records.update_collection_record("specs", "a", {"qty": "6"}, base_dir=box.data_dir, |
| 615 | judged_rev=judged) |
| 616 | with pytest.raises(object_records.RecordChangedError): |
| 617 | object_records.delete_collection_record("specs", "a", base_dir=box.data_dir, judged_rev=judged) |
| 618 | assert stored(box, "specs", "a")["qty"] == "5" |
| 619 | current = object_records.compute_record_rev(stored(box, "specs", "a")) |
| 620 | assert object_records.update_collection_record("specs", "a", {"qty": "6"}, base_dir=box.data_dir, |
| 621 | judged_rev=current)["qty"] == "6" |
| 622 | current = object_records.compute_record_rev(stored(box, "specs", "a")) |
| 623 | object_records.delete_collection_record("specs", "a", base_dir=box.data_dir, judged_rev=current) |
| 624 | with pytest.raises(object_records.RecordNotFoundError): |
| 625 | stored(box, "specs", "a") |
| 626 | |
| 627 | |
| 628 | def test_a_relation_is_checked_without_its_targets_lock(tmp_path): |
| 629 | """Pins S54: a create pointing at a tag completes while another writer |
| 630 | holds the tags file lock, so nothing stops the tag being deleted between |
| 631 | the existence check and the append.""" |
| 632 | with sandbox(tmp_path) as box: |
| 633 | box.call("admin", "POST", TAGS, {"id": "t1", "name": "x"}) |
| 634 | held, release = threading.Event(), threading.Event() |
| 635 | |
| 636 | def hold(): |
| 637 | with object_records._records_file_lock(object_records.collection_records_file("tags", box.data_dir)): |
| 638 | held.set() |
| 639 | release.wait(10) |
| 640 | |
| 641 | holder = threading.Thread(target=hold) |
| 642 | holder.start() |
| 643 | try: |
| 644 | assert held.wait(5) |
| 645 | done = [] |
| 646 | writer = threading.Thread(target=lambda: done.append(object_records.create_collection_record( |
| 647 | "specs", {"id": "a", "title": "t", "tag_id": "t1"}, base_dir=box.data_dir))) |
| 648 | writer.start() |
| 649 | writer.join(5) |
| 650 | assert done, "the create waited for the target collection's lock" |
| 651 | finally: |
| 652 | release.set() |
| 653 | holder.join(5) |
| 654 | |
| 655 | |
| 656 | def test_a_deleted_target_leaves_a_pointer_that_blocks_every_later_update(tmp_path): |
| 657 | """Pins S54, S80 (relations). Open question.""" |
| 658 | with sandbox(tmp_path) as box: |
| 659 | people(box, "ann") |
| 660 | box.call("admin", "POST", TAGS, {"id": "t1", "name": "x"}) |
| 661 | box.call("ann", "POST", SPECS, {"id": "a", "title": "t", "tag_id": "t1"}) |
| 662 | assert box.call("admin", "DELETE", f"{TAGS}/t1")[0] == 200 |
| 663 | assert box.call("ann", "PUT", f"{SPECS}/a", {"title": "u"}) == \ |
| 664 | (400, {"status": "error", "error": "Record field 'tag_id' references a missing record: tags/t1"}) |
| 665 | assert box.call("ann", "PUT", f"{SPECS}/a", {"title": "u", "tag_id": ""})[0] == 200 |
| 666 | |
| 667 | |
| 668 | # --- 6. what a refusal guarantees --------------------------------------------------- |
| 669 | |
| 670 | |
| 671 | def _files(root: Path) -> dict[str, bytes]: |
| 672 | return {str(path.relative_to(root)): path.read_bytes() for path in sorted(root.rglob("*")) if path.is_file()} |
| 673 | |
| 674 | |
| 675 | # What a refused write may still leave: empty lock files, the permission audit |
| 676 | # line and the hook's execution log line. Nothing a reader of the data sees. |
| 677 | MAY_CHANGE = re.compile(r"(^|/)\.[^/]*\.lock$|^\.locks/|^permissions/audit\.jsonl$|^logs/hook_specs/") |
| 678 | |
| 679 | REFUSED = [ |
| 680 | ("validation", "POST", "", {"id": "x", "title": "", "qty": "3", "parent_id": "p1"}), |
| 681 | ("the hook", "POST", "", {"id": "x", "title": "hook-refuse", "qty": "3", "parent_id": "p1"}), |
| 682 | ("unique", "POST", "", {"id": "x", "title": "t", "code": "k1", "qty": "3", "parent_id": "p1"}), |
| 683 | ("a locked check", "POST", "", {"id": "x", "title": "check-refuse", "qty": "3", "parent_id": "p1"}), |
| 684 | ("a field permission", "POST", "", {"id": "x", "title": "t", "secret": "s", "parent_id": "p1"}), |
| 685 | ("locked_when", "PUT", "/held", {"qty": "9"}), |
| 686 | ("a transition", "PUT", "/held", {"status": "gone"}), |
| 687 | ("a locked delete", "DELETE", "/held", None), |
| 688 | ] |
| 689 | |
| 690 | |
| 691 | @pytest.mark.parametrize("label,method,suffix,body", REFUSED, ids=[c[0] for c in REFUSED]) |
| 692 | def test_a_refusal_writes_no_record_change_index_or_rollup_and_publishes_nothing( |
| 693 | tmp_path, monkeypatch, label, method, suffix, body): |
| 694 | """Pins S60.""" |
| 695 | with sandbox(tmp_path) as box: |
| 696 | people(box, "ann") |
| 697 | box.call("ann", "POST", PARENTS, {"id": "p1", "label": "P", "owner_id": "ann"}) |
| 698 | box.call("ann", "POST", SPECS, {"id": "held", "title": "t", "code": "k1", "qty": "2", "parent_id": "p1"}) |
| 699 | box.call("ann", "PUT", f"{SPECS}/held", {"status": "approved", "note": "n"}) |
| 700 | published = [] |
| 701 | monkeypatch.setattr(object_server, "_publish_record_change_event", |
| 702 | lambda change, record=None: published.append(change)) |
| 703 | before = _files(box.data_dir) |
| 704 | status, _ = box.call("ann", method, SPECS + suffix, body) |
| 705 | assert status >= 400 |
| 706 | after = _files(box.data_dir) |
| 707 | changed = [name for name in sorted(set(before) | set(after)) if before.get(name) != after.get(name)] |
| 708 | assert [name for name in changed if not MAY_CHANGE.search(name)] == [] |
| 709 | assert published == [] |
| 710 | assert stored(box, "parents", "p1")["total"] == "2" |
| 711 | # The same write, allowed, does change those files and publish. |
| 712 | assert box.call("ann", "POST", SPECS, {"id": "y", "title": "t", "qty": "3", "parent_id": "p1"})[0] == 201 |
| 713 | assert len(published) == 1 and stored(box, "parents", "p1")["total"] == "5" |
| 714 | |
| 715 | |
| 716 | # --- 7. computed fields, formulas and rollups -------------------------------------- |
| 717 | |
| 718 | |
| 719 | def test_a_computed_result_is_validated_like_any_value(tmp_path): |
| 720 | """Pins S72: headroom = 100 - qty must be at least 10.""" |
| 721 | with sandbox(tmp_path) as box: |
| 722 | people(box, "ann") |
| 723 | assert box.call("ann", "POST", SPECS, {"id": "a", "title": "t", "qty": "95"}) == \ |
| 724 | (400, {"status": "error", "error": "Record field 'headroom' is below min"}) |
| 725 | assert box.call("ann", "POST", SPECS, {"id": "a", "title": "t", "qty": "90"})[1]["record"]["headroom"] == "10" |
| 726 | # A blank operand breaks the formula: blank, and blank is not checked. |
| 727 | assert box.call("ann", "POST", SPECS, {"id": "b", "title": "t"})[1]["record"]["headroom"] == "" |
| 728 | |
| 729 | |
| 730 | def test_a_client_may_not_send_a_read_only_field_even_blank(tmp_path): |
| 731 | """Pins S73.""" |
| 732 | with sandbox(tmp_path) as box: |
| 733 | people(box, "ann") |
| 734 | assert box.call("ann", "POST", SPECS, {"id": "a", "title": "t", "created_at": ""})[1]["error"] == \ |
| 735 | "Record field 'created_at' is computed or read-only and cannot be written" |
| 736 | |
| 737 | |
| 738 | def test_a_rollup_refresh_the_parent_refuses_is_dropped_and_the_child_stands(tmp_path): |
| 739 | """Pins S74, S76. Open question: the parent's total is stale and nothing says so.""" |
| 740 | with sandbox(tmp_path) as box: |
| 741 | people(box, "ann") |
| 742 | box.call("ann", "POST", PARENTS, {"id": "frozen", "label": "frozen-total", "owner_id": "ann"}) |
| 743 | box.call("ann", "POST", PARENTS, {"id": "open", "label": "open", "owner_id": "ann"}) |
| 744 | assert box.call("ann", "POST", SPECS, {"id": "a", "title": "t", "qty": "7", "parent_id": "frozen"})[0] == 201 |
| 745 | assert box.call("ann", "POST", SPECS, {"id": "b", "title": "t", "qty": "7", "parent_id": "open"})[0] == 201 |
| 746 | assert stored(box, "parents", "frozen")["total"] == "0" |
| 747 | assert stored(box, "parents", "open")["total"] == "7" |
| 748 | |
| 749 | |
| 750 | # --- 8. a partial update ------------------------------------------------------------ |
| 751 | |
| 752 | |
| 753 | def test_an_update_validates_the_whole_row_it_would_store(tmp_path): |
| 754 | """Pins S80 (validation): a row that breaks a bound declared after it was |
| 755 | written is refused on an edit that does not touch the field.""" |
| 756 | with sandbox(tmp_path) as box: |
| 757 | people(box, "ann") |
| 758 | box.call("ann", "POST", SPECS, {"id": "a", "title": "t", "qty": "50"}) |
| 759 | schema = json.loads(json.dumps(object_schemas.get_schema("specs", base_dir=box.data_dir))) |
| 760 | for field in schema["fields"]: |
| 761 | if field["name"] == "qty": |
| 762 | field["validation"] = {"min": 0, "max": 10} |
| 763 | object_schemas.replace_schema("specs", schema, base_dir=box.data_dir) |
| 764 | assert box.call("ann", "PUT", f"{SPECS}/a", {"title": "u"})[1]["error"] == "Record field 'qty' is above max" |
| 765 | |
| 766 | |
| 767 | def test_requires_is_asked_only_of_a_pointer_the_update_changes(tmp_path): |
| 768 | """Pins S80 (requires).""" |
| 769 | with sandbox(tmp_path) as box: |
| 770 | people(box, "ann", "bob") |
| 771 | box.call("ann", "POST", PARENTS, {"id": "p1", "label": "P", "owner_id": "ann"}) |
| 772 | box.call("ann", "POST", SPECS, {"id": "a", "title": "t", "parent_id": "p1"}) |
| 773 | object_records.update_collection_record("parents", "p1", {"owner_id": "bob"}, base_dir=box.data_dir) |
| 774 | assert box.call("ann", "PUT", f"{SPECS}/a", {"title": "u"})[0] == 200 |
| 775 | assert box.call("ann", "PUT", f"{SPECS}/a", {"title": "v", "parent_id": "p1"})[0] == 200 |
| 776 | box.call("ann", "POST", PARENTS, {"id": "p2", "label": "Q", "owner_id": "ann"}) |
| 777 | object_records.update_collection_record("parents", "p2", {"owner_id": "bob"}, base_dir=box.data_dir) |
| 778 | assert box.call("ann", "PUT", f"{SPECS}/a", {"parent_id": "p2"})[1]["error"] == \ |
| 779 | "Record field 'parent_id' references a missing record: parents/p2" |
| 780 | |
| 781 | |
| 782 | def test_requires_refuses_a_target_the_writer_may_read_but_not_update(tmp_path): |
| 783 | """Pins S15 (requires: unreadable is missing, readable but not updatable is a 403).""" |
| 784 | readable = {"effect": "allow", "principal": "registered", "actions": ["read"], "collection": "parents", |
| 785 | "reason": "everyone sees parents"} |
| 786 | with sandbox(tmp_path, rules=[readable]) as box: |
| 787 | people(box, "ann", "bob") |
| 788 | box.call("bob", "POST", PARENTS, {"id": "pb", "label": "B", "owner_id": "bob"}) |
| 789 | status, body = box.call("ann", "POST", SPECS, {"id": "a", "title": "t", "parent_id": "pb"}) |
| 790 | assert (status, body["code"], body["field"]) == (403, "forbidden", "parent_id") |
| 791 | |
| 792 | |
| 793 | def test_an_update_that_changes_no_value_does_not_run_a_locked_check(tmp_path): |
| 794 | """Pins S80 (locked_checks): the check runs when any value of the row, |
| 795 | computed ones included, would differ; it is then handed the whole row.""" |
| 796 | with sandbox(tmp_path) as box: |
| 797 | people(box, "ann") |
| 798 | box.call("ann", "POST", SPECS, {"id": "a", "title": "t", "qty": "1"}) |
| 799 | |
| 800 | def unchecked(schema): |
| 801 | schema.pop("locked_checks", None) |
| 802 | _with_schema(box, unchecked, lambda: object_records.update_collection_record( |
| 803 | "specs", "a", {"title": "check-refuse"}, base_dir=box.data_dir)) |
| 804 | assert box.call("ann", "PUT", f"{SPECS}/a", {"title": "check-refuse", "qty": "1"})[0] == 200 |
| 805 | assert refusal(box.call("ann", "PUT", f"{SPECS}/a", {"qty": "2"})) == (409, "check_refused") |
| 806 | |
| 807 | |
| 808 | def test_unique_and_locked_when_count_only_what_the_update_changes(tmp_path): |
| 809 | """Pins S80 (unique, locked_when, transitions): a key sent back with other |
| 810 | spacing or case is the same key, and a frozen field or a state sent back |
| 811 | unchanged is no change.""" |
| 812 | with sandbox(tmp_path) as box: |
| 813 | people(box, "ann") |
| 814 | box.call("ann", "POST", SPECS, {"id": "a", "title": "t", "code": "k1", "qty": "1"}) |
| 815 | box.call("ann", "PUT", f"{SPECS}/a", {"status": "approved", "note": "n"}) |
| 816 | # status sent back unchanged is no move, though approved -> approved is not listed. |
| 817 | status, body = box.call("ann", "PUT", f"{SPECS}/a", {"title": "t", "qty": "1", "note": "m", |
| 818 | "status": "approved"}) |
| 819 | assert status == 200 |
| 820 | box.call("ann", "POST", SPECS, {"id": "b", "title": "t", "code": "k2"}) |
| 821 | assert box.call("ann", "PUT", f"{SPECS}/b", {"code": " K2 "})[0] == 200 |
| 822 | |
| 823 | |
| 824 | # --- 9. time ------------------------------------------------------------------------- |
| 825 | |
| 826 | |
| 827 | class _Clock(datetime): |
| 828 | """datetime with a fixed now(): 2026-06-15 03:00 UTC.""" |
| 829 | |
| 830 | FIXED = datetime(2026, 6, 15, 3, 0, tzinfo=timezone.utc) |
| 831 | |
| 832 | @classmethod |
| 833 | def now(cls, tz=None): |
| 834 | return cls.FIXED.astimezone(tz) if tz else cls.FIXED.replace(tzinfo=None) |
| 835 | |
| 836 | |
| 837 | def _local_zone(name: str): |
| 838 | """Set the process time zone (POSIX TZ string, no tz database needed); |
| 839 | return a function that puts it back.""" |
| 840 | previous = os.environ.get("TZ") |
| 841 | os.environ["TZ"] = name |
| 842 | time.tzset() |
| 843 | |
| 844 | def restore(): |
| 845 | if previous is None: |
| 846 | os.environ.pop("TZ", None) |
| 847 | else: |
| 848 | os.environ["TZ"] = previous |
| 849 | time.tzset() |
| 850 | return restore |
| 851 | |
| 852 | |
| 853 | def test_created_at_is_stamped_from_the_utc_clock_whatever_the_servers_zone(tmp_path, monkeypatch): |
| 854 | """Pins S90.""" |
| 855 | data = tmp_path / "data" |
| 856 | for name, kind in (("stamps", "datetime"), ("days", "date")): |
| 857 | object_schemas.replace_schema(name, {"name": name, "fields": [ |
| 858 | {"name": "id"}, {"name": "created_at", "type": kind, "read_only": True}]}, base_dir=data) |
| 859 | monkeypatch.setattr(object_records, "datetime", _Clock) |
| 860 | restore = _local_zone("AOE+12") # local time is UTC-12: 2026-06-14 15:00 |
| 861 | try: |
| 862 | stamp = object_records.create_collection_record("stamps", {"id": "a"}, base_dir=data)["created_at"] |
| 863 | day = object_records.create_collection_record("days", {"id": "a"}, base_dir=data)["created_at"] |
| 864 | kept = object_records.create_collection_record("stamps", {"id": "b", "created_at": "2020-01-01"}, |
| 865 | base_dir=data, preserve_read_only=True)["created_at"] |
| 866 | finally: |
| 867 | restore() |
| 868 | assert stamp == "2026-06-15T03:00:00Z" |
| 869 | assert day == "2026-06-15" |
| 870 | assert kept == "2020-01-01" |
| 871 | |
| 872 | |
| 873 | def test_a_rule_window_reads_a_bound_without_an_offset_as_utc(tmp_path): |
| 874 | """Pins S91.""" |
| 875 | subject = object_permissions.PermissionSubject(user_id="ann") |
| 876 | |
| 877 | def allowed(at, **window): |
| 878 | policy = object_permissions.PermissionPolicy(access_mode="role_based", rules=( |
| 879 | object_permissions.PermissionRule.allow("user:ann", ["read"], collection="specs", **window),)) |
| 880 | return object_permissions.check_permission(subject, "read", policy=policy, collection="specs", |
| 881 | now=at).allowed |
| 882 | |
| 883 | midnight = datetime(2026, 7, 1, tzinfo=timezone.utc) |
| 884 | second_before = datetime(2026, 6, 30, 23, 59, 59, tzinfo=timezone.utc) |
| 885 | for bound in ("2026-07-01", "2026-07-01T00:00:00", "2026-07-01T00:00:00Z", "2026-07-01T02:00:00+02:00"): |
| 886 | assert allowed(second_before, expires_at=bound) and not allowed(midnight, expires_at=bound), bound |
| 887 | assert allowed(midnight, valid_from=bound) and not allowed(second_before, valid_from=bound), bound |
| 888 | restore = _local_zone("AOE+12") |
| 889 | try: |
| 890 | assert not allowed(midnight, expires_at="2026-07-01T00:00:00") |
| 891 | finally: |
| 892 | restore() |
| 893 | |
| 894 | |
| 895 | def test_an_ordered_comparison_reads_dates_and_datetimes_in_utc(): |
| 896 | """Pins S92 at the engine function rules, guards and attention counts share.""" |
| 897 | subject = object_permissions.PermissionSubject(user_id="ann") |
| 898 | |
| 899 | def matches(stored, op, value): |
| 900 | return object_permissions.record_matches_filter({"f": stored}, {"f": {"op": op, "value": value}}, subject) |
| 901 | |
| 902 | for stored in ("2026-05-01T10:00:00Z", "2026-05-01T10:00:00+00:00", "2026-05-01T10:00:00"): |
| 903 | assert matches(stored, "gte", "2000-01-01") and matches(stored, "gt", "2000-01-01"), stored |
| 904 | assert matches(stored, "lte", "2999-01-01") and matches(stored, "lt", "2999-01-01"), stored |
| 905 | assert not matches(stored, "lt", "2000-01-01") and not matches(stored, "gt", "2999-01-01"), stored |
| 906 | # A date alone is UTC midnight, either way round. |
| 907 | assert matches(stored, "gte", "2026-05-01") and matches(stored, "lt", "2026-05-02"), stored |
| 908 | assert matches("2026-05-01", "lte", stored) and not matches("2026-05-01", "gte", stored), stored |
| 909 | # No offset is UTC, so a naive and a zoned value are the same instant. |
| 910 | assert matches("2026-05-01T10:00:00", "gte", "2026-05-01T10:00:00Z") |
| 911 | assert matches("2026-05-01T10:00:00", "lte", "2026-05-01T10:00:00Z") |
| 912 | assert matches("2026-05-01T10:00:00Z", "gt", "2026-05-01T11:00:00+05:00") # 06:00 UTC |
| 913 | assert matches("2026-05-01", "lt", "2026-05-02") |
| 914 | assert matches("9", "lt", "10") # numbers before text |
| 915 | assert not matches("2026-05-01T10:00:00Z", "eq", "2026-05-01T10:00:00+00:00") # eq is the text |
| 916 | |
| 917 | |
| 918 | def test_a_value_that_cannot_be_compared_matches_no_allow_and_holds_a_deny(): |
| 919 | """Pins S95 at the engine function, in both readings.""" |
| 920 | subject = object_permissions.PermissionSubject(user_id="ann") |
| 921 | cases = [ # (stored value or MISSING, bound) |
| 922 | ("", "2026-01-01"), ("soon", "2026-01-01"), (None, "2026-01-01"), ("", "3"), ("abc", "3"), |
| 923 | ("2026-05-01", "3"), ("7", "$account_id"), ("7", "$accessible_projects"), |
| 924 | ] |
| 925 | for stored, bound in cases: |
| 926 | record = {} if stored is None else {"f": stored} |
| 927 | for op in ("gte", "gt", "lte", "lt"): |
| 928 | row_filter = {"f": {"op": op, "value": bound}} |
| 929 | assert object_permissions.record_matches_filter(record, row_filter, subject) is False, (stored, bound) |
| 930 | assert object_permissions._record_matches_filter(record, row_filter, subject, unknown=True), \ |
| 931 | (stored, bound) |
| 932 | # The deny's other conditions still decide: one that is false spares the row. |
| 933 | spared = {**row_filter, "owner_id": "bob"} |
| 934 | assert not object_permissions._record_matches_filter( |
| 935 | {**record, "owner_id": "ann"}, spared, subject, unknown=True), (stored, bound) |
| 936 | # A plain-text bound is compared as text, as before: it can always be judged. |
| 937 | assert object_permissions.record_matches_filter({"f": "apple"}, {"f": {"op": "lt", "value": "b"}}, subject) |
| 938 | assert not object_permissions._record_matches_filter( |
| 939 | {"f": "cherry"}, {"f": {"op": "lt", "value": "b"}}, subject, unknown=True) |
| 940 | |
| 941 | |
| 942 | def test_an_ordered_comparison_of_two_numbers_is_a_float_comparison(): |
| 943 | """Pins S94: two integers a formula tells apart compare equal here.""" |
| 944 | subject = object_permissions.PermissionSubject(user_id="ann") |
| 945 | record = {"f": "9007199254740993"} |
| 946 | assert not object_permissions.record_matches_filter(record, {"f": {"op": "gt", "value": "9007199254740992"}}, |
| 947 | subject) |
| 948 | assert object_permissions.record_matches_filter(record, {"f": {"op": "lte", "value": "9007199254740992"}}, |
| 949 | subject) |
| 950 | |
| 951 | |
| 952 | DATED_RULES = [ |
| 953 | {"effect": "allow", "principal": "registered", "actions": ["read"], "collection": "specs", |
| 954 | "row_filter": {"when_at": {"op": "gte", "value": "2000-01-01"}}, "reason": "dated rows are public"}, |
| 955 | {"effect": "deny", "principal": "registered", "actions": ["update"], "collection": "specs", |
| 956 | "row_filter": {"when_at": {"op": "lt", "value": "2999-01-01"}}, "reason": "dated rows are settled"}, |
| 957 | ] |
| 958 | |
| 959 | |
| 960 | def test_a_date_bound_grants_and_refuses_a_naive_datetime(tmp_path): |
| 961 | """Pins S92 over HTTP: the half that works.""" |
| 962 | with sandbox(tmp_path, rules=DATED_RULES) as box: |
| 963 | people(box, "ann", "bob") |
| 964 | object_records.create_collection_record( |
| 965 | "specs", {"id": "naive", "title": "t", "owner_id": "ann", "when_at": "2026-05-01T10:00:00"}, |
| 966 | base_dir=box.data_dir) |
| 967 | assert box.call("bob", "GET", f"{SPECS}/naive")[0] == 200 |
| 968 | assert refusal(box.call("ann", "PUT", f"{SPECS}/naive", {"title": "u"})) == (403, "forbidden") |
| 969 | |
| 970 | |
| 971 | def test_a_date_bound_grants_on_a_zoned_datetime_as_an_instant(tmp_path): |
| 972 | """Pins S92 over HTTP: an allow with a date bound matches a value carrying |
| 973 | a zone by comparing instants (the date is UTC midnight).""" |
| 974 | with sandbox(tmp_path, rules=DATED_RULES) as box: |
| 975 | people(box, "ann", "bob") |
| 976 | object_records.create_collection_record( |
| 977 | "specs", {"id": "zoned", "title": "t", "owner_id": "ann", "when_at": "2026-05-01T10:00:00Z"}, |
| 978 | base_dir=box.data_dir) |
| 979 | assert box.call("bob", "GET", f"{SPECS}/zoned")[0] == 200 |
| 980 | |
| 981 | |
| 982 | def test_a_date_bound_deny_refuses_a_zoned_datetime(tmp_path): |
| 983 | """Pins S92: a deny with a date bound refuses a row stamped with a zone, |
| 984 | the shape this engine stamps created_at in.""" |
| 985 | with sandbox(tmp_path, rules=DATED_RULES) as box: |
| 986 | people(box, "ann") |
| 987 | object_records.create_collection_record( |
| 988 | "specs", {"id": "zoned", "title": "t", "owner_id": "ann", "when_at": "2026-05-01T10:00:00Z"}, |
| 989 | base_dir=box.data_dir) |
| 990 | assert refusal(box.call("ann", "PUT", f"{SPECS}/zoned", {"title": "u"})) == (403, "forbidden") |
| 991 | assert stored(box, "specs", "zoned")["title"] == "t" |
| 992 | |
| 993 | |
| 994 | def test_a_row_the_date_bound_cannot_judge_is_not_granted_and_stays_denied(tmp_path): |
| 995 | """Pins S95 over HTTP: a blank when_at is neither before nor after a date, |
| 996 | so the allow does not grant it and the deny refuses it; a deny whose |
| 997 | other condition is false still spares it.""" |
| 998 | spared = [{**DATED_RULES[0]}, {**DATED_RULES[1], "row_filter": {**DATED_RULES[1]["row_filter"], |
| 999 | "lvl": "settled"}}] |
| 1000 | with sandbox(tmp_path, rules=DATED_RULES) as box: |
| 1001 | people(box, "ann", "bob") |
| 1002 | box.call("ann", "POST", SPECS, {"id": "blank", "title": "t"}) |
| 1003 | assert box.call("bob", "GET", f"{SPECS}/blank")[0] == 404 |
| 1004 | assert refusal(box.call("ann", "PUT", f"{SPECS}/blank", {"title": "u"})) == (403, "forbidden") |
| 1005 | with sandbox(tmp_path / "spared", rules=spared) as box: |
| 1006 | people(box, "ann") |
| 1007 | box.call("ann", "POST", SPECS, {"id": "blank", "title": "t"}) |
| 1008 | assert box.call("ann", "PUT", f"{SPECS}/blank", {"title": "u"})[0] == 200 |
| 1009 | |
| 1010 | |
| 1011 | def test_guards_attention_and_list_filters_read_a_date_bound_in_utc(tmp_path): |
| 1012 | """Pins S92, S95 at the other places an ordered condition is judged: an |
| 1013 | attention count and a list filter. A transition guard cannot hold one.""" |
| 1014 | with sandbox(tmp_path) as box: |
| 1015 | people(box, "ann") |
| 1016 | for record_id, when_at in (("z", "2026-05-01T10:00:00Z"), ("o", "2026-05-01T23:30:00-05:00"), |
| 1017 | ("blank", "")): |
| 1018 | box.call("ann", "POST", SPECS, {"id": record_id, "title": "t", "when_at": when_at}) |
| 1019 | # A list filter: o is 04:30 UTC on 2 May. |
| 1020 | status, body = box.call("ann", "GET", f"{SPECS}?when_at.gte=2026-05-02") |
| 1021 | assert status == 200 and [row["id"] for row in body["records"]] == ["o"] |
| 1022 | status, body = box.call("ann", "GET", f"{SPECS}?when_at.lt=2026-05-02") |
| 1023 | assert status == 200 and [row["id"] for row in body["records"]] == ["z"] |
| 1024 | # An attention count. |
| 1025 | compiled = object_attention._split_where(object_attention.parse_where( |
| 1026 | {"when_at": {"op": "lt", "value": "2026-05-02"}}, require_equality=False)) |
| 1027 | rows = [stored(box, "specs", record_id) for record_id in ("z", "o", "blank")] |
| 1028 | now = datetime(2026, 6, 1, tzinfo=timezone.utc) |
| 1029 | assert [row["id"] for row in rows |
| 1030 | if object_attention._matches(row, compiled, None, now=now, today=now.date())] == ["z"] |
| 1031 | # A transition guard's `when` takes equality conditions only, so an |
| 1032 | # ordered condition never reaches a guard. |
| 1033 | def guarded(schema): |
| 1034 | for field in schema["fields"]: |
| 1035 | if field["name"] == "status": |
| 1036 | field["transitions"]["draft"] = [ |
| 1037 | {"to": "archived", "when": {"when_at": {"op": "lt", "value": "2026-05-02"}}}] |
| 1038 | with pytest.raises(ValueError, match="'when' values must be non-empty strings"): |
| 1039 | _with_schema(box, guarded, lambda: None) |
| 1040 | |
| 1041 | |
| 1042 | def test_older_than_days_ages_a_date_against_the_servers_local_date(tmp_path): |
| 1043 | """Pins S93: at 06:00 UTC on 15 June it is still 14 June twelve hours west, |
| 1044 | so a date of 7 June is 7 days old there and 8 days old in UTC.""" |
| 1045 | now = datetime(2026, 6, 15, 6, 0, tzinfo=timezone.utc) |
| 1046 | compiled = object_attention._split_where(object_attention.parse_where( |
| 1047 | {"day": {"op": "older_than_days", "value": 8}}, require_equality=False)) |
| 1048 | |
| 1049 | def older(value): |
| 1050 | today = now.astimezone().date() |
| 1051 | return object_attention._matches({"day": value}, compiled, None, now=now, today=today) |
| 1052 | |
| 1053 | restore = _local_zone("AOE+12") |
| 1054 | try: |
| 1055 | west = older("2026-06-07") |
| 1056 | west_stamp = older("2026-06-07T06:00:00Z") |
| 1057 | finally: |
| 1058 | restore() |
| 1059 | restore = _local_zone("UTC0") |
| 1060 | try: |
| 1061 | utc = older("2026-06-07") |
| 1062 | finally: |
| 1063 | restore() |
| 1064 | assert (west, utc) == (False, True) |
| 1065 | assert west_stamp is True, "a datetime is aged from the UTC instant wherever the server is" |
| 1066 | |
| 1067 | |
| 1068 | # --- the page and its tests ---------------------------------------------------------- |
| 1069 | |
| 1070 | |
| 1071 | def _statements(text: str) -> list[str]: |
| 1072 | return re.findall(r"^\*\*(S\d+)\.\*\*", text, flags=re.MULTILINE) |
| 1073 | |
| 1074 | |
| 1075 | def test_every_statement_in_the_document_is_pinned(): |
| 1076 | """Every numbered statement is named by a test here or cited, with a test |
| 1077 | that exists, in the page's table of older tests.""" |
| 1078 | text = DOC.read_text(encoding="utf-8") |
| 1079 | statements = _statements(text) |
| 1080 | assert statements and len(statements) == len(set(statements)), "statement numbers repeat" |
| 1081 | here = set() |
| 1082 | for name, function in globals().items(): |
| 1083 | if name.startswith("test_") and callable(function) and function.__doc__: |
| 1084 | here.update(re.findall(r"\bS\d+\b", function.__doc__.split("\n\n")[0])) |
| 1085 | cited = set() |
| 1086 | for ids, path, test in re.findall(r"^\| ([S\d, ]+) \| `(tests/[\w/]+\.py)::(test_\w+)` \|", text, |
| 1087 | flags=re.MULTILINE): |
| 1088 | source = (ROOT / path).read_text(encoding="utf-8") |
| 1089 | assert re.search(rf"^def {test}\(", source, flags=re.MULTILINE), f"{path}::{test} does not exist" |
| 1090 | cited.update(part.strip() for part in ids.split(",")) |
| 1091 | missing = [statement for statement in statements if statement not in here | cited] |
| 1092 | assert not missing, f"statements no test pins: {missing}" |
| 1093 | unknown = sorted((here | cited) - set(statements), key=lambda s: int(s[1:])) |
| 1094 | assert not unknown, f"tests name statements the page does not have: {unknown}" |