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_strict_save.py · 22.6 KB · 473 lines
| 1 | """Saving the deployment policy is held to DRON; reading it is not. |
| 2 | |
| 3 | Two moments, treated differently (docs/permissions-model.md, docs/dron.md): |
| 4 | |
| 5 | - SAVING (PUT /permissions/policy, object_permission_store.replace_policy) |
| 6 | is a new write by an operator. A policy the schema refuses in a way that |
| 7 | changes meaning is refused before anything is written, with a 400 naming |
| 8 | the rule (index, package tag) and the key. A misspelt `row_filter` used to |
| 9 | be dropped, turning an own-rows allow into an allow on every row. |
| 10 | - READING the stored file never refuses and never changes a decision: a box |
| 11 | that has such a rule on disk decides exactly as it did, and says so in |
| 12 | /admin/status, /permissions/status, /permissions/unshipped and the |
| 13 | startup log. |
| 14 | |
| 15 | And a save is not refused over rules the operator did not just write: a |
| 16 | policy the server produced (GET, then PUT unchanged) always saves back, on a |
| 17 | box with every shipped package installed and on one carrying older rules. |
| 18 | """ |
| 19 | |
| 20 | from __future__ import annotations |
| 21 | |
| 22 | import asyncio |
| 23 | import copy |
| 24 | import json |
| 25 | import sys |
| 26 | from pathlib import Path |
| 27 | |
| 28 | import pytest |
| 29 | |
| 30 | import object_packages |
| 31 | import object_permission_store |
| 32 | import object_permissions |
| 33 | import object_server |
| 34 | |
| 35 | sys.path.insert(0, str(Path(__file__).resolve().parent)) |
| 36 | import test_dron_schema # noqa: E402 (the worklist: POLICY_ENGINE_LAXER) |
| 37 | |
| 38 | ROOT = Path(__file__).resolve().parents[1] |
| 39 | PACKAGES_ROOT = ROOT / "packages" |
| 40 | ADMIN_TOKEN = "unit-test-only-admin-token" |
| 41 | # A reason no alert or log line may repeat: /permissions/unshipped shows |
| 42 | # rules whole, the status surfaces name them by index, package and key only. |
| 43 | REASON = "made-up reason text that must not reach an alert" |
| 44 | |
| 45 | OWN_ROWS = { |
| 46 | "effect": "allow", "principal": "role:sales", "actions": ["read"], |
| 47 | "collection": "contacts", "row_filter": {"owner_id": "$user_id"}, "reason": REASON, |
| 48 | } |
| 49 | TYPO = {**{k: v for k, v in OWN_ROWS.items() if k != "row_filter"}, |
| 50 | "rowfilter": {"owner_id": "$user_id"}} |
| 51 | |
| 52 | |
| 53 | class Box: |
| 54 | def __init__(self, tmp_path, monkeypatch): |
| 55 | self.data = tmp_path / "data" |
| 56 | self.objects = tmp_path / "objects" |
| 57 | self.objects.mkdir(parents=True, exist_ok=True) |
| 58 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(self.data)) |
| 59 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(self.objects)) |
| 60 | monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", ADMIN_TOKEN) |
| 61 | monkeypatch.setenv("DBBASIC_PACKAGES_DIR", str(PACKAGES_ROOT)) |
| 62 | monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true") |
| 63 | monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true") |
| 64 | for name in ("DBBASIC_OBJECT_TIMEOUT_SECONDS", "DBBASIC_WORKER_POOL_SIZE", |
| 65 | "DBBASIC_ROW_FILTER_INDEX", "DBBASIC_TRUSTED_IN_PROCESS_OBJECTS", |
| 66 | "DBBASIC_ENABLE_SESSION_ADMIN_GATES", "DBBASIC_PRIVATE_PACKAGES_DIR"): |
| 67 | monkeypatch.delenv(name, raising=False) |
| 68 | self.admin = [("authorization", f"Token {ADMIN_TOKEN}")] |
| 69 | records = self.data / "collections" / "contacts" / "records.tsv" |
| 70 | records.parent.mkdir(parents=True, exist_ok=True) |
| 71 | records.write_text("id\tname\towner_id\nc1\tAda\t7\nc2\tBob\t8\n") |
| 72 | |
| 73 | def call(self, path, method="GET", payload=None, headers=()): |
| 74 | body = json.dumps(payload).encode("utf-8") if payload is not None else b"" |
| 75 | scope_headers = [(b"accept", b"application/json"), (b"content-type", b"application/json")] |
| 76 | scope_headers += [(k.encode("latin-1"), v.encode("latin-1")) for k, v in headers] |
| 77 | messages = [] |
| 78 | |
| 79 | async def receive(): |
| 80 | return {"type": "http.request", "body": body, "more_body": False} |
| 81 | |
| 82 | async def send(message): |
| 83 | messages.append(message) |
| 84 | |
| 85 | scope = {"type": "http", "method": method, "path": path, "query_string": b"", |
| 86 | "headers": scope_headers, "client": ("127.0.0.1", 12345)} |
| 87 | asyncio.run(object_server.app(scope, receive, send)) |
| 88 | start = next(m for m in messages if m["type"] == "http.response.start") |
| 89 | raw = b"".join(m.get("body", b"") for m in messages if m["type"] == "http.response.body") |
| 90 | return start["status"], json.loads(raw.decode("utf-8")) |
| 91 | |
| 92 | def write_by_hand(self, payload): |
| 93 | path = object_permission_store.policy_path(self.data) |
| 94 | path.parent.mkdir(parents=True, exist_ok=True) |
| 95 | path.write_text(json.dumps(payload, indent=2)) |
| 96 | |
| 97 | def file_text(self): |
| 98 | return object_permission_store.policy_path(self.data).read_text() |
| 99 | |
| 100 | def sales_sees(self): |
| 101 | status, body = self.call("/collections/contacts/records", |
| 102 | headers=[("x-dbbasic-user-id", "7"), ("x-dbbasic-roles", "sales")]) |
| 103 | assert status == 200, body |
| 104 | return sorted(record["id"] for record in body["records"]) |
| 105 | |
| 106 | |
| 107 | def policy(*rules): |
| 108 | return {"access_mode": "role_based", "rules": [dict(rule) for rule in rules]} |
| 109 | |
| 110 | |
| 111 | # ---- A. saving -------------------------------------------------------------- |
| 112 | |
| 113 | |
| 114 | def test_a_misspelt_row_filter_is_refused_at_save_and_nothing_is_written(tmp_path, monkeypatch): |
| 115 | box = Box(tmp_path, monkeypatch) |
| 116 | assert box.call("/permissions/policy", "PUT", policy(OWN_ROWS), box.admin)[0] == 200 |
| 117 | before = box.file_text() |
| 118 | assert box.sales_sees() == ["c1"] |
| 119 | |
| 120 | status, body = box.call("/permissions/policy", "PUT", policy(OWN_ROWS, TYPO), box.admin) |
| 121 | |
| 122 | assert status == 400 |
| 123 | assert "rule 1: unknown key 'rowfilter' (did you mean 'row_filter'?)" in body["error"] |
| 124 | assert "nothing was saved" in body["error"] |
| 125 | assert body["problems"] == [{"index": 1, "package": None, "key": "rowfilter", |
| 126 | "message": "unknown key 'rowfilter' (did you mean 'row_filter'?)"}] |
| 127 | assert box.file_text() == before |
| 128 | assert box.sales_sees() == ["c1"] |
| 129 | |
| 130 | |
| 131 | def test_the_refusal_names_the_package_tag_and_every_mistake(tmp_path, monkeypatch): |
| 132 | box = Box(tmp_path, monkeypatch) |
| 133 | bad = {**TYPO, "package": "app-contacts", "expires_at": "tomorrow"} |
| 134 | status, body = box.call( |
| 135 | "/permissions/policy", "PUT", {**policy(bad), "admin_role": []}, box.admin) |
| 136 | assert status == 400 |
| 137 | assert "rule 0 (package app-contacts): unknown key 'rowfilter'" in body["error"] |
| 138 | assert "rule 0 (package app-contacts): expires_at 'tomorrow'" in body["error"] |
| 139 | assert "policy key 'admin_role': unknown key 'admin_role' (did you mean 'admin_roles'?)" in body["error"] |
| 140 | assert {(p["index"], p["package"], p["key"]) for p in body["problems"]} == { |
| 141 | (0, "app-contacts", "rowfilter"), (0, "app-contacts", "expires_at"), (None, None, "admin_role")} |
| 142 | assert not object_permission_store.policy_path(box.data).exists() |
| 143 | |
| 144 | |
| 145 | def test_the_starter_policy_still_installs(): |
| 146 | payload = object_permission_store.starter_policy_payload() |
| 147 | assert object_permissions.policy_declaration_problems(payload) == [] |
| 148 | |
| 149 | |
| 150 | @pytest.mark.parametrize("label,payload,why", test_dron_schema.POLICY_ENGINE_LAXER, |
| 151 | ids=[case[0] for case in test_dron_schema.POLICY_ENGINE_LAXER]) |
| 152 | def test_every_case_the_engine_reads_loosely_is_refused_at_save(tmp_path, label, payload, why): |
| 153 | with pytest.raises(object_permissions.PolicyDeclarationError) as refused: |
| 154 | object_permission_store.replace_policy(copy.deepcopy(payload), tmp_path) |
| 155 | assert refused.value.problems and all(p["key"] for p in refused.value.problems) |
| 156 | assert not object_permission_store.policy_path(tmp_path).exists() |
| 157 | |
| 158 | |
| 159 | @pytest.mark.parametrize("label,payload", test_dron_schema.POLICY_BOTH_ACCEPT, |
| 160 | ids=[case[0] for case in test_dron_schema.POLICY_BOTH_ACCEPT]) |
| 161 | def test_every_policy_both_accept_saves(tmp_path, label, payload): |
| 162 | object_permission_store.replace_policy(copy.deepcopy(payload), tmp_path) |
| 163 | |
| 164 | |
| 165 | def test_a_new_rule_next_to_kept_ones_is_still_judged(tmp_path, monkeypatch): |
| 166 | """Keeping stored rules is per rule: an operator's new rule is checked |
| 167 | even when the rest of the policy is old.""" |
| 168 | box = Box(tmp_path, monkeypatch) |
| 169 | legacy = {**OWN_ROWS, "principal": "sales"} # matches nobody; stored by an older box |
| 170 | box.write_by_hand(policy(legacy)) |
| 171 | status, body = box.call("/permissions/policy", "GET", headers=box.admin) |
| 172 | produced = body["policy"] |
| 173 | assert box.call("/permissions/policy", "PUT", produced, box.admin)[0] == 200 |
| 174 | produced["rules"].append(dict(legacy, collection="other")) |
| 175 | status, body = box.call("/permissions/policy", "PUT", produced, box.admin) |
| 176 | assert status == 400 |
| 177 | assert [(p["index"], p["key"]) for p in body["problems"]] == [(1, "principal")] |
| 178 | |
| 179 | |
| 180 | def test_a_stored_rule_copied_with_its_misspelt_key_is_judged(tmp_path, monkeypatch): |
| 181 | """The file's own text, typo included, is not what GET returns: saving |
| 182 | it would drop the key again, so it is refused like any new typo.""" |
| 183 | box = Box(tmp_path, monkeypatch) |
| 184 | box.write_by_hand(policy(TYPO)) |
| 185 | status, body = box.call("/permissions/policy", "PUT", policy(TYPO), box.admin) |
| 186 | assert status == 400 and body["problems"][0]["key"] == "rowfilter" |
| 187 | |
| 188 | |
| 189 | # ---- round trips: a policy the server produced always saves back ------------ |
| 190 | |
| 191 | |
| 192 | def _round_trip(box): |
| 193 | status, body = box.call("/permissions/policy", headers=box.admin) |
| 194 | assert status == 200 and body["policy"] is not None |
| 195 | before = box.file_text() |
| 196 | status, saved = box.call("/permissions/policy", "PUT", body["policy"], box.admin) |
| 197 | assert status == 200, saved |
| 198 | assert saved["policy"] == body["policy"] |
| 199 | assert box.file_text() == before |
| 200 | |
| 201 | |
| 202 | def test_round_trip_on_a_box_with_every_shipped_package_installed(tmp_path, monkeypatch): |
| 203 | box = Box(tmp_path, monkeypatch) |
| 204 | object_permission_store.replace_policy(object_permission_store.starter_policy_payload(), box.data) |
| 205 | pending = sorted(path.name for path in PACKAGES_ROOT.iterdir() |
| 206 | if (path / object_packages.MANIFEST_FILE).is_file()) |
| 207 | while pending: # dependencies first: retry until nothing more installs |
| 208 | installed = [] |
| 209 | for package_id in pending: |
| 210 | try: |
| 211 | object_packages.install_package(package_id, root=PACKAGES_ROOT, base_dir=box.data, |
| 212 | object_roots=[box.objects]) |
| 213 | except object_packages.PackageInstallError: |
| 214 | continue |
| 215 | installed.append(package_id) |
| 216 | assert installed, f"these shipped packages do not install: {pending}" |
| 217 | pending = [package_id for package_id in pending if package_id not in installed] |
| 218 | stored = json.loads(box.file_text()) |
| 219 | assert len({rule.get("package") for rule in stored["rules"]}) > 20 |
| 220 | _round_trip(box) |
| 221 | # Nothing to report either: every shipped rule is DRON. |
| 222 | assert object_permission_store.stored_policy_findings(box.data) == [] |
| 223 | |
| 224 | |
| 225 | # Rules an older box may hold that today's check refuses. None is something |
| 226 | # the operator writes in this save, so none may refuse it. None of them is a |
| 227 | # serious finding: those block a save that keeps them (tests below). |
| 228 | OLDER_RULES = [ |
| 229 | {"effect": "allow", "principal": "registered", "actions": ["read", "execute"], |
| 230 | "reason": "signed-in users can read and run objects"}, # the old starter's wide rule |
| 231 | {"effect": "ALLOW", "principal": "public", "actions": ["read"], "collection": "news", |
| 232 | "package": "app-news-old"}, |
| 233 | {"effect": "allow", "principal": "registered", "actions": ["read"], "collection": "posts", |
| 234 | "row_filter": {"is_public": True}, "package": "app-forum"}, |
| 235 | {"effect": "allow", "principal": "admin", "actions": ["update"], "collection": "posts"}, |
| 236 | {"effect": "allow", "principal": "role:manager", "actions": ["read", "reed"], |
| 237 | "collection": "legacy-orders", "package": "app-orders"}, |
| 238 | {"effect": "deny", "principal": "registered", "actions": ["delete", "delete"], "collection": "posts"}, |
| 239 | {"effect": "allow", "principal": "public", "actions": ["read"], "collection": 5}, |
| 240 | ] |
| 241 | |
| 242 | |
| 243 | def test_round_trip_on_a_box_upgraded_from_an_older_rule_set(tmp_path, monkeypatch): |
| 244 | box = Box(tmp_path, monkeypatch) |
| 245 | payload = object_permission_store.starter_policy_payload() |
| 246 | payload["rules"] += copy.deepcopy(OLDER_RULES) |
| 247 | payload["user_roles"] = {"7": ["sales", "sales", 3]} |
| 248 | payload["access_mode"] = None |
| 249 | box.write_by_hand(payload) |
| 250 | assert object_permissions.policy_declaration_problems(payload), "the fixture must hold old mistakes" |
| 251 | # The first save writes the engine's reading; from then on it is a fixed point. |
| 252 | status, body = box.call("/permissions/policy", headers=box.admin) |
| 253 | status, saved = box.call("/permissions/policy", "PUT", body["policy"], box.admin) |
| 254 | assert status == 200, saved |
| 255 | _round_trip(box) |
| 256 | |
| 257 | |
| 258 | def test_round_trip_keeps_old_package_rules_after_an_install(tmp_path, monkeypatch): |
| 259 | """The package installer rewrites the file; the old rules it carries |
| 260 | forward are still the box's own, and still save back.""" |
| 261 | box = Box(tmp_path, monkeypatch) |
| 262 | payload = object_permission_store.starter_policy_payload() |
| 263 | payload["rules"] += copy.deepcopy(OLDER_RULES) |
| 264 | box.write_by_hand(payload) |
| 265 | object_packages.install_package("app-notes", root=PACKAGES_ROOT, base_dir=box.data, |
| 266 | object_roots=[box.objects]) |
| 267 | _round_trip(box) |
| 268 | |
| 269 | |
| 270 | # ---- B. reading: decisions unchanged, findings reported --------------------- |
| 271 | |
| 272 | |
| 273 | def test_a_hand_written_typo_still_decides_as_before_and_is_reported(tmp_path, monkeypatch, capsys): |
| 274 | box = Box(tmp_path, monkeypatch) |
| 275 | box.write_by_hand(policy(TYPO)) |
| 276 | reference = object_permissions.PermissionPolicy( |
| 277 | access_mode="role_based", |
| 278 | rules=(object_permissions.rule_from_dict({k: v for k, v in TYPO.items() if k != "rowfilter"}),)) |
| 279 | |
| 280 | # Decisions: exactly the engine's old reading (the filter dropped), so |
| 281 | # the sales user still reads every row, through the HTTP app too. |
| 282 | assert object_permission_store.load_policy(box.data) == reference |
| 283 | assert box.sales_sees() == ["c1", "c2"] |
| 284 | |
| 285 | # Reported where an operator looks. |
| 286 | status, admin_status = box.call("/admin/status", headers=box.admin) |
| 287 | assert status == 200 |
| 288 | [alert] = [a for a in admin_status["alerts"] if "Permission policy file has" in a] |
| 289 | assert "rule 0 key 'rowfilter'" in alert |
| 290 | assert "this allow applies to every row" in alert |
| 291 | assert "rename it to 'row_filter'" in alert |
| 292 | assert "Nothing was changed" in alert |
| 293 | |
| 294 | status, permissions = box.call("/permissions/status", headers=box.admin) |
| 295 | [finding] = permissions["policy"]["findings"] |
| 296 | assert finding["serious"] is True and finding["index"] == 0 and finding["key"] == "rowfilter" |
| 297 | assert any("rule 0 key 'rowfilter'" in w for w in permissions["warnings"]) |
| 298 | |
| 299 | status, unshipped = box.call("/permissions/unshipped", headers=box.admin) |
| 300 | assert status == 200 and unshipped["findings"] == [finding] |
| 301 | |
| 302 | object_server._note_policy_findings() |
| 303 | log = capsys.readouterr().err |
| 304 | assert "SERIOUS permission policy mistake, rule 0 key 'rowfilter'" in log |
| 305 | |
| 306 | # None of it repeats the rule's reason text (unshipped shows the rule whole). |
| 307 | surfaces = [alert, json.dumps(permissions["warnings"]), json.dumps(finding), log] |
| 308 | assert not any(REASON in text for text in surfaces) |
| 309 | assert any(REASON in json.dumps(entry) for entry in unshipped["rules"]) |
| 310 | |
| 311 | # And still deciding as before after all that reading. |
| 312 | assert box.sales_sees() == ["c1", "c2"] |
| 313 | |
| 314 | |
| 315 | @pytest.mark.parametrize("deny_rule,key", [ |
| 316 | ({"principal": "sales"}, "principal"), |
| 317 | ({"expires_at": "next week"}, "expires_at"), |
| 318 | ({"row_filter": {"owner_id": "$userid"}}, "row_filter"), |
| 319 | ]) |
| 320 | def test_a_deny_that_never_applies_is_reported_as_serious_and_still_never_applies( |
| 321 | tmp_path, monkeypatch, deny_rule, key): |
| 322 | box = Box(tmp_path, monkeypatch) |
| 323 | grant = {k: v for k, v in OWN_ROWS.items() if k != "row_filter"} # every row |
| 324 | deny = {"effect": "deny", "principal": "role:sales", "actions": ["read"], |
| 325 | "collection": "contacts", "reason": REASON, **deny_rule} |
| 326 | box.write_by_hand(policy(grant, deny)) |
| 327 | assert box.sales_sees() == ["c1", "c2"] # the deny is off, as it always was |
| 328 | |
| 329 | [finding] = object_permission_store.stored_policy_findings(box.data) |
| 330 | assert (finding["index"], finding["key"], finding["serious"]) == (1, key, True) |
| 331 | assert "this deny never applies" in finding["today"] |
| 332 | status, admin_status = box.call("/admin/status", headers=box.admin) |
| 333 | assert any(f"rule 1 key '{key}'" in alert for alert in admin_status["alerts"]) |
| 334 | |
| 335 | |
| 336 | def test_a_mistake_that_does_not_widen_is_reported_but_not_as_serious(tmp_path, monkeypatch): |
| 337 | box = Box(tmp_path, monkeypatch) |
| 338 | box.write_by_hand(policy({**OWN_ROWS, "effect": "ALLOW"})) |
| 339 | assert box.sales_sees() == ["c1"] |
| 340 | [finding] = object_permission_store.stored_policy_findings(box.data) |
| 341 | assert finding["serious"] is False and finding["today"] == "read as 'allow'" |
| 342 | status, admin_status = box.call("/admin/status", headers=box.admin) |
| 343 | [alert] = [a for a in admin_status["alerts"] if "Permission policy file has" in a] |
| 344 | assert "none widens access" in alert |
| 345 | |
| 346 | |
| 347 | def test_a_clean_policy_has_no_findings_and_no_alert(tmp_path, monkeypatch): |
| 348 | box = Box(tmp_path, monkeypatch) |
| 349 | box.write_by_hand(policy(OWN_ROWS)) |
| 350 | assert object_permission_store.stored_policy_findings(box.data) == [] |
| 351 | status, admin_status = box.call("/admin/status", headers=box.admin) |
| 352 | assert not any("Permission policy file has" in alert for alert in admin_status["alerts"]) |
| 353 | |
| 354 | |
| 355 | def test_a_restore_preview_names_the_mistakes_in_the_policy_it_would_put_back(tmp_path): |
| 356 | """A restore is not refused for them (it puts the box's own file back), |
| 357 | but the preview compares only the engine's reading, where a dropped key |
| 358 | is invisible; the findings say what that reading hides.""" |
| 359 | import io |
| 360 | import tarfile |
| 361 | |
| 362 | import object_policy_diff |
| 363 | |
| 364 | data = tmp_path / "data" |
| 365 | object_permission_store.replace_policy(policy(OWN_ROWS), data) |
| 366 | archive = tmp_path / "snapshot.tar.gz" |
| 367 | raw = json.dumps(policy(TYPO)).encode("utf-8") |
| 368 | with tarfile.open(archive, "w:gz") as tar: |
| 369 | member = tarfile.TarInfo(object_policy_diff.POLICY_MEMBER) |
| 370 | member.size = len(raw) |
| 371 | tar.addfile(member, io.BytesIO(raw)) |
| 372 | |
| 373 | diff = object_policy_diff.restore_policy_diff(archive, data) |
| 374 | [finding] = diff["findings"] |
| 375 | assert (finding["index"], finding["key"], finding["serious"]) == (0, "rowfilter", True) |
| 376 | text = object_policy_diff.format_policy_diff(diff) |
| 377 | assert "! rule 0 key 'rowfilter': the engine ignores this key, so this allow applies to every row" in text |
| 378 | assert REASON not in text |
| 379 | |
| 380 | |
| 381 | # ---- a save must not silently write a serious finding back ------------------- |
| 382 | |
| 383 | |
| 384 | def _alerts(box): |
| 385 | status, body = box.call("/admin/status", headers=box.admin) |
| 386 | assert status == 200 |
| 387 | return [alert for alert in body["alerts"] if "Permission policy file has" in alert] |
| 388 | |
| 389 | |
| 390 | def _typo_box(tmp_path, monkeypatch, *extra): |
| 391 | box = Box(tmp_path, monkeypatch) |
| 392 | other = {"effect": "allow", "principal": "public", "actions": ["read"], "collection": "news"} |
| 393 | box.write_by_hand(policy(other, {**TYPO, "package": "app-contacts"}, *extra)) |
| 394 | status, body = box.call("/permissions/policy", headers=box.admin) |
| 395 | return box, body["policy"] |
| 396 | |
| 397 | |
| 398 | def test_get_then_put_with_a_stored_widening_typo_is_refused_and_the_file_is_unchanged(tmp_path, monkeypatch): |
| 399 | box, produced = _typo_box(tmp_path, monkeypatch) |
| 400 | before = box.file_text() |
| 401 | status, body = box.call("/permissions/policy", "PUT", produced, box.admin) |
| 402 | assert status == 400 |
| 403 | assert "rule 1 (package app-contacts) key 'rowfilter'" in body["error"] |
| 404 | assert "this allow applies to every row" in body["error"] |
| 405 | assert "rename it to 'row_filter'" in body["error"] |
| 406 | assert "Fix or remove that rule in the same save" in body["error"] |
| 407 | [problem] = body["problems"] |
| 408 | assert (problem["index"], problem["package"], problem["key"], problem["serious"]) == ( |
| 409 | 1, "app-contacts", "rowfilter", True) |
| 410 | assert REASON not in body["error"] |
| 411 | assert box.file_text() == before |
| 412 | assert _alerts(box) and box.sales_sees() == ["c1", "c2"] |
| 413 | |
| 414 | |
| 415 | def test_the_same_put_with_the_rule_fixed_saves_and_the_alert_is_gone(tmp_path, monkeypatch): |
| 416 | box, produced = _typo_box(tmp_path, monkeypatch) |
| 417 | produced["rules"][1]["row_filter"] = {"owner_id": "$user_id"} |
| 418 | status, body = box.call("/permissions/policy", "PUT", produced, box.admin) |
| 419 | assert status == 200, body |
| 420 | assert _alerts(box) == [] |
| 421 | assert box.sales_sees() == ["c1"] |
| 422 | |
| 423 | |
| 424 | def test_the_same_put_with_the_rule_removed_saves(tmp_path, monkeypatch): |
| 425 | box, produced = _typo_box(tmp_path, monkeypatch) |
| 426 | del produced["rules"][1] |
| 427 | status, body = box.call("/permissions/policy", "PUT", produced, box.admin) |
| 428 | assert status == 200, body |
| 429 | assert _alerts(box) == [] |
| 430 | |
| 431 | |
| 432 | def test_an_unrelated_edit_while_the_finding_stands_is_refused_naming_it(tmp_path, monkeypatch): |
| 433 | box, produced = _typo_box(tmp_path, monkeypatch) |
| 434 | before = box.file_text() |
| 435 | produced["roles"] = {"sales": {"label": "Sales"}} |
| 436 | produced["rules"].insert(0, {"effect": "allow", "principal": "public", "actions": ["read"], |
| 437 | "collection": "events"}) |
| 438 | status, body = box.call("/permissions/policy", "PUT", produced, box.admin) |
| 439 | assert status == 400 |
| 440 | assert [(p["index"], p["key"]) for p in body["problems"]] == [(1, "rowfilter")] |
| 441 | assert box.file_text() == before |
| 442 | |
| 443 | |
| 444 | @pytest.mark.parametrize("deny_rule", [{"principal": "sales"}, {"expires_at": "next week"}]) |
| 445 | def test_a_deny_that_never_applies_blocks_a_save_that_keeps_it(tmp_path, monkeypatch, deny_rule): |
| 446 | box = Box(tmp_path, monkeypatch) |
| 447 | deny = {"effect": "deny", "principal": "role:sales", "actions": ["read"], |
| 448 | "collection": "contacts", **deny_rule} |
| 449 | box.write_by_hand(policy(OWN_ROWS, deny)) |
| 450 | status, body = box.call("/permissions/policy", headers=box.admin) |
| 451 | assert box.call("/permissions/policy", "PUT", body["policy"], box.admin)[0] == 400 |
| 452 | body["policy"]["rules"][1].update({"principal": "role:sales"}) |
| 453 | body["policy"]["rules"][1].pop("expires_at", None) |
| 454 | assert box.call("/permissions/policy", "PUT", body["policy"], box.admin)[0] == 200 |
| 455 | |
| 456 | |
| 457 | def test_a_misspelt_rules_key_blocks_a_save_until_the_rules_are_written(tmp_path, monkeypatch): |
| 458 | box = Box(tmp_path, monkeypatch) |
| 459 | box.write_by_hand({"access_mode": "role_based", "rulez": [OWN_ROWS]}) |
| 460 | status, body = box.call("/permissions/policy", headers=box.admin) |
| 461 | status, refused = box.call("/permissions/policy", "PUT", body["policy"], box.admin) |
| 462 | assert status == 400 and refused["problems"][0]["key"] == "rulez" |
| 463 | body["policy"]["rules"] = [OWN_ROWS] |
| 464 | assert box.call("/permissions/policy", "PUT", body["policy"], box.admin)[0] == 200 |
| 465 | |
| 466 | |
| 467 | def test_a_finding_that_does_not_widen_does_not_block_a_save(tmp_path, monkeypatch): |
| 468 | box = Box(tmp_path, monkeypatch) |
| 469 | box.write_by_hand(policy({**OWN_ROWS, "effect": "ALLOW"}, {**OWN_ROWS, "principal": "sales"})) |
| 470 | assert _alerts(box) |
| 471 | status, body = box.call("/permissions/policy", headers=box.admin) |
| 472 | status, saved = box.call("/permissions/policy", "PUT", body["policy"], box.admin) |
| 473 | assert status == 200, saved |