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_starter_policy_scope.py · 13.2 KB · 285 lines
| 1 | """The starter policy grants a signed-in user nothing a package did not. |
| 2 | |
| 3 | `object_permission_store.starter_policy_payload()` is the policy a fresh |
| 4 | deployment starts with. It used to carry an allow rule for the `registered` |
| 5 | principal on `read` and `execute` with no collection and no object_id: |
| 6 | |
| 7 | {"effect": "allow", "principal": "registered", |
| 8 | "actions": ["read", "execute"], |
| 9 | "reason": "signed-in users can read and run objects"} |
| 10 | |
| 11 | A rule with no resource matches every resource (`_resource_matches`), and |
| 12 | `check_permission` returns the first allow rule that matches, in policy order, |
| 13 | without comparing it with the others. So on a box that started from the |
| 14 | starter policy every signed-in account -- and with open signup that is anyone |
| 15 | with an email address -- could run every object (the billing runner, the |
| 16 | recurring-journal runner, the sweepers, every hook, the T&M invoice generator |
| 17 | the package restricts to `role:manager`) and read every collection (the email |
| 18 | outbox, scheduler runs, page views), and the row filters the packages ship on |
| 19 | `wallets`, `wallet_entries` and the rest decided nothing, because the broad |
| 20 | rule matched each row first. |
| 21 | |
| 22 | The owner dropped the rule from their live box and the 31 pages they checked |
| 23 | did not change: what users need is granted by the packages. These tests run |
| 24 | a fresh box (starter policy first, then the real packages, enforcement on, |
| 25 | real sessions) and pin both halves: the reach the rule used to give is gone, |
| 26 | and what the packages grant still works. |
| 27 | """ |
| 28 | |
| 29 | from __future__ import annotations |
| 30 | |
| 31 | import asyncio |
| 32 | import json |
| 33 | from pathlib import Path |
| 34 | |
| 35 | import pytest |
| 36 | |
| 37 | import object_identity |
| 38 | import object_packages |
| 39 | import object_permission_store |
| 40 | import object_permissions |
| 41 | import object_records |
| 42 | import object_server |
| 43 | |
| 44 | ROOT = Path(__file__).resolve().parents[1] |
| 45 | PACKAGES_ROOT = ROOT / "packages" |
| 46 | ADMIN_TOKEN = "unit-test-only-admin-token" |
| 47 | |
| 48 | |
| 49 | def _closure(names): |
| 50 | ordered = [] |
| 51 | |
| 52 | def visit(name): |
| 53 | if name in ordered: |
| 54 | return |
| 55 | manifest = json.loads((PACKAGES_ROOT / name / "dbbasic-package.json").read_text()) |
| 56 | for dep in manifest.get("dependencies", []): |
| 57 | visit(dep if isinstance(dep, str) else dep["id"]) |
| 58 | ordered.append(name) |
| 59 | |
| 60 | for name in names: |
| 61 | visit(name) |
| 62 | return ordered |
| 63 | |
| 64 | |
| 65 | class FreshBox: |
| 66 | """What a new deployment is: the starter policy PUT first, packages |
| 67 | installed after (their rules are appended), enforcement on.""" |
| 68 | |
| 69 | def __init__(self, tmp_path, monkeypatch, *packages): |
| 70 | self.data = tmp_path / "data" |
| 71 | self.root = tmp_path / "objects" |
| 72 | self.root.mkdir(parents=True, exist_ok=True) |
| 73 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(self.data)) |
| 74 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(self.root)) |
| 75 | monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", ADMIN_TOKEN) |
| 76 | monkeypatch.setenv("DBBASIC_ENABLE_SITE_ROUTES", "true") |
| 77 | monkeypatch.setenv("DBBASIC_ENABLE_PERMISSION_ENFORCEMENT", "true") |
| 78 | for name in ("DBBASIC_OBJECT_TIMEOUT_SECONDS", "DBBASIC_WORKER_POOL_SIZE", |
| 79 | "DBBASIC_ROW_FILTER_INDEX", "DBBASIC_TRUSTED_IN_PROCESS_OBJECTS", |
| 80 | "DBBASIC_ALLOW_UNREADY_PERMISSION_ENFORCEMENT", |
| 81 | "DBBASIC_ENABLE_SESSION_ADMIN_GATES", "DBBASIC_PACKAGES_DIR", |
| 82 | "DBBASIC_PRIVATE_PACKAGES_DIR"): |
| 83 | monkeypatch.delenv(name, raising=False) |
| 84 | self.admin = [("authorization", f"Token {ADMIN_TOKEN}")] |
| 85 | object_permission_store.replace_policy( |
| 86 | object_permission_store.starter_policy_payload(), self.data) |
| 87 | for package in _closure(packages): |
| 88 | object_packages.install_package( |
| 89 | package, root=PACKAGES_ROOT, base_dir=self.data, object_roots=[self.root]) |
| 90 | self.user("probe-user") # enforcement needs a non-admin identity path |
| 91 | |
| 92 | def user(self, user_id, roles=()): |
| 93 | object_identity.create_user( |
| 94 | {"user_id": user_id, "roles": list(roles)}, base_dir=self.data) |
| 95 | session = object_identity.create_session({"user_id": user_id}, base_dir=self.data) |
| 96 | return [("authorization", f"Bearer {session['token']}")] |
| 97 | |
| 98 | def call(self, path, method="GET", payload=None, headers=()): |
| 99 | body = json.dumps(payload).encode("utf-8") if payload is not None else b"" |
| 100 | scope_headers = [(b"accept", b"application/json"), (b"content-type", b"application/json")] |
| 101 | scope_headers += [(k.encode("latin-1"), v.encode("latin-1")) for k, v in headers] |
| 102 | messages = [] |
| 103 | |
| 104 | async def receive(): |
| 105 | return {"type": "http.request", "body": body, "more_body": False} |
| 106 | |
| 107 | async def send(message): |
| 108 | messages.append(message) |
| 109 | |
| 110 | scope = {"type": "http", "method": method, "path": path, "query_string": b"", |
| 111 | "headers": scope_headers, "client": ("127.0.0.1", 12345)} |
| 112 | asyncio.run(object_server.app(scope, receive, send)) |
| 113 | start = next(m for m in messages if m["type"] == "http.response.start") |
| 114 | raw = b"".join(m.get("body", b"") for m in messages if m["type"] == "http.response.body") |
| 115 | try: |
| 116 | return start["status"], json.loads(raw.decode("utf-8")) |
| 117 | except ValueError: |
| 118 | return start["status"], raw.decode("utf-8", "replace") |
| 119 | |
| 120 | |
| 121 | def _enforced(box): |
| 122 | status, body = box.call("/permissions/status", headers=box.admin) |
| 123 | assert status == 200 |
| 124 | flags = body["permissions"] |
| 125 | # A broken fixture must not read as a passing refusal below. |
| 126 | assert flags["enforcement_enabled"] and not flags["enforcement_blocked"], flags |
| 127 | |
| 128 | |
| 129 | # ---- the policy itself ------------------------------------------------------ |
| 130 | |
| 131 | |
| 132 | def test_the_starter_policy_has_no_allow_rule_that_names_no_resource(): |
| 133 | """No allow rule for `registered` or `public` without a collection or an |
| 134 | object_id. Such a rule is every resource at once, and what it grants is |
| 135 | then decided by nothing but who is signed in.""" |
| 136 | payload = object_permission_store.starter_policy_payload() |
| 137 | wide = [rule for rule in payload["rules"] |
| 138 | if rule["effect"] == "allow" |
| 139 | and rule["principal"] in ("registered", "public") |
| 140 | and not rule.get("collection") and not rule.get("object_id")] |
| 141 | assert wide == [] |
| 142 | |
| 143 | |
| 144 | def test_the_starter_policy_still_serves_the_public_pages_and_the_write_probe(): |
| 145 | """What the starter policy is for is kept, each as a rule that names its |
| 146 | resource.""" |
| 147 | policy = object_permissions.policy_from_dict( |
| 148 | object_permission_store.starter_policy_payload()) |
| 149 | anonymous = object_permissions.PermissionSubject.anonymous() |
| 150 | alice = object_permissions.PermissionSubject(user_id="alice") |
| 151 | |
| 152 | for object_id in ("site_home", "system_dashboard", "system_write_probe"): |
| 153 | assert object_permissions.check_permission( |
| 154 | anonymous, "execute", policy=policy, object_id=object_id).allowed, object_id |
| 155 | assert object_permissions.check_permission( |
| 156 | anonymous, "read", policy=policy, collection="dbbasic_probe").allowed |
| 157 | for action in ("create", "update", "delete"): |
| 158 | assert object_permissions.check_permission( |
| 159 | alice, action, policy=policy, collection="dbbasic_probe").allowed, action |
| 160 | assert not object_permissions.check_permission( |
| 161 | anonymous, action, policy=policy, collection="dbbasic_probe").allowed, action |
| 162 | |
| 163 | |
| 164 | def test_the_starter_policy_alone_grants_a_signed_in_user_nothing_else(): |
| 165 | policy = object_permissions.policy_from_dict( |
| 166 | object_permission_store.starter_policy_payload()) |
| 167 | alice = object_permissions.PermissionSubject(user_id="alice") |
| 168 | assert not object_permissions.check_permission( |
| 169 | alice, "execute", policy=policy, object_id="system_billing_runner").allowed |
| 170 | assert not object_permissions.check_permission( |
| 171 | alice, "read", policy=policy, collection="email_outbox").allowed |
| 172 | |
| 173 | |
| 174 | # ---- a fresh box, over HTTP ------------------------------------------------- |
| 175 | |
| 176 | |
| 177 | # Shipped objects no package rule lets a signed-in user run. Each is an |
| 178 | # operator or reaction object (a runner, a sweeper, a generator the package |
| 179 | # gives to `role:manager`); the first four are what the problem report named. |
| 180 | OPERATOR_OBJECTS = [ |
| 181 | ("app-billing", "system_billing_runner"), |
| 182 | ("app-finance", "system_fin_recurring_runner"), |
| 183 | ("app-runner", "system_run_sweeper"), |
| 184 | ("app-invoices", "action_generate_tm_invoice"), |
| 185 | ("app-billing", "site_customer_funds"), |
| 186 | ] |
| 187 | |
| 188 | |
| 189 | @pytest.mark.parametrize("package_id,object_id", OPERATOR_OBJECTS, ids=[o for _, o in OPERATOR_OBJECTS]) |
| 190 | def test_a_signed_in_user_cannot_run_an_object_no_package_grants_them( |
| 191 | tmp_path, monkeypatch, package_id, object_id): |
| 192 | box = FreshBox(tmp_path, monkeypatch, package_id) |
| 193 | _enforced(box) |
| 194 | alice = box.user("alice") |
| 195 | |
| 196 | method = "GET" if object_id.startswith("site_") else "POST" |
| 197 | status, body = box.call(f"/objects/{object_id}", method=method, payload={}, headers=alice) |
| 198 | assert status == 403, (status, body) |
| 199 | |
| 200 | # Control: the object is there and runs for the operator, so the 403 |
| 201 | # above is a permission verdict and not a missing route. |
| 202 | status, body = box.call(f"/objects/{object_id}", method=method, payload={}, headers=box.admin) |
| 203 | assert status not in (403, 404, 405), (status, body) |
| 204 | |
| 205 | |
| 206 | # Collections the packages that own them give no signed-in user a read of. |
| 207 | UNGRANTED_COLLECTIONS = [ |
| 208 | ("app-email", "email_outbox"), |
| 209 | ("system-dashboard", "scheduler_runs"), |
| 210 | ("app-analytics", "page_views"), |
| 211 | ("app-shop", "carts"), |
| 212 | ] |
| 213 | |
| 214 | |
| 215 | @pytest.mark.parametrize("package_id,collection", UNGRANTED_COLLECTIONS, |
| 216 | ids=[c for _, c in UNGRANTED_COLLECTIONS]) |
| 217 | def test_a_signed_in_user_cannot_read_a_collection_no_package_grants_them( |
| 218 | tmp_path, monkeypatch, package_id, collection): |
| 219 | box = FreshBox(tmp_path, monkeypatch, package_id) |
| 220 | _enforced(box) |
| 221 | alice = box.user("alice") |
| 222 | status, _ = box.call(f"/collections/{collection}/records", headers=alice) |
| 223 | assert status == 403 |
| 224 | status, body = box.call(f"/collections/{collection}/records", headers=box.admin) |
| 225 | assert status == 200, (status, body) # control: the collection exists |
| 226 | |
| 227 | |
| 228 | def test_a_packages_row_filter_decides_what_a_signed_in_user_reads(tmp_path, monkeypatch): |
| 229 | """The question the broad rule raised: does an unfiltered allow beat a |
| 230 | package's `owner_id = $user_id` filter? It did. `check_permission` returns |
| 231 | the FIRST matching allow rule and never compares it with the others; the |
| 232 | starter rule matched every row of `wallets`, so the filter app-billing |
| 233 | ships was never consulted and bob read alice's balance.""" |
| 234 | box = FreshBox(tmp_path, monkeypatch, "app-billing") |
| 235 | _enforced(box) |
| 236 | alice, bob = box.user("alice"), box.user("bob") |
| 237 | object_records.create_collection_record( |
| 238 | "wallets", {"id": "w-alice", "owner_id": "alice", "currency": "USD", "kind": "balance"}, |
| 239 | base_dir=box.data, preserve_read_only=True) |
| 240 | |
| 241 | status, body = box.call("/collections/wallets/records/w-alice", headers=alice) |
| 242 | assert status == 200 and body["record"]["owner_id"] == "alice" # control: the owner sees it |
| 243 | |
| 244 | status, _ = box.call("/collections/wallets/records/w-alice", headers=bob) |
| 245 | assert status in (403, 404) |
| 246 | status, body = box.call("/collections/wallets/records", headers=bob) |
| 247 | assert status == 200 and body["records"] == [] |
| 248 | |
| 249 | subject = object_permissions.PermissionSubject(user_id="bob") |
| 250 | policy = object_permission_store.load_policy(box.data) |
| 251 | assert not object_permissions.check_permission( |
| 252 | subject, "read", policy=policy, collection="wallets", |
| 253 | record={"id": "w-alice", "owner_id": "alice"}).allowed |
| 254 | |
| 255 | |
| 256 | def test_what_the_packages_grant_still_works_on_a_fresh_box(tmp_path, monkeypatch): |
| 257 | """Removing the broad rule must not cost a user what a package gives them: |
| 258 | their own rows, the pages the packages make public or registered, and the |
| 259 | probe records the starter policy opens to signed-in users.""" |
| 260 | box = FreshBox(tmp_path, monkeypatch, "app-billing", "app-notes") |
| 261 | _enforced(box) |
| 262 | alice, bob = box.user("alice"), box.user("bob") |
| 263 | object_records.create_collection_record( |
| 264 | "wallets", {"id": "w-alice", "owner_id": "alice", "currency": "USD", "kind": "balance"}, |
| 265 | base_dir=box.data, preserve_read_only=True) |
| 266 | |
| 267 | status, body = box.call("/collections/wallets/records", headers=alice) |
| 268 | assert status == 200 and [r["id"] for r in body["records"]] == ["w-alice"] |
| 269 | status, _ = box.call("/collections/billing_plans/records", headers=bob) |
| 270 | assert status == 200 # a registered read the package ships |
| 271 | |
| 272 | status, body = box.call("/collections/notes/records", method="POST", |
| 273 | payload={"id": "n1", "title": "mine", "content": "x", "owner_id": "alice"}, headers=alice) |
| 274 | assert status in (200, 201), (status, body) |
| 275 | status, body = box.call("/collections/notes/records", headers=alice) |
| 276 | assert status == 200 and [r["id"] for r in body["records"]] == ["n1"] |
| 277 | status, body = box.call("/collections/notes/records", headers=bob) |
| 278 | assert status == 200 and body["records"] == [] |
| 279 | |
| 280 | status, _ = box.call("/objects/site_home", headers=()) |
| 281 | assert status != 403 # public home page, starter rule |
| 282 | status, body = box.call("/collections/dbbasic_probe/records", method="POST", |
| 283 | payload={"id": "p1"}, headers=alice) |
| 284 | assert status in (200, 201, 400), (status, body) # allowed through; 400 would be a schema verdict |
| 285 | assert status != 403 |