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_wide_permission_rules.py · 10.4 KB · 225 lines
| 1 | """A wide allow rule is visible, not silently left in force. |
| 2 | |
| 3 | The starter policy used to ship an allow for `registered` on read and execute |
| 4 | with no collection and no object_id (see tests/test_starter_policy_scope.py). |
| 5 | A box that started from it still has the rule, and nothing may remove it for |
| 6 | the operator: it carries no `package` tag, so a package upgrade's retraction |
| 7 | never touches it, and the server does not delete an operator's rule on its |
| 8 | own. What it can do is say so -- in GET /permissions/unshipped and in the |
| 9 | startup log -- and these tests pin that, plus the documented way out (read the |
| 10 | policy, drop the rule, write it back). |
| 11 | """ |
| 12 | |
| 13 | from __future__ import annotations |
| 14 | |
| 15 | import asyncio |
| 16 | import json |
| 17 | from pathlib import Path |
| 18 | |
| 19 | import pytest |
| 20 | |
| 21 | import object_identity |
| 22 | import object_packages |
| 23 | import object_permission_store |
| 24 | import object_permissions |
| 25 | import object_server |
| 26 | |
| 27 | ROOT = Path(__file__).resolve().parents[1] |
| 28 | PACKAGES_ROOT = ROOT / "packages" |
| 29 | ADMIN_TOKEN = "unit-test-only-admin-token" |
| 30 | |
| 31 | # The rule the starter policy used to ship, as an existing box holds it. |
| 32 | LEGACY_RULE = { |
| 33 | "effect": "allow", "principal": "registered", "actions": ["read", "execute"], |
| 34 | "reason": "signed-in users can read and run objects", |
| 35 | } |
| 36 | |
| 37 | |
| 38 | def rule(**kwargs): |
| 39 | base = {"effect": "allow", "principal": "registered", "actions": ["read"]} |
| 40 | return object_permissions.rule_from_dict({**base, **kwargs}) |
| 41 | |
| 42 | |
| 43 | # ---- what counts as wide ---------------------------------------------------- |
| 44 | |
| 45 | |
| 46 | @pytest.mark.parametrize("payload", [ |
| 47 | {"principal": "registered"}, |
| 48 | {"principal": "public", "actions": ["execute"]}, |
| 49 | {"principal": "registered", "actions": ["read", "execute"], "row_filter": {"owner_id": "$user_id"}}, |
| 50 | ]) |
| 51 | def test_an_allow_for_everyone_signed_in_or_not_that_names_no_resource_is_wide(payload): |
| 52 | why = object_permissions.wide_rule_reason(rule(**payload)) |
| 53 | assert why and "EVERY object and collection" in why and "\n" not in why |
| 54 | |
| 55 | |
| 56 | @pytest.mark.parametrize("payload", [ |
| 57 | {"collection": "notes"}, |
| 58 | {"object_id": "site_home", "actions": ["execute"]}, |
| 59 | {"collection": "notes", "object_id": "site_home"}, |
| 60 | {"principal": "role:manager"}, |
| 61 | {"principal": "owner"}, |
| 62 | {"principal": "user:42"}, |
| 63 | {"effect": "deny"}, |
| 64 | ]) |
| 65 | def test_a_rule_that_names_a_resource_or_is_not_for_everyone_is_not_wide(payload): |
| 66 | assert object_permissions.wide_rule_reason(rule(**payload)) is None |
| 67 | |
| 68 | |
| 69 | def test_the_explanation_names_who_and_what(): |
| 70 | why = object_permissions.wide_rule_reason(object_permissions.rule_from_dict(LEGACY_RULE)) |
| 71 | assert "every signed-in user" in why and "execute, read" in why |
| 72 | |
| 73 | |
| 74 | # ---- a box that still has it ------------------------------------------------ |
| 75 | |
| 76 | |
| 77 | class Box: |
| 78 | def __init__(self, tmp_path, monkeypatch, *, wide): |
| 79 | self.data = tmp_path / "data" |
| 80 | self.root = tmp_path / "objects" |
| 81 | self.root.mkdir(parents=True, exist_ok=True) |
| 82 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(self.data)) |
| 83 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(self.root)) |
| 84 | monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", ADMIN_TOKEN) |
| 85 | monkeypatch.setenv("DBBASIC_PACKAGES_DIR", str(PACKAGES_ROOT)) |
| 86 | monkeypatch.setenv("DBBASIC_ENABLE_SITE_ROUTES", "true") |
| 87 | monkeypatch.setenv("DBBASIC_ENABLE_PERMISSION_ENFORCEMENT", "true") |
| 88 | for name in ("DBBASIC_OBJECT_TIMEOUT_SECONDS", "DBBASIC_WORKER_POOL_SIZE", |
| 89 | "DBBASIC_ROW_FILTER_INDEX", "DBBASIC_TRUSTED_IN_PROCESS_OBJECTS", |
| 90 | "DBBASIC_ALLOW_UNREADY_PERMISSION_ENFORCEMENT", |
| 91 | "DBBASIC_ENABLE_SESSION_ADMIN_GATES", "DBBASIC_PRIVATE_PACKAGES_DIR"): |
| 92 | monkeypatch.delenv(name, raising=False) |
| 93 | self.admin = [("authorization", f"Token {ADMIN_TOKEN}")] |
| 94 | payload = object_permission_store.starter_policy_payload() |
| 95 | if wide: |
| 96 | payload["rules"].insert(4, dict(LEGACY_RULE)) |
| 97 | object_permission_store.replace_policy(payload, self.data) |
| 98 | for package in ("app-finance", "app-payments", "app-invoices", "app-billing"): |
| 99 | object_packages.install_package( |
| 100 | package, root=PACKAGES_ROOT, base_dir=self.data, object_roots=[self.root]) |
| 101 | self.user("probe-user") |
| 102 | |
| 103 | def user(self, user_id): |
| 104 | object_identity.create_user({"user_id": user_id, "roles": []}, base_dir=self.data) |
| 105 | session = object_identity.create_session({"user_id": user_id}, base_dir=self.data) |
| 106 | return [("authorization", f"Bearer {session['token']}")] |
| 107 | |
| 108 | def call(self, path, method="GET", payload=None, headers=()): |
| 109 | body = json.dumps(payload).encode("utf-8") if payload is not None else b"" |
| 110 | scope_headers = [(b"accept", b"application/json"), (b"content-type", b"application/json")] |
| 111 | scope_headers += [(k.encode("latin-1"), v.encode("latin-1")) for k, v in headers] |
| 112 | messages = [] |
| 113 | |
| 114 | async def receive(): |
| 115 | return {"type": "http.request", "body": body, "more_body": False} |
| 116 | |
| 117 | async def send(message): |
| 118 | messages.append(message) |
| 119 | |
| 120 | scope = {"type": "http", "method": method, "path": path, "query_string": b"", |
| 121 | "headers": scope_headers, "client": ("127.0.0.1", 12345)} |
| 122 | asyncio.run(object_server.app(scope, receive, send)) |
| 123 | start = next(m for m in messages if m["type"] == "http.response.start") |
| 124 | raw = b"".join(m.get("body", b"") for m in messages if m["type"] == "http.response.body") |
| 125 | return start["status"], json.loads(raw.decode("utf-8")) |
| 126 | |
| 127 | |
| 128 | def test_the_unshipped_report_flags_the_wide_rule_and_only_that_one(tmp_path, monkeypatch): |
| 129 | box = Box(tmp_path, monkeypatch, wide=True) |
| 130 | alice = box.user("alice") |
| 131 | assert box.call("/permissions/unshipped", headers=alice)[0] in (401, 403) |
| 132 | |
| 133 | status, body = box.call("/permissions/unshipped", headers=box.admin) |
| 134 | assert status == 200 |
| 135 | flagged = [entry for entry in body["rules"] if "wide" in entry] |
| 136 | assert [(e["index"], e["state"], e["package"], e["rule"]["reason"]) for e in flagged] == [ |
| 137 | (4, "operator", None, LEGACY_RULE["reason"])] |
| 138 | assert "EVERY object and collection" in flagged[0]["wide"] |
| 139 | assert [(w["index"], w["package"]) for w in body["wide_rules"]] == [(4, None)] |
| 140 | assert body["wide_rules"][0]["why"] == flagged[0]["wide"] |
| 141 | # The rest of the report is what it was: the starter rules are unshipped |
| 142 | # operator rules and carry no flag. |
| 143 | assert {e["state"] for e in body["rules"]} == {"operator"} |
| 144 | assert len(body["rules"]) == 6 |
| 145 | |
| 146 | |
| 147 | def test_a_fresh_box_has_nothing_wide(tmp_path, monkeypatch): |
| 148 | box = Box(tmp_path, monkeypatch, wide=False) |
| 149 | status, body = box.call("/permissions/unshipped", headers=box.admin) |
| 150 | assert status == 200 |
| 151 | assert body["wide_rules"] == [] and not any("wide" in entry for entry in body["rules"]) |
| 152 | |
| 153 | |
| 154 | def test_a_wide_rule_a_package_ships_is_still_reported(tmp_path, monkeypatch): |
| 155 | """A rule a package ships is not in `rules` (it is the package's), but it |
| 156 | is no less wide for that; `wide_rules` covers the whole policy.""" |
| 157 | box = Box(tmp_path, monkeypatch, wide=False) |
| 158 | policy = object_permission_store.load_policy(box.data) |
| 159 | tagged = object_permissions.rule_from_dict({**LEGACY_RULE, "package": "app-billing"}) |
| 160 | object_permission_store.save_policy( |
| 161 | object_permissions.PermissionPolicy( |
| 162 | access_mode=policy.access_mode, rules=policy.rules + (tagged,), |
| 163 | roles=policy.roles, user_roles=policy.user_roles, admin_roles=policy.admin_roles), |
| 164 | base_dir=box.data) |
| 165 | status, body = box.call("/permissions/unshipped", headers=box.admin) |
| 166 | assert status == 200 |
| 167 | assert [(w["package"], w["index"]) for w in body["wide_rules"]] == [("app-billing", len(policy.rules))] |
| 168 | |
| 169 | |
| 170 | def test_the_wide_rule_is_not_removed_for_the_operator_by_an_upgrade(tmp_path, monkeypatch): |
| 171 | """The reason it is reported: no package install removes it.""" |
| 172 | box = Box(tmp_path, monkeypatch, wide=True) |
| 173 | for package in ("app-finance", "app-payments", "app-invoices", "app-billing"): |
| 174 | object_packages.install_package( |
| 175 | package, root=PACKAGES_ROOT, base_dir=box.data, object_roots=[box.root], |
| 176 | allow_replace=True) |
| 177 | rules = object_permission_store.load_policy(box.data).rules |
| 178 | assert sum(1 for r in rules if object_permissions.wide_rule_reason(r)) == 1 |
| 179 | |
| 180 | |
| 181 | def test_the_startup_log_names_the_wide_rule(tmp_path, monkeypatch, capsys): |
| 182 | Box(tmp_path, monkeypatch, wide=True) |
| 183 | object_server._note_wide_permission_rules() |
| 184 | err = capsys.readouterr().err |
| 185 | assert "WIDE permission rule #4" in err |
| 186 | assert LEGACY_RULE["reason"] in err and "GET /permissions/unshipped" in err |
| 187 | |
| 188 | |
| 189 | def test_the_startup_log_is_quiet_on_a_fresh_box_and_when_checks_are_off(tmp_path, monkeypatch, capsys): |
| 190 | Box(tmp_path, monkeypatch, wide=False) |
| 191 | object_server._note_wide_permission_rules() |
| 192 | assert capsys.readouterr().err == "" |
| 193 | |
| 194 | object_permission_store.replace_policy( |
| 195 | {"access_mode": "role_based", "rules": [LEGACY_RULE]}, tmp_path / "data") |
| 196 | object_server._note_wide_permission_rules() |
| 197 | assert "WIDE permission rule #0" in capsys.readouterr().err |
| 198 | monkeypatch.delenv("DBBASIC_ENABLE_PERMISSION_ENFORCEMENT") |
| 199 | monkeypatch.delenv("DBBASIC_ENABLE_PERMISSION_AUDIT", raising=False) |
| 200 | object_server._note_wide_permission_rules() |
| 201 | assert capsys.readouterr().err == "" |
| 202 | |
| 203 | |
| 204 | def test_the_documented_removal_works_and_takes_the_reach_away(tmp_path, monkeypatch): |
| 205 | """GET /permissions/policy, drop the rule, PUT it back: the user loses |
| 206 | exactly what only the rule gave them and keeps what a package grants.""" |
| 207 | box = Box(tmp_path, monkeypatch, wide=True) |
| 208 | alice = box.user("alice") |
| 209 | assert box.call("/objects/system_billing_runner", method="POST", payload={}, headers=alice)[0] == 200 |
| 210 | assert box.call("/collections/billing_plans/records", headers=alice)[0] == 200 |
| 211 | |
| 212 | status, body = box.call("/permissions/policy", headers=box.admin) |
| 213 | assert status == 200 |
| 214 | policy = body["policy"] |
| 215 | policy["rules"] = [r for r in policy["rules"] |
| 216 | if not (r["effect"] == "allow" and r["principal"] in ("registered", "public") |
| 217 | and not r.get("collection") and not r.get("object_id"))] |
| 218 | status, body = box.call("/permissions/policy", method="PUT", payload={"policy": policy}, |
| 219 | headers=box.admin) |
| 220 | assert status == 200, body |
| 221 | |
| 222 | assert box.call("/objects/system_billing_runner", method="POST", payload={}, headers=alice)[0] == 403 |
| 223 | assert box.call("/collections/billing_plans/records", headers=alice)[0] == 200 |
| 224 | status, body = box.call("/permissions/unshipped", headers=box.admin) |
| 225 | assert body["wide_rules"] == [] |