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_policy_cache.py · 16.3 KB · 406 lines
| 1 | """A parsed permission policy is served only while its file still has the stat it was read under. |
| 2 | |
| 3 | load_policy parsed policy.json and rebuilt every rule on each call (about |
| 4 | 1 ms with 246 rules, one to three calls per request). It now keeps the |
| 5 | parsed policy. Every permission decision is made from it, so the other side |
| 6 | of the trade is absolute: whoever changes the policy (the API in another |
| 7 | worker, the package installer, the daemon, an operator's editor, a restore), |
| 8 | and however little the change shows in size or mtime, the very next call -- |
| 9 | and the very next request -- must decide from what is on disk. When in doubt |
| 10 | the file is read. The oracle is a fresh parse. |
| 11 | """ |
| 12 | |
| 13 | import json |
| 14 | import os |
| 15 | import random |
| 16 | import threading |
| 17 | import time |
| 18 | from pathlib import Path |
| 19 | |
| 20 | import pytest |
| 21 | |
| 22 | import object_packages |
| 23 | import object_permission_store |
| 24 | import object_permissions |
| 25 | import object_server |
| 26 | from test_object_server import TEST_ADMIN_TOKEN, enable_admin_token, request, write_records |
| 27 | |
| 28 | |
| 29 | def settle() -> None: |
| 30 | """Wait until a policy read now may be kept (_POLICY_CACHE_RACY_NS).""" |
| 31 | time.sleep(object_permission_store._POLICY_CACHE_RACY_NS / 1e9 + 0.03) |
| 32 | |
| 33 | |
| 34 | def rule(principal: str, collection: str, *actions: str, effect: str = "allow") -> dict: |
| 35 | return {"effect": effect, "principal": principal, "actions": list(actions or ("read",)), |
| 36 | "collection": collection, "reason": "test"} |
| 37 | |
| 38 | |
| 39 | def policy_text(*rules: dict) -> str: |
| 40 | return json.dumps({"access_mode": "role_based", "rules": list(rules)}, indent=2, sort_keys=True) + "\n" |
| 41 | |
| 42 | |
| 43 | def policy_file(data_dir: Path) -> Path: |
| 44 | return data_dir / "permissions" / "policy.json" |
| 45 | |
| 46 | |
| 47 | def write_policy(data_dir: Path, *rules: dict) -> Path: |
| 48 | path = policy_file(data_dir) |
| 49 | path.parent.mkdir(parents=True, exist_ok=True) |
| 50 | path.write_text(policy_text(*rules)) |
| 51 | return path |
| 52 | |
| 53 | |
| 54 | def collections(data_dir) -> list[str]: |
| 55 | return [r.collection for r in object_permission_store.load_policy(data_dir).rules] |
| 56 | |
| 57 | |
| 58 | def fresh(data_dir: Path) -> object_permissions.PermissionPolicy: |
| 59 | """What an uncached read returns.""" |
| 60 | return object_permissions.policy_from_dict(json.loads(policy_file(data_dir).read_text())) |
| 61 | |
| 62 | |
| 63 | @pytest.fixture |
| 64 | def parses(monkeypatch): |
| 65 | calls = [] |
| 66 | real = object_permissions.policy_from_dict |
| 67 | |
| 68 | def counting(payload): |
| 69 | calls.append(1) |
| 70 | return real(payload) |
| 71 | |
| 72 | monkeypatch.setattr(object_permission_store.object_permissions, "policy_from_dict", counting) |
| 73 | return calls |
| 74 | |
| 75 | |
| 76 | @pytest.fixture |
| 77 | def data_dir(tmp_path): |
| 78 | data_dir = tmp_path / "data" |
| 79 | write_policy(data_dir, rule("registered", "notes")) |
| 80 | return data_dir |
| 81 | |
| 82 | |
| 83 | # --- the store --------------------------------------------------------------------------------- |
| 84 | |
| 85 | |
| 86 | def test_a_settled_policy_is_parsed_once(data_dir, parses): |
| 87 | settle() |
| 88 | first = object_permission_store.load_policy(data_dir) |
| 89 | assert first == fresh(data_dir) |
| 90 | for base in (data_dir, str(data_dir), data_dir): |
| 91 | assert object_permission_store.load_policy(base) is first |
| 92 | assert len(parses) == 2 # the load, and the oracle's own parse |
| 93 | |
| 94 | |
| 95 | def test_a_same_size_edit_in_the_same_instant_is_seen(data_dir): |
| 96 | """The dangerous edit: an operator swaps one word for another of the |
| 97 | same length ("allow" for "deny " would do it), twice within a tick. A |
| 98 | policy read inside that window must not be kept.""" |
| 99 | settle() |
| 100 | assert collections(data_dir) == ["notes"] |
| 101 | path = policy_file(data_dir) |
| 102 | text = path.read_text() |
| 103 | path.write_text(text.replace('"notes"', '"tasks"')) |
| 104 | assert collections(data_dir) == ["tasks"] |
| 105 | path.write_text(text.replace('"notes"', '"deals"')) |
| 106 | assert collections(data_dir) == ["deals"] |
| 107 | path.write_text(text) |
| 108 | assert collections(data_dir) == ["notes"] |
| 109 | |
| 110 | |
| 111 | def test_a_policy_read_moments_after_it_was_written_is_not_kept(data_dir, parses): |
| 112 | settle() |
| 113 | collections(data_dir) |
| 114 | write_policy(data_dir, rule("registered", "notes"), rule("registered", "tasks")) |
| 115 | before = len(parses) |
| 116 | collections(data_dir) |
| 117 | collections(data_dir) |
| 118 | assert len(parses) == before + 2, "inside the racy window every load reads the file" |
| 119 | settle() |
| 120 | collections(data_dir) |
| 121 | collections(data_dir) |
| 122 | assert len(parses) == before + 3, "once the file has settled one parse is kept" |
| 123 | |
| 124 | |
| 125 | def test_a_policy_saved_through_the_store_is_seen(data_dir): |
| 126 | """save_policy replaces the file: what the API and the installer do.""" |
| 127 | settle() |
| 128 | assert collections(data_dir) == ["notes"] |
| 129 | object_permission_store.replace_policy(json.loads(policy_text(rule("registered", "tasks"))), data_dir) |
| 130 | assert collections(data_dir) == ["tasks"] |
| 131 | assert collections(str(data_dir)) == ["tasks"] |
| 132 | object_permission_store.replace_policy(json.loads(policy_text()), str(data_dir)) |
| 133 | assert collections(data_dir) == [] |
| 134 | |
| 135 | |
| 136 | def test_an_atomic_replace_that_keeps_size_and_mtime_is_seen(data_dir): |
| 137 | """A restore: a different file with the old size and the old mtime. |
| 138 | Only inode and ctime give it away.""" |
| 139 | settle() |
| 140 | path = policy_file(data_dir) |
| 141 | before = os.stat(path) |
| 142 | assert collections(data_dir) == ["notes"] |
| 143 | replacement = path.with_name("policy.json.restored") |
| 144 | replacement.write_text(path.read_text().replace('"notes"', '"tasks"')) |
| 145 | os.utime(replacement, ns=(before.st_atime_ns, before.st_mtime_ns)) |
| 146 | os.replace(replacement, path) |
| 147 | after = os.stat(path) |
| 148 | assert (after.st_mtime_ns, after.st_size) == (before.st_mtime_ns, before.st_size) |
| 149 | assert collections(data_dir) == ["tasks"] |
| 150 | |
| 151 | |
| 152 | def test_an_in_place_edit_whose_mtime_is_set_back_is_seen(data_dir): |
| 153 | settle() |
| 154 | path = policy_file(data_dir) |
| 155 | before = os.stat(path) |
| 156 | assert collections(data_dir) == ["notes"] |
| 157 | path.write_text(path.read_text().replace('"notes"', '"tasks"')) |
| 158 | os.utime(path, ns=(before.st_atime_ns, before.st_mtime_ns)) |
| 159 | assert os.stat(path).st_mtime_ns == before.st_mtime_ns |
| 160 | assert collections(data_dir) == ["tasks"] |
| 161 | |
| 162 | |
| 163 | def test_a_removed_policy_file_means_the_default_at_once_and_a_new_one_is_seen(data_dir): |
| 164 | """The default policy has no rules: with enforcement on, nothing is |
| 165 | allowed. Serving the old rules after the file is gone would be the |
| 166 | opposite of failing closed.""" |
| 167 | settle() |
| 168 | assert collections(data_dir) == ["notes"] |
| 169 | policy_file(data_dir).unlink() |
| 170 | assert object_permission_store.load_policy(data_dir) is object_permission_store.DEFAULT_POLICY |
| 171 | assert object_permission_store.load_policy(data_dir) is object_permission_store.DEFAULT_POLICY |
| 172 | write_policy(data_dir, rule("registered", "tasks")) |
| 173 | assert collections(data_dir) == ["tasks"] |
| 174 | |
| 175 | |
| 176 | def test_a_policy_file_that_stops_parsing_raises_every_time_and_recovers(data_dir): |
| 177 | """Never an older policy in place of one that cannot be read, and never |
| 178 | a remembered error once the file is fixed.""" |
| 179 | settle() |
| 180 | assert collections(data_dir) == ["notes"] |
| 181 | path = policy_file(data_dir) |
| 182 | path.write_text("{ not json") |
| 183 | settle() |
| 184 | for _ in range(3): |
| 185 | with pytest.raises(ValueError, match="invalid JSON"): |
| 186 | object_permission_store.load_policy(data_dir) |
| 187 | path.write_text(json.dumps({"access_mode": "no-such-mode"})) |
| 188 | for _ in range(2): |
| 189 | with pytest.raises(ValueError, match="access_mode"): |
| 190 | object_permission_store.load_policy(data_dir) |
| 191 | write_policy(data_dir, rule("registered", "tasks")) |
| 192 | assert collections(data_dir) == ["tasks"] |
| 193 | |
| 194 | |
| 195 | def test_a_policy_file_replaced_by_a_link_out_of_the_directory_is_refused(data_dir, tmp_path): |
| 196 | settle() |
| 197 | assert collections(data_dir) == ["notes"] |
| 198 | outside = tmp_path / "outside.json" |
| 199 | outside.write_text(policy_text(rule("public", "notes", "read", "create", "update", "delete"))) |
| 200 | policy_file(data_dir).unlink() |
| 201 | os.symlink(outside, policy_file(data_dir)) |
| 202 | for _ in range(2): |
| 203 | with pytest.raises(ValueError, match="escapes"): |
| 204 | object_permission_store.load_policy(data_dir) |
| 205 | |
| 206 | |
| 207 | def test_a_linked_policy_file_is_read_every_time(data_dir, parses): |
| 208 | target = data_dir / "permissions" / "policy.shared" |
| 209 | target.write_text(policy_text(rule("registered", "notes"))) |
| 210 | policy_file(data_dir).unlink() |
| 211 | os.symlink(target, policy_file(data_dir)) |
| 212 | settle() |
| 213 | assert collections(data_dir) == ["notes"] |
| 214 | assert collections(data_dir) == ["notes"] |
| 215 | assert len(parses) == 2 |
| 216 | target.write_text(policy_text(rule("registered", "tasks"))) |
| 217 | assert collections(data_dir) == ["tasks"] |
| 218 | |
| 219 | |
| 220 | def test_a_relative_data_directory_follows_the_working_directory(tmp_path, monkeypatch): |
| 221 | write_policy(tmp_path / "a" / "data", rule("registered", "in_a")) |
| 222 | write_policy(tmp_path / "b" / "data", rule("registered", "in_b")) |
| 223 | settle() |
| 224 | monkeypatch.chdir(tmp_path / "a") |
| 225 | assert collections("data") == ["in_a"] |
| 226 | assert collections("data") == ["in_a"] |
| 227 | monkeypatch.chdir(tmp_path / "b") |
| 228 | assert collections("data") == ["in_b"] |
| 229 | |
| 230 | |
| 231 | def test_installing_a_package_that_ships_rules_is_seen(data_dir, tmp_path): |
| 232 | settle() |
| 233 | assert collections(data_dir) == ["notes"] |
| 234 | package_dir = tmp_path / "packages" / "app-pallets" |
| 235 | (package_dir / "schemas").mkdir(parents=True) |
| 236 | (package_dir / "permissions").mkdir() |
| 237 | (package_dir / object_packages.MANIFEST_FILE).write_text(json.dumps({ |
| 238 | "id": "app-pallets", "name": "Pallets", "version": "0.1.0", |
| 239 | "schemas": [{"collection": "pallets", "path": "schemas/pallets.json"}], |
| 240 | "permissions": [{"path": "permissions/rules.json"}], |
| 241 | })) |
| 242 | (package_dir / "schemas" / "pallets.json").write_text(json.dumps({"fields": [{"name": "id"}]})) |
| 243 | (package_dir / "permissions" / "rules.json").write_text(json.dumps({"rules": [rule("registered", "pallets")]})) |
| 244 | object_packages.install_package( |
| 245 | "app-pallets", root=tmp_path / "packages", base_dir=data_dir, object_roots=[tmp_path / "objects"] |
| 246 | ) |
| 247 | assert "pallets" in collections(data_dir) |
| 248 | assert object_permission_store.load_policy(data_dir) == fresh(data_dir) |
| 249 | |
| 250 | |
| 251 | def test_the_shared_policy_is_not_changed_by_being_used(data_dir): |
| 252 | """Callers get the cached object itself. Checks, serialising and the |
| 253 | package installer's merge must leave it exactly as parsed.""" |
| 254 | write_policy(data_dir, {**rule("registered", "notes"), "row_filter": {"owner_id": "$user_id"}}, |
| 255 | rule("role:sales", "deals", "read", "update")) |
| 256 | settle() |
| 257 | policy = object_permission_store.load_policy(data_dir) |
| 258 | snapshot = json.dumps(object_permissions.policy_to_dict(policy), sort_keys=True) |
| 259 | subject = object_permissions.PermissionSubject(user_id="7", roles=("sales",)) |
| 260 | for action in ("read", "update", "delete"): |
| 261 | for collection in ("notes", "deals", "other"): |
| 262 | object_permissions.check_permission( |
| 263 | subject, action, policy=policy, collection=collection, record={"owner_id": "7"} |
| 264 | ) |
| 265 | object_permissions.policy_to_dict(policy) |
| 266 | assert object_permission_store.load_policy(data_dir) is policy |
| 267 | assert json.dumps(object_permissions.policy_to_dict(policy), sort_keys=True) == snapshot |
| 268 | assert policy == fresh(data_dir) |
| 269 | |
| 270 | |
| 271 | def test_a_random_run_of_edits_never_disagrees_with_a_fresh_parse(tmp_path): |
| 272 | rng = random.Random(20261128) |
| 273 | data_dir = tmp_path / "data" |
| 274 | names = ["notes", "tasks", "deals", "leads", "items"] |
| 275 | path = write_policy(data_dir, rule("registered", "notes")) |
| 276 | for step in range(150): |
| 277 | rules = [rule(rng.choice(["registered", "public"]), name, effect=rng.choice(["allow", "deny "]).strip()) |
| 278 | for name in rng.sample(names, rng.randrange(0, 4))] |
| 279 | move = rng.random() |
| 280 | if move < 0.40: |
| 281 | path.write_text(policy_text(*rules)) |
| 282 | elif move < 0.70: |
| 283 | object_permission_store.replace_policy(json.loads(policy_text(*rules)), data_dir) |
| 284 | elif move < 0.80: |
| 285 | stamp = os.stat(path) |
| 286 | path.write_text(policy_text(*rules)) |
| 287 | os.utime(path, ns=(stamp.st_atime_ns, stamp.st_mtime_ns)) |
| 288 | if rng.random() < 0.12: |
| 289 | settle() |
| 290 | base = data_dir if rng.random() < 0.5 else str(data_dir) |
| 291 | assert object_permission_store.load_policy(base) == fresh(data_dir), f"step {step}" |
| 292 | |
| 293 | |
| 294 | def test_loading_from_several_threads_while_the_policy_is_replaced(data_dir): |
| 295 | stop = threading.Event() |
| 296 | problems: list[str] = [] |
| 297 | possible = (["notes"], ["notes", "tasks"]) |
| 298 | |
| 299 | def reader() -> None: |
| 300 | while not stop.is_set(): |
| 301 | try: |
| 302 | seen = collections(data_dir) |
| 303 | except Exception as exc: # noqa: BLE001 |
| 304 | problems.append(repr(exc)) |
| 305 | return |
| 306 | if seen not in possible: |
| 307 | problems.append(f"impossible policy: {seen}") |
| 308 | return |
| 309 | |
| 310 | threads = [threading.Thread(target=reader) for _ in range(4)] |
| 311 | for thread in threads: |
| 312 | thread.start() |
| 313 | both = json.loads(policy_text(rule("registered", "notes"), rule("registered", "tasks"))) |
| 314 | one = json.loads(policy_text(rule("registered", "notes"))) |
| 315 | for round_ in range(40): |
| 316 | object_permission_store.replace_policy(both, data_dir) |
| 317 | if round_ % 4 == 0: |
| 318 | time.sleep(0.07) |
| 319 | object_permission_store.replace_policy(one, data_dir) |
| 320 | stop.set() |
| 321 | for thread in threads: |
| 322 | thread.join() |
| 323 | assert problems == [] |
| 324 | assert collections(data_dir) == ["notes"] |
| 325 | settle() |
| 326 | assert collections(data_dir) == ["notes"] |
| 327 | |
| 328 | |
| 329 | # --- the next request ---------------------------------------------------------------------------- |
| 330 | |
| 331 | |
| 332 | @pytest.fixture |
| 333 | def served(tmp_path, monkeypatch): |
| 334 | """A data dir served with enforcement on, where user 7 may read contacts. |
| 335 | |
| 336 | Enforcement is forced on for a policy the readiness check would hold in |
| 337 | shadow mode (no file, no allow rule): these tests are about which policy |
| 338 | a request is decided from, and shadow mode allows everything.""" |
| 339 | data_dir = tmp_path / "data" |
| 340 | write_records(data_dir, "contacts", "id\tname\towner_id\n1\tAlice\t7\n2\tBob\t8\n") |
| 341 | write_policy(data_dir, rule("registered", "contacts", "read", "create")) |
| 342 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 343 | monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true") |
| 344 | monkeypatch.setenv(object_server.PERMISSION_UNREADY_ENFORCEMENT_ENV, "true") |
| 345 | monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true") |
| 346 | enable_admin_token(monkeypatch) |
| 347 | settle() |
| 348 | return data_dir |
| 349 | |
| 350 | |
| 351 | def read_status() -> int: |
| 352 | status, _, _ = request("/collections/contacts/records", headers=[("x-dbbasic-user-id", "7")]) |
| 353 | return status |
| 354 | |
| 355 | |
| 356 | def test_a_deny_written_by_hand_refuses_the_very_next_request(served): |
| 357 | assert read_status() == 200 |
| 358 | assert read_status() == 200 |
| 359 | write_policy(served, rule("registered", "contacts", "read", effect="deny"), |
| 360 | rule("registered", "contacts", "read", "create")) |
| 361 | assert read_status() == 403 |
| 362 | write_policy(served, rule("registered", "contacts", "read", "create")) |
| 363 | assert read_status() == 200 |
| 364 | |
| 365 | |
| 366 | def test_a_same_size_allow_to_deny_edit_refuses_the_very_next_request(served): |
| 367 | """One word changed in place, file size unchanged, no settling.""" |
| 368 | assert read_status() == 200 |
| 369 | path = policy_file(served) |
| 370 | allowed = path.read_text() |
| 371 | denied = allowed.replace('"allow"', '"deny" ') |
| 372 | assert len(denied) == len(allowed) and denied != allowed |
| 373 | path.write_text(denied) |
| 374 | assert read_status() == 403 |
| 375 | path.write_text(allowed) |
| 376 | assert read_status() == 200 |
| 377 | path.write_text(denied) |
| 378 | assert read_status() == 403 |
| 379 | |
| 380 | |
| 381 | def test_a_policy_changed_through_the_api_decides_the_very_next_request(served): |
| 382 | assert read_status() == 200 |
| 383 | admin = [("authorization", f"Bearer {TEST_ADMIN_TOKEN}")] |
| 384 | status, _, payload = request("/permissions/policy", headers=admin) |
| 385 | assert status == 200 |
| 386 | status, _, _ = request( |
| 387 | "/permissions/policy", method="PUT", headers=admin, |
| 388 | body=json.dumps({"policy": {"access_mode": "role_based", "rules": []}}).encode(), |
| 389 | ) |
| 390 | assert status == 200 |
| 391 | assert read_status() == 403 |
| 392 | status, _, _ = request( |
| 393 | "/permissions/policy", method="PUT", headers=admin, body=json.dumps({"policy": payload["policy"]}).encode(), |
| 394 | ) |
| 395 | assert status == 200 |
| 396 | assert read_status() == 200 |
| 397 | |
| 398 | |
| 399 | def test_a_removed_or_unreadable_policy_never_leaves_the_old_rules_in_force(served): |
| 400 | assert read_status() == 200 |
| 401 | policy_file(served).unlink() |
| 402 | assert read_status() == 403, "no policy file: the default has no rule that allows this" |
| 403 | policy_file(served).write_text("{ not json") |
| 404 | assert read_status() == 503, "a policy that cannot be read must fail the request, not allow it" |
| 405 | write_policy(served, rule("registered", "contacts", "read", "create")) |
| 406 | assert read_status() == 200 |