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_fail_closed.py · 29.6 KB · 606 lines
| 1 | """DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS: a stored allow whose narrowing |
| 2 | key was dropped grants nothing. |
| 3 | |
| 4 | The stored policy file is read leniently (tests/test_policy_strict_save.py): |
| 5 | a misspelt `row_filter` is ignored, so an own-rows allow covers every row, |
| 6 | and the box reports it as a serious finding while still applying it. This |
| 7 | setting, off by default, makes the engine stop applying such a rule: |
| 8 | |
| 9 | - OFF (unset, or anything but 1/true/yes/on): every answer is byte for byte |
| 10 | what it was. Only the finding's words say the rule applies more widely |
| 11 | than written and name the setting. |
| 12 | - ON: every stored ALLOW rule with a serious finding is treated as absent |
| 13 | for decisions. It stays in the file and in GET /permissions/policy, and a |
| 14 | save still has to fix or remove it. Deny rules are untouched in every case. |
| 15 | - ON and the findings cannot be worked out: no policy, the same refusal as |
| 16 | for a policy file that does not parse. |
| 17 | |
| 18 | All through the real HTTP app. |
| 19 | """ |
| 20 | |
| 21 | from __future__ import annotations |
| 22 | |
| 23 | import asyncio |
| 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 | from test_policy_strict_save import OWN_ROWS, PACKAGES_ROOT, REASON, TYPO, Box, policy # noqa: E402 |
| 37 | |
| 38 | SETTING = "DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS" |
| 39 | NOT_APPLIED = "this rule is not applied" |
| 40 | APPLIED_WIDELY = ("this rule applies more widely than written; set " |
| 41 | "DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS to stop applying it") |
| 42 | |
| 43 | SALES_7 = [("x-dbbasic-user-id", "7"), ("x-dbbasic-roles", "sales")] |
| 44 | SALES_8 = [("x-dbbasic-user-id", "8"), ("x-dbbasic-roles", "sales")] |
| 45 | # Correctly written rules that sit beside the mistaken one. |
| 46 | LEADS_OWN = {"effect": "allow", "principal": "role:sales", "actions": ["read"], |
| 47 | "collection": "leads", "row_filter": {"owner_id": "$user_id"}} |
| 48 | NEWS_PUBLIC = {"effect": "allow", "principal": "public", "actions": ["read"], "collection": "news"} |
| 49 | # The requests every comparison replays: lists and single rows, as the two |
| 50 | # sales users and as nobody. |
| 51 | REQUESTS = [ |
| 52 | ("/collections/contacts/records", SALES_7), |
| 53 | ("/collections/contacts/records", SALES_8), |
| 54 | ("/collections/contacts/records", []), |
| 55 | ("/collections/contacts/records/c1", SALES_7), |
| 56 | ("/collections/contacts/records/c2", SALES_7), |
| 57 | ("/collections/leads/records", SALES_7), |
| 58 | ("/collections/leads/records/l2", SALES_7), |
| 59 | ("/collections/news/records", []), |
| 60 | ] |
| 61 | |
| 62 | |
| 63 | class FailClosedBox(Box): |
| 64 | def __init__(self, tmp_path, monkeypatch, setting=None): |
| 65 | super().__init__(tmp_path, monkeypatch) |
| 66 | self.monkeypatch = monkeypatch |
| 67 | self.set(setting) |
| 68 | self.rows("leads", "id\tname\towner_id\nl1\tLead one\t7\nl2\tLead two\t8\n") |
| 69 | self.rows("news", "id\ttitle\nn1\tOpen day\n") |
| 70 | |
| 71 | def set(self, setting): |
| 72 | if setting is None: |
| 73 | self.monkeypatch.delenv(SETTING, raising=False) |
| 74 | else: |
| 75 | self.monkeypatch.setenv(SETTING, setting) |
| 76 | |
| 77 | def rows(self, collection, text): |
| 78 | path = self.data / "collections" / collection / "records.tsv" |
| 79 | path.parent.mkdir(parents=True, exist_ok=True) |
| 80 | path.write_text(text) |
| 81 | |
| 82 | def raw(self, path, headers=()): |
| 83 | """(status, body bytes) exactly as the app sent them.""" |
| 84 | scope_headers = [(b"accept", b"application/json")] |
| 85 | scope_headers += [(k.encode("latin-1"), v.encode("latin-1")) for k, v in headers] |
| 86 | messages = [] |
| 87 | |
| 88 | async def receive(): |
| 89 | return {"type": "http.request", "body": b"", "more_body": False} |
| 90 | |
| 91 | async def send(message): |
| 92 | messages.append(message) |
| 93 | |
| 94 | scope = {"type": "http", "method": "GET", "path": path, "query_string": b"", |
| 95 | "headers": scope_headers, "client": ("127.0.0.1", 12345)} |
| 96 | asyncio.run(object_server.app(scope, receive, send)) |
| 97 | start = next(m for m in messages if m["type"] == "http.response.start") |
| 98 | return start["status"], b"".join( |
| 99 | m.get("body", b"") for m in messages if m["type"] == "http.response.body") |
| 100 | |
| 101 | def answers(self, requests=REQUESTS): |
| 102 | return [self.raw(path, headers) for path, headers in requests] |
| 103 | |
| 104 | def ids(self, collection, headers): |
| 105 | """The ids a list shows, [] when the list itself is refused.""" |
| 106 | status, body = self.raw(f"/collections/{collection}/records", headers) |
| 107 | if status == 403: |
| 108 | return [] |
| 109 | assert status == 200, body |
| 110 | return sorted(record["id"] for record in json.loads(body)["records"]) |
| 111 | |
| 112 | def not_applied(self): |
| 113 | return [index for index, rule in enumerate(object_permission_store.load_policy(self.data).rules) |
| 114 | if rule.not_applied] |
| 115 | |
| 116 | |
| 117 | def _widened(rule=TYPO): |
| 118 | """The rule as the engine reads it: the misspelt key gone.""" |
| 119 | return {k: v for k, v in rule.items() if k in object_permissions.RULE_KEYS and v is not None} |
| 120 | |
| 121 | |
| 122 | # ---- the setting itself ------------------------------------------------------ |
| 123 | |
| 124 | |
| 125 | @pytest.mark.parametrize("value,on", [ |
| 126 | (None, False), ("", False), ("0", False), ("false", False), ("off", False), ("no", False), |
| 127 | ("maybe", False), ("1", True), ("true", True), ("TRUE", True), (" yes ", True), ("on", True), |
| 128 | ]) |
| 129 | def test_the_setting_is_off_unless_set_to_a_true_value(monkeypatch, value, on): |
| 130 | if value is None: |
| 131 | monkeypatch.delenv(SETTING, raising=False) |
| 132 | else: |
| 133 | monkeypatch.setenv(SETTING, value) |
| 134 | assert object_permissions.FAIL_CLOSED_WIDENED_ALLOWS_ENV == SETTING |
| 135 | assert object_permissions.fail_closed_widened_allows() is on |
| 136 | |
| 137 | |
| 138 | # ---- off: nothing changes ---------------------------------------------------- |
| 139 | |
| 140 | |
| 141 | @pytest.mark.parametrize("setting", [None, "", "false", "0"]) |
| 142 | def test_off_every_answer_is_byte_for_byte_what_the_widened_rule_always_gave( |
| 143 | tmp_path, monkeypatch, setting): |
| 144 | """The reference is the same box with the rule written as the engine has |
| 145 | always read the typo (no filter): the old behaviour, spelt out.""" |
| 146 | box = FailClosedBox(tmp_path, monkeypatch, setting) |
| 147 | box.write_by_hand(policy(TYPO, LEADS_OWN, NEWS_PUBLIC)) |
| 148 | with_typo = box.answers() |
| 149 | loaded = object_permission_store.load_policy(box.data) |
| 150 | assert box.not_applied() == [] |
| 151 | assert box.ids("contacts", SALES_7) == ["c1", "c2"] # still every row, as before |
| 152 | |
| 153 | box.write_by_hand(policy(_widened(), LEADS_OWN, NEWS_PUBLIC)) |
| 154 | assert with_typo == box.answers() |
| 155 | assert loaded == object_permission_store.load_policy(box.data) |
| 156 | assert [status for status, _ in with_typo] == [200, 200, 403, 200, 200, 200, 404, 200] |
| 157 | |
| 158 | |
| 159 | def test_off_the_finding_says_the_rule_applies_more_widely_and_names_the_setting(tmp_path, monkeypatch): |
| 160 | box = FailClosedBox(tmp_path, monkeypatch) |
| 161 | box.write_by_hand(policy(TYPO)) |
| 162 | |
| 163 | status, permissions = box.call("/permissions/status", headers=box.admin) |
| 164 | [finding] = permissions["policy"]["findings"] |
| 165 | assert finding["serious"] is True and finding["applied"] is True |
| 166 | assert finding["today"] == ( |
| 167 | "the engine ignores this key, so this allow applies to every row, not only the rows " |
| 168 | f"the filter was meant to pick; {APPLIED_WIDELY}") |
| 169 | [warning] = [w for w in permissions["warnings"] if "rule 0 key 'rowfilter'" in w] |
| 170 | assert warning.startswith("Permission policy allows more than written, ") and APPLIED_WIDELY in warning |
| 171 | |
| 172 | status, admin_status = box.call("/admin/status", headers=box.admin) |
| 173 | [alert] = [a for a in admin_status["alerts"] if "Permission policy file has" in a] |
| 174 | assert APPLIED_WIDELY in alert and NOT_APPLIED not in alert |
| 175 | assert "Nothing was changed; the box decides as it did." in alert |
| 176 | assert REASON not in alert + json.dumps(permissions) |
| 177 | |
| 178 | |
| 179 | # ---- on: the widened allow grants nothing ------------------------------------- |
| 180 | |
| 181 | |
| 182 | def test_on_the_own_rows_allow_with_a_misspelt_row_filter_grants_nothing(tmp_path, monkeypatch): |
| 183 | box = FailClosedBox(tmp_path, monkeypatch, "true") |
| 184 | box.write_by_hand(policy(TYPO, LEADS_OWN, NEWS_PUBLIC)) |
| 185 | |
| 186 | # None of the rows: not the others' (the widening), and not user 7's own |
| 187 | # either -- the rule is absent, not repaired by guessing what was meant. |
| 188 | assert box.ids("contacts", SALES_7) == [] |
| 189 | assert box.ids("contacts", SALES_8) == [] |
| 190 | assert box.raw("/collections/contacts/records", SALES_7)[0] == 403 |
| 191 | assert box.raw("/collections/contacts/records/c2", SALES_7)[0] in (403, 404) |
| 192 | assert box.not_applied() == [0] |
| 193 | |
| 194 | # Correctly written rules in the same policy still grant, filter and all. |
| 195 | assert box.ids("leads", SALES_7) == ["l1"] |
| 196 | assert box.ids("leads", SALES_8) == ["l2"] |
| 197 | assert box.ids("news", []) == ["n1"] |
| 198 | |
| 199 | |
| 200 | def test_on_the_answers_are_those_of_a_policy_without_the_rule(tmp_path, monkeypatch): |
| 201 | box = FailClosedBox(tmp_path, monkeypatch, "on") |
| 202 | box.write_by_hand(policy(LEADS_OWN, TYPO, NEWS_PUBLIC)) |
| 203 | stopped = box.answers() |
| 204 | box.write_by_hand(policy(LEADS_OWN, NEWS_PUBLIC)) |
| 205 | assert stopped == box.answers() |
| 206 | |
| 207 | |
| 208 | @pytest.mark.parametrize("mistake,request_path", [ |
| 209 | ({"effect": "allow", "principal": "role:sales", "actions": ["read"], "colection": "leads"}, |
| 210 | "/collections/contacts/records"), |
| 211 | ({"effect": "allow", "principal": "role:sales", "actions": ["read"], "collection": None}, |
| 212 | "/collections/contacts/records"), |
| 213 | ({"effect": "allow", "principal": "role:sales", "actions": ["read"], "collection": "contacts", |
| 214 | "expires_at": None}, "/collections/contacts/records"), |
| 215 | ({"effect": "allow", "principal": "role:sales", "actions": ["read"], "collection": "contacts", |
| 216 | "denied_feilds": ["name"]}, "/collections/contacts/records"), |
| 217 | ], ids=["misspelt-collection", "null-collection", "null-expires_at", "misspelt-denied_fields"]) |
| 218 | def test_on_every_other_serious_allow_finding_stops_its_rule_too( |
| 219 | tmp_path, monkeypatch, mistake, request_path): |
| 220 | box = FailClosedBox(tmp_path, monkeypatch, None) |
| 221 | box.write_by_hand(policy(mistake, NEWS_PUBLIC)) |
| 222 | [finding] = object_permission_store.stored_policy_findings(box.data) |
| 223 | assert finding["serious"] is True and finding["applied"] is True |
| 224 | assert box.raw(request_path, SALES_7)[0] == 200 # applied, widely, while off |
| 225 | |
| 226 | box.set("1") |
| 227 | [finding] = object_permission_store.stored_policy_findings(box.data) |
| 228 | assert finding["serious"] is True and finding["applied"] is False |
| 229 | assert box.raw(request_path, SALES_7)[0] == 403 |
| 230 | assert box.ids("news", []) == ["n1"] |
| 231 | |
| 232 | |
| 233 | def test_on_a_mistake_that_is_not_serious_leaves_its_allow_applied(tmp_path, monkeypatch): |
| 234 | box = FailClosedBox(tmp_path, monkeypatch, "true") |
| 235 | box.write_by_hand(policy({**OWN_ROWS, "effect": "ALLOW"})) |
| 236 | [finding] = object_permission_store.stored_policy_findings(box.data) |
| 237 | assert finding["serious"] is False and "applied" not in finding |
| 238 | assert finding["today"] == "read as 'allow'" |
| 239 | assert box.ids("contacts", SALES_7) == ["c1"] and box.not_applied() == [] |
| 240 | |
| 241 | |
| 242 | def test_on_the_finding_the_alert_and_the_status_say_the_rule_is_not_applied(tmp_path, monkeypatch, capsys): |
| 243 | box = FailClosedBox(tmp_path, monkeypatch, "true") |
| 244 | box.write_by_hand(policy(NEWS_PUBLIC, {**TYPO, "package": "app-contacts"})) |
| 245 | |
| 246 | status, permissions = box.call("/permissions/status", headers=box.admin) |
| 247 | [finding] = permissions["policy"]["findings"] |
| 248 | assert (finding["index"], finding["package"], finding["key"]) == (1, "app-contacts", "rowfilter") |
| 249 | assert finding["serious"] is True and finding["applied"] is False |
| 250 | assert finding["today"] == ( |
| 251 | "the engine ignores this key, so this allow would apply to every row, not only the rows " |
| 252 | f"the filter was meant to pick; {NOT_APPLIED}") |
| 253 | assert finding["fix"] == "rename it to 'row_filter' and save the policy" |
| 254 | [warning] = [w for w in permissions["warnings"] if "key 'rowfilter'" in w] |
| 255 | assert NOT_APPLIED in warning and "Permission policy allows more than written" not in warning |
| 256 | |
| 257 | status, admin_status = box.call("/admin/status", headers=box.admin) |
| 258 | [alert] = [a for a in admin_status["alerts"] if "Permission policy file has" in a] |
| 259 | assert "rule 1 (package app-contacts) key 'rowfilter'" in alert |
| 260 | assert NOT_APPLIED in alert and "set DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS to stop" not in alert |
| 261 | assert "1 allow rule(s) named here are not applied" in alert |
| 262 | assert "the box decides as it did" not in alert |
| 263 | |
| 264 | status, unshipped = box.call("/permissions/unshipped", headers=box.admin) |
| 265 | assert unshipped["findings"] == [finding] |
| 266 | |
| 267 | object_server._note_policy_findings() |
| 268 | assert NOT_APPLIED in capsys.readouterr().err |
| 269 | assert REASON not in alert + json.dumps(permissions["warnings"]) + json.dumps(finding) |
| 270 | |
| 271 | |
| 272 | def test_on_the_rule_stays_in_the_file_and_must_still_be_fixed_to_grant(tmp_path, monkeypatch): |
| 273 | box = FailClosedBox(tmp_path, monkeypatch, "true") |
| 274 | box.write_by_hand(policy(NEWS_PUBLIC, TYPO)) |
| 275 | before = box.file_text() |
| 276 | |
| 277 | # GET still shows the rule (as the engine reads it), so it can be fixed. |
| 278 | status, body = box.call("/permissions/policy", headers=box.admin) |
| 279 | produced = body["policy"] |
| 280 | assert status == 200 and len(produced["rules"]) == 2 |
| 281 | assert "not_applied" not in json.dumps(produced) |
| 282 | |
| 283 | # Saving it back unfixed is refused, as with the setting off. |
| 284 | status, refused = box.call("/permissions/policy", "PUT", produced, box.admin) |
| 285 | assert status == 400 and refused["problems"][0]["key"] == "rowfilter" |
| 286 | assert NOT_APPLIED in refused["error"] |
| 287 | assert box.file_text() == before and box.ids("contacts", SALES_7) == [] |
| 288 | |
| 289 | # Fixed, it grants what was written. |
| 290 | produced["rules"][1]["row_filter"] = {"owner_id": "$user_id"} |
| 291 | assert box.call("/permissions/policy", "PUT", produced, box.admin)[0] == 200 |
| 292 | assert box.ids("contacts", SALES_7) == ["c1"] and box.not_applied() == [] |
| 293 | assert object_permission_store.stored_policy_findings(box.data) == [] |
| 294 | |
| 295 | |
| 296 | def test_the_setting_is_read_on_every_load_not_remembered_with_the_policy(tmp_path, monkeypatch): |
| 297 | import time |
| 298 | |
| 299 | box = FailClosedBox(tmp_path, monkeypatch) |
| 300 | box.write_by_hand(policy(TYPO)) |
| 301 | time.sleep(object_permission_store._POLICY_CACHE_RACY_NS / 1e9 + 0.03) # let the read be kept |
| 302 | assert box.ids("contacts", SALES_7) == ["c1", "c2"] |
| 303 | assert box.ids("contacts", SALES_7) == ["c1", "c2"] |
| 304 | box.set("true") |
| 305 | assert box.ids("contacts", SALES_7) == [] |
| 306 | assert box.ids("contacts", SALES_7) == [] |
| 307 | box.set("false") |
| 308 | assert box.ids("contacts", SALES_7) == ["c1", "c2"] |
| 309 | |
| 310 | |
| 311 | # ---- deny rules are untouched in every case ----------------------------------- |
| 312 | |
| 313 | |
| 314 | @pytest.mark.parametrize("deny_rule,key,seen", [ |
| 315 | # A deny that never applies (serious): stays off, on and off. |
| 316 | ({"principal": "sales"}, "principal", ["c1", "c2"]), |
| 317 | ({"expires_at": "next week"}, "expires_at", ["c1", "c2"]), |
| 318 | ({"row_filter": {"owner_id": "$userid"}}, "row_filter", ["c1", "c2"]), |
| 319 | # A deny whose narrowing key was dropped: applies to every row, on and off. |
| 320 | ({"rowfilter": {"owner_id": "8"}}, "rowfilter", []), |
| 321 | ({"collection": None}, "collection", []), |
| 322 | ], ids=["principal", "expires_at", "row_filter", "misspelt-row_filter", "null-collection"]) |
| 323 | def test_a_deny_with_a_finding_behaves_the_same_on_and_off(tmp_path, monkeypatch, deny_rule, key, seen): |
| 324 | grant = {k: v for k, v in OWN_ROWS.items() if k != "row_filter"} # every row, as written |
| 325 | deny = {"effect": "deny", "principal": "role:sales", "actions": ["read"], |
| 326 | "collection": "contacts", **deny_rule} |
| 327 | box = FailClosedBox(tmp_path, monkeypatch) |
| 328 | box.write_by_hand(policy(grant, deny, LEADS_OWN, NEWS_PUBLIC)) |
| 329 | |
| 330 | off = box.answers() |
| 331 | findings_off = object_permission_store.stored_policy_findings(box.data) |
| 332 | assert box.ids("contacts", SALES_7) == seen |
| 333 | box.set("true") |
| 334 | assert box.answers() == off |
| 335 | assert box.ids("contacts", SALES_7) == seen |
| 336 | assert box.not_applied() == [] |
| 337 | |
| 338 | # The finding reads the same too: nothing about a deny depends on the setting. |
| 339 | [finding] = findings_off |
| 340 | assert (finding["index"], finding["key"]) == (1, key) and "applied" not in finding |
| 341 | assert object_permission_store.stored_policy_findings(box.data) == findings_off |
| 342 | assert NOT_APPLIED not in finding["today"] and SETTING not in finding["today"] |
| 343 | |
| 344 | |
| 345 | def test_on_a_serious_deny_beside_a_widened_allow_only_the_allow_is_stopped(tmp_path, monkeypatch): |
| 346 | deny = {"effect": "deny", "principal": "sales", "actions": ["read"], "collection": "leads"} |
| 347 | box = FailClosedBox(tmp_path, monkeypatch, "true") |
| 348 | box.write_by_hand(policy(TYPO, deny, LEADS_OWN)) |
| 349 | assert box.not_applied() == [0] |
| 350 | assert box.ids("contacts", SALES_7) == [] |
| 351 | assert box.ids("leads", SALES_7) == ["l1"] # the deny matches nobody, as always |
| 352 | by_index = {f["index"]: f for f in object_permission_store.stored_policy_findings(box.data)} |
| 353 | assert by_index[0]["applied"] is False and "applied" not in by_index[1] |
| 354 | |
| 355 | |
| 356 | # ---- package rules installed the normal way ----------------------------------- |
| 357 | |
| 358 | |
| 359 | def _install_notes(box): |
| 360 | pending = ["app-notes", "app-projects", "app-views"] |
| 361 | while pending: # dependencies first: retry until nothing more installs |
| 362 | installed = [] |
| 363 | for package_id in pending: |
| 364 | try: |
| 365 | object_packages.install_package(package_id, root=PACKAGES_ROOT, base_dir=box.data, |
| 366 | object_roots=[box.objects]) |
| 367 | except object_packages.PackageInstallError: |
| 368 | continue |
| 369 | installed.append(package_id) |
| 370 | assert installed, f"these packages do not install: {pending}" |
| 371 | pending = [package_id for package_id in pending if package_id not in installed] |
| 372 | |
| 373 | |
| 374 | def _notes_box(tmp_path, monkeypatch, setting): |
| 375 | box = FailClosedBox(tmp_path, monkeypatch, setting) |
| 376 | object_permission_store.replace_policy(object_permission_store.starter_policy_payload(), box.data) |
| 377 | _install_notes(box) |
| 378 | return box |
| 379 | |
| 380 | |
| 381 | NOTE_REQUESTS = [ |
| 382 | ("/collections/notes/records", [("x-dbbasic-user-id", "7")]), |
| 383 | ("/collections/notes/records", [("x-dbbasic-user-id", "8")]), |
| 384 | ("/collections/notes/records", []), |
| 385 | ("/collections/projects/records", [("x-dbbasic-user-id", "7")]), |
| 386 | ] |
| 387 | |
| 388 | |
| 389 | def test_package_rules_installed_the_normal_way_are_unaffected(tmp_path, monkeypatch): |
| 390 | off = _notes_box(tmp_path / "off", monkeypatch, None) |
| 391 | off_file = off.file_text() |
| 392 | off_answers = off.answers(NOTE_REQUESTS) |
| 393 | assert object_permission_store.stored_policy_findings(off.data) == [] |
| 394 | assert off_answers[0][0] == 200 # a signed-in user reaches their notes |
| 395 | off.set("true") # the same box, switched on: the same bytes |
| 396 | assert off.answers(NOTE_REQUESTS) == off_answers and off.not_applied() == [] |
| 397 | |
| 398 | on = _notes_box(tmp_path / "on", monkeypatch, "true") # installed while on |
| 399 | assert on.file_text() == off_file # the installer writes the same policy |
| 400 | assert object_permission_store.stored_policy_findings(on.data) == [] |
| 401 | assert on.not_applied() == [] |
| 402 | stored = json.loads(on.file_text()) |
| 403 | assert {"app-notes", "app-projects"} <= {rule.get("package") for rule in stored["rules"]} |
| 404 | assert [status for status, _ in on.answers(NOTE_REQUESTS)] == [status for status, _ in off_answers] |
| 405 | |
| 406 | |
| 407 | def test_on_an_install_beside_a_stopped_rule_keeps_it_in_the_file_and_stopped(tmp_path, monkeypatch): |
| 408 | """The installer loads the policy, adds its rules and saves: the stopped |
| 409 | rule must come through that neither lost nor switched back on.""" |
| 410 | box = FailClosedBox(tmp_path, monkeypatch, "true") |
| 411 | box.write_by_hand(policy(TYPO, NEWS_PUBLIC)) |
| 412 | _install_notes(box) |
| 413 | stored = json.loads(box.file_text()) |
| 414 | assert len(stored["rules"]) > 2 |
| 415 | # Written back as the file held it, misspelt key and all: written as the |
| 416 | # engine reads it, the finding would be gone and the rule back on. |
| 417 | assert stored["rules"][0] == TYPO |
| 418 | [finding] = object_permission_store.stored_policy_findings(box.data) |
| 419 | assert (finding["index"], finding["key"], finding["applied"]) == (0, "rowfilter", False) |
| 420 | assert box.not_applied() == [0] |
| 421 | assert box.ids("contacts", SALES_7) == [] |
| 422 | assert box.ids("news", []) == ["n1"] |
| 423 | assert box.raw("/collections/notes/records", [("x-dbbasic-user-id", "7")])[0] == 200 |
| 424 | |
| 425 | # Installing again (the retraction pass and the merge both run) leaves it alone. |
| 426 | object_packages.install_package("app-notes", root=PACKAGES_ROOT, base_dir=box.data, |
| 427 | object_roots=[box.objects], allow_replace=True) |
| 428 | assert json.loads(box.file_text())["rules"][0] == TYPO |
| 429 | assert box.ids("contacts", SALES_7) == [] |
| 430 | |
| 431 | |
| 432 | def test_a_stopped_rule_whose_stored_form_is_gone_is_not_saved_as_applied(tmp_path, monkeypatch): |
| 433 | box = FailClosedBox(tmp_path, monkeypatch, "true") |
| 434 | box.write_by_hand(policy(TYPO, NEWS_PUBLIC)) |
| 435 | loaded = object_permission_store.load_policy(box.data) |
| 436 | assert loaded.rules[0].not_applied |
| 437 | box.write_by_hand(policy(NEWS_PUBLIC)) # the file changed under the holder of `loaded` |
| 438 | before = box.file_text() |
| 439 | with pytest.raises(ValueError, match="not saved"): |
| 440 | object_permission_store.save_policy(loaded, box.data) |
| 441 | assert box.file_text() == before |
| 442 | |
| 443 | |
| 444 | def test_off_an_install_keeps_the_stored_mistake_its_finding_and_every_decision(tmp_path, monkeypatch): |
| 445 | """A package install loads the policy, adds its rules and saves. It used |
| 446 | to write the typo'd rule back as the engine reads it: the misspelt key |
| 447 | gone, the finding and alert gone, the rule now simply "an allow on every |
| 448 | row". It is written back as the file held it, so the engine reads it as |
| 449 | it did and the report survives.""" |
| 450 | box = FailClosedBox(tmp_path, monkeypatch) |
| 451 | deny = {"effect": "deny", "principal": "sales", "actions": ["read"], "collection": "leads"} |
| 452 | box.write_by_hand(policy(TYPO, deny, LEADS_OWN, NEWS_PUBLIC)) |
| 453 | before = box.answers() |
| 454 | findings = object_permission_store.stored_policy_findings(box.data) |
| 455 | assert sorted((f["index"], f["key"], f["serious"]) for f in findings) == [ |
| 456 | (0, "rowfilter", True), (1, "principal", True)] |
| 457 | loaded = object_permission_store.load_policy(box.data).rules[:4] |
| 458 | |
| 459 | _install_notes(box) |
| 460 | |
| 461 | assert box.answers() == before # byte for byte |
| 462 | assert box.ids("contacts", SALES_7) == ["c1", "c2"] # still every row: off changes no decision |
| 463 | stored = json.loads(box.file_text()) |
| 464 | assert len(stored["rules"]) > 4 |
| 465 | assert stored["rules"][0] == TYPO and stored["rules"][1] == deny |
| 466 | assert object_permission_store.load_policy(box.data).rules[:4] == loaded |
| 467 | assert object_permission_store.stored_policy_findings(box.data) == findings |
| 468 | status, admin_status = box.call("/admin/status", headers=box.admin) |
| 469 | [alert] = [a for a in admin_status["alerts"] if "Permission policy file has" in a] |
| 470 | assert "rule 0 key 'rowfilter'" in alert and APPLIED_WIDELY in alert |
| 471 | assert box.raw("/collections/notes/records", [("x-dbbasic-user-id", "7")])[0] == 200 |
| 472 | |
| 473 | # A second pass (retraction and merge both run) changes nothing more. |
| 474 | object_packages.install_package("app-notes", root=PACKAGES_ROOT, base_dir=box.data, |
| 475 | object_roots=[box.objects], allow_replace=True) |
| 476 | assert json.loads(box.file_text())["rules"][0] == TYPO |
| 477 | assert box.answers() == before |
| 478 | |
| 479 | # And the operator can still fix it: their own save is written as given. |
| 480 | status, body = box.call("/permissions/policy", headers=box.admin) |
| 481 | body["policy"]["rules"][0]["row_filter"] = {"owner_id": "$user_id"} |
| 482 | body["policy"]["rules"][1]["principal"] = "role:nobody" |
| 483 | assert box.call("/permissions/policy", "PUT", body["policy"], box.admin)[0] == 200 |
| 484 | assert object_permission_store.stored_policy_findings(box.data) == [] |
| 485 | assert box.ids("contacts", SALES_7) == ["c1"] |
| 486 | |
| 487 | |
| 488 | def test_off_a_policy_without_a_stored_mistake_is_saved_as_it_always_was(tmp_path, monkeypatch): |
| 489 | box = FailClosedBox(tmp_path, monkeypatch) |
| 490 | box.write_by_hand(policy({**OWN_ROWS, "effect": "ALLOW"}, NEWS_PUBLIC)) # not serious |
| 491 | loaded = object_permission_store.load_policy(box.data) |
| 492 | object_permission_store.save_policy(loaded, box.data) |
| 493 | assert json.loads(box.file_text()) == object_permissions.policy_to_dict(loaded) |
| 494 | |
| 495 | |
| 496 | def test_a_written_twin_of_a_stored_mistake_is_not_given_the_mistake(tmp_path, monkeypatch): |
| 497 | """One stored rule with the typo, one written the wide way on purpose: |
| 498 | only one rule gets the stored form back.""" |
| 499 | box = FailClosedBox(tmp_path, monkeypatch) |
| 500 | box.write_by_hand(policy(_widened(), TYPO)) |
| 501 | object_permission_store.save_policy(object_permission_store.load_policy(box.data), box.data) |
| 502 | rules = json.loads(box.file_text())["rules"] |
| 503 | assert [("rowfilter" in rule) for rule in rules].count(True) == 1 and len(rules) == 2 |
| 504 | assert len(object_permission_store.stored_policy_findings(box.data)) == 1 |
| 505 | |
| 506 | |
| 507 | @pytest.mark.parametrize("setting", [None, "true"]) |
| 508 | def test_an_install_keeps_a_misspelt_policy_key_its_finding_and_every_decision(tmp_path, monkeypatch, setting): |
| 509 | """`rulez` and `admin_role` are keys the engine ignores, so the loaded |
| 510 | policy does not carry them and an install used to write the file without |
| 511 | them: the finding and its alert vanished. They are written back as the |
| 512 | file held them; the engine goes on ignoring them.""" |
| 513 | box = FailClosedBox(tmp_path, monkeypatch, setting) |
| 514 | box.write_by_hand({"access_mode": "role_based", "rulez": [OWN_ROWS], "admin_role": ["boss"], |
| 515 | "rules": [LEADS_OWN, NEWS_PUBLIC]}) |
| 516 | before = box.answers() |
| 517 | findings = object_permission_store.stored_policy_findings(box.data) |
| 518 | assert sorted((f["index"], f["key"], f["serious"]) for f in findings) == [ |
| 519 | (None, "admin_role", True), (None, "rulez", True)] |
| 520 | loaded = object_permission_store.load_policy(box.data) |
| 521 | |
| 522 | _install_notes(box) |
| 523 | |
| 524 | assert box.answers() == before # byte for byte |
| 525 | stored = json.loads(box.file_text()) |
| 526 | assert stored["rulez"] == [OWN_ROWS] and stored["admin_role"] == ["boss"] |
| 527 | assert len(stored["rules"]) > 2 |
| 528 | after = object_permission_store.load_policy(box.data) |
| 529 | assert after.rules[:2] == loaded.rules and after.admin_roles == loaded.admin_roles |
| 530 | kept = object_permission_store.stored_policy_findings(box.data) # in the file's (now sorted) key order |
| 531 | assert sorted(kept, key=lambda f: f["key"]) == sorted(findings, key=lambda f: f["key"]) |
| 532 | status, admin_status = box.call("/admin/status", headers=box.admin) |
| 533 | [alert] = [a for a in admin_status["alerts"] if "Permission policy file has" in a] |
| 534 | assert "'rulez'" in alert and "'admin_role'" in alert |
| 535 | |
| 536 | # A second pass (retraction and merge both run) changes nothing more. |
| 537 | object_packages.install_package("app-notes", root=PACKAGES_ROOT, base_dir=box.data, |
| 538 | object_roots=[box.objects], allow_replace=True) |
| 539 | again = json.loads(box.file_text()) |
| 540 | assert again["rulez"] == [OWN_ROWS] and again["admin_role"] == ["boss"] |
| 541 | assert box.answers() == before |
| 542 | |
| 543 | # The operator's own save is written as given: nothing is carried over, |
| 544 | # and it is still refused until it writes what the keys were meant as. |
| 545 | status, body = box.call("/permissions/policy", headers=box.admin) |
| 546 | assert "rulez" not in body["policy"] |
| 547 | assert box.call("/permissions/policy", "PUT", body["policy"], box.admin)[0] == 400 |
| 548 | assert json.loads(box.file_text()) == again |
| 549 | body["policy"]["rules"].append(OWN_ROWS) |
| 550 | body["policy"]["admin_roles"] = ["boss"] |
| 551 | assert box.call("/permissions/policy", "PUT", body["policy"], box.admin)[0] == 200 |
| 552 | fixed = json.loads(box.file_text()) |
| 553 | assert "rulez" not in fixed and "admin_role" not in fixed |
| 554 | assert object_permission_store.stored_policy_findings(box.data) == [] |
| 555 | |
| 556 | |
| 557 | def test_an_unknown_policy_key_that_is_not_serious_is_dropped_as_it_always_was(tmp_path, monkeypatch): |
| 558 | box = FailClosedBox(tmp_path, monkeypatch) |
| 559 | box.write_by_hand({**policy(NEWS_PUBLIC), "comment": "written by hand", "rulez": [OWN_ROWS]}) |
| 560 | assert sorted((f["key"], f["serious"]) for f in object_permission_store.stored_policy_findings(box.data)) == [ |
| 561 | ("comment", False), ("rulez", True)] |
| 562 | loaded = object_permission_store.load_policy(box.data) |
| 563 | object_permission_store.save_policy(loaded, box.data) |
| 564 | assert json.loads(box.file_text()) == {**object_permissions.policy_to_dict(loaded), "rulez": [OWN_ROWS]} |
| 565 | |
| 566 | box.write_by_hand({**policy(NEWS_PUBLIC), "comment": "written by hand"}) |
| 567 | object_permission_store.save_policy(loaded, box.data) |
| 568 | assert json.loads(box.file_text()) == object_permissions.policy_to_dict(loaded) |
| 569 | |
| 570 | |
| 571 | def test_a_save_that_is_the_operators_own_does_not_carry_a_policy_key_over(tmp_path, monkeypatch): |
| 572 | box = FailClosedBox(tmp_path, monkeypatch) |
| 573 | box.write_by_hand({"access_mode": "role_based", "rulez": [OWN_ROWS]}) |
| 574 | loaded = object_permission_store.load_policy(box.data) |
| 575 | object_permission_store.save_policy(loaded, box.data, keep_stored_mistakes=False) |
| 576 | assert json.loads(box.file_text()) == object_permissions.policy_to_dict(loaded) |
| 577 | |
| 578 | |
| 579 | # ---- on, and the findings cannot be worked out: no policy --------------------- |
| 580 | |
| 581 | |
| 582 | def test_on_findings_that_cannot_be_computed_fail_closed_like_an_unreadable_policy(tmp_path, monkeypatch): |
| 583 | box = FailClosedBox(tmp_path, monkeypatch, "true") |
| 584 | path = object_permission_store.policy_path(box.data) |
| 585 | box.write_by_hand(policy(TYPO, LEADS_OWN, NEWS_PUBLIC)) |
| 586 | path.write_text("{not json") # what the engine already does with no usable policy |
| 587 | with pytest.raises(ValueError): |
| 588 | object_permission_store.load_policy(box.data) |
| 589 | unreadable = box.answers() |
| 590 | assert all(status != 200 for status, _ in unreadable) |
| 591 | |
| 592 | box.write_by_hand(policy(TYPO, LEADS_OWN, NEWS_PUBLIC)) |
| 593 | |
| 594 | def boom(*args, **kwargs): |
| 595 | raise RuntimeError("made-up failure") |
| 596 | |
| 597 | monkeypatch.setattr(object_permissions, "policy_declaration_problems", boom) |
| 598 | with pytest.raises(ValueError, match="could not be checked for allow rules"): |
| 599 | object_permission_store.load_policy(box.data) |
| 600 | # The same answers, byte for byte: no new failure mode, nobody served on a guess. |
| 601 | assert box.answers() == unreadable |
| 602 | |
| 603 | # With the setting off the findings are not consulted for a decision. |
| 604 | box.set(None) |
| 605 | assert box.ids("contacts", SALES_7) == ["c1", "c2"] |
| 606 | assert box.ids("leads", SALES_7) == ["l1"] |