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_findings_access_control.py · 49.9 KB · 1007 lines
| 1 | """Access-control findings from the pages / hooks-actions inventory, reproduced |
| 2 | end to end. |
| 3 | |
| 4 | Each test drives the REAL ASGI app in process, with permission enforcement ON, |
| 5 | the owning package(s) really installed into tmp_path, and real sessions for |
| 6 | non-admin users (object_identity.create_user / create_session). Nothing here |
| 7 | fixes anything: every test asserts the CORRECT, secure behaviour. |
| 8 | |
| 9 | * A finding that is real is `xfail(strict=True)`: green today, and it fails |
| 10 | loudly (XPASS) the day somebody fixes it, which is the cue to delete the |
| 11 | marker. Every xfail below was seen to fail for the reason in its `reason`. |
| 12 | * A finding that is refuted is a normal passing test that pins the correct |
| 13 | behaviour. |
| 14 | |
| 15 | Why a test cannot "fail" for an unrelated reason: set-up and control checks |
| 16 | (the owner CAN see the thing, the API DOES refuse the other user, the route |
| 17 | IS enabled, enforcement IS effective) raise `SetupBroken`, which is not an |
| 18 | AssertionError. The xfails are declared `raises=AssertionError`, so a broken |
| 19 | fixture, a missing dependency or a 404 from a route that is not enabled shows |
| 20 | up as a real failure instead of being swallowed as "expected". |
| 21 | |
| 22 | Write-ups with file:line: config-inventory/pages.md, config-inventory/hooks-actions.md |
| 23 | (the inventory's own checkout path is /Users/dan/code/softwaredistros/config-inventory). |
| 24 | """ |
| 25 | |
| 26 | from __future__ import annotations |
| 27 | |
| 28 | import asyncio |
| 29 | import json |
| 30 | import re |
| 31 | import sys |
| 32 | from collections import namedtuple |
| 33 | from datetime import datetime, timezone |
| 34 | from pathlib import Path |
| 35 | |
| 36 | import pytest |
| 37 | |
| 38 | import object_identity |
| 39 | import object_packages |
| 40 | import object_permission_store |
| 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 | JSON_HEADERS = [("content-type", "application/json")] |
| 48 | |
| 49 | Response = namedtuple("Response", "status headers body") |
| 50 | |
| 51 | |
| 52 | class SetupBroken(Exception): |
| 53 | """A precondition of the scenario failed. Deliberately NOT an |
| 54 | AssertionError, so an xfail(raises=AssertionError) cannot swallow it.""" |
| 55 | |
| 56 | |
| 57 | def precondition(condition, message): |
| 58 | if not condition: |
| 59 | raise SetupBroken(message) |
| 60 | |
| 61 | |
| 62 | def finding(summary, doc): |
| 63 | return pytest.mark.xfail( |
| 64 | strict=True, raises=AssertionError, |
| 65 | reason=f"FINDING: {summary}, see config-inventory/{doc}") |
| 66 | |
| 67 | |
| 68 | def _text(response): |
| 69 | return response.body.decode("utf-8", "replace") |
| 70 | |
| 71 | |
| 72 | def _json(response): |
| 73 | return json.loads(response.body.decode("utf-8")) |
| 74 | |
| 75 | |
| 76 | def _page_text(response): |
| 77 | """HTML with the <style> blocks removed, so assertions read page content.""" |
| 78 | return re.sub(r"<style.*?</style>", "", _text(response), flags=re.S) |
| 79 | |
| 80 | |
| 81 | def _package_closure(names): |
| 82 | """Packages in dependency order (install_package does not resolve them).""" |
| 83 | ordered = [] |
| 84 | |
| 85 | def visit(name): |
| 86 | if name in ordered: |
| 87 | return |
| 88 | manifest = json.loads((PACKAGES_ROOT / name / "dbbasic-package.json").read_text()) |
| 89 | for dep in manifest.get("dependencies", []): |
| 90 | visit(dep if isinstance(dep, str) else dep["id"]) |
| 91 | ordered.append(name) |
| 92 | |
| 93 | for name in names: |
| 94 | visit(name) |
| 95 | return ordered |
| 96 | |
| 97 | |
| 98 | class Site: |
| 99 | """A permissioned install: real packages, enforcement ON, real sessions.""" |
| 100 | |
| 101 | def __init__(self, tmp_path, monkeypatch, packages, *, env=None): |
| 102 | self.data = tmp_path / "data" |
| 103 | self.root = tmp_path / "objects" |
| 104 | self.root.mkdir(parents=True, exist_ok=True) |
| 105 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(self.data)) |
| 106 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(self.root)) |
| 107 | monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", ADMIN_TOKEN) |
| 108 | monkeypatch.setenv("DBBASIC_ENABLE_SITE_ROUTES", "true") |
| 109 | monkeypatch.setenv("DBBASIC_ENABLE_PERMISSION_ENFORCEMENT", "true") |
| 110 | # In-process execution (no per-call subprocess/pool) and a full scan. |
| 111 | for name in ("DBBASIC_OBJECT_TIMEOUT_SECONDS", "DBBASIC_WORKER_POOL_SIZE", |
| 112 | "DBBASIC_ROW_FILTER_INDEX", "DBBASIC_TRUSTED_IN_PROCESS_OBJECTS", |
| 113 | "DBBASIC_ALLOW_UNREADY_PERMISSION_ENFORCEMENT", |
| 114 | "DBBASIC_ENABLE_SESSION_ADMIN_GATES"): |
| 115 | monkeypatch.delenv(name, raising=False) |
| 116 | for name, value in (env or {}).items(): |
| 117 | monkeypatch.setenv(name, value) |
| 118 | self.installed = _package_closure(packages) |
| 119 | for package in self.installed: |
| 120 | object_packages.install_package( |
| 121 | package, root=PACKAGES_ROOT, base_dir=self.data, object_roots=[self.root]) |
| 122 | self.admin = [("authorization", f"Token {ADMIN_TOKEN}")] |
| 123 | |
| 124 | def require_enforcement(self): |
| 125 | status = self.call("/permissions/status", headers=self.admin) |
| 126 | precondition(status.status == 200, f"/permissions/status: {status.status}") |
| 127 | flags = _json(status)["permissions"] |
| 128 | precondition(flags["enforcement_enabled"] and not flags["enforcement_blocked"], |
| 129 | f"permission enforcement is not effective: {flags}") |
| 130 | |
| 131 | def user(self, user_id, roles=()): |
| 132 | """A registered user with a real session; returns its headers.""" |
| 133 | object_identity.create_user( |
| 134 | {"user_id": user_id, "roles": list(roles)}, base_dir=self.data) |
| 135 | session = object_identity.create_session({"user_id": user_id}, base_dir=self.data) |
| 136 | return [("authorization", f"Bearer {session['token']}")] |
| 137 | |
| 138 | def create(self, collection, record): |
| 139 | """A trusted write (what an action or the daemon does), read-only |
| 140 | fields allowed so ids, tokens and stamps can be set.""" |
| 141 | return object_records.create_collection_record( |
| 142 | collection, record, base_dir=self.data, preserve_read_only=True) |
| 143 | |
| 144 | def rows(self, collection): |
| 145 | return object_records.read_collection_records(collection, base_dir=self.data) |
| 146 | |
| 147 | def row(self, collection, record_id): |
| 148 | return object_records.get_collection_record( |
| 149 | collection, record_id, base_dir=self.data) |
| 150 | |
| 151 | def call(self, path, method="GET", payload=None, headers=(), html=False, query=""): |
| 152 | body = b"" |
| 153 | scope_headers = [(b"accept", (b"text/html" if html else b"application/json"))] |
| 154 | for name, value in headers: |
| 155 | scope_headers.append((name.encode("latin-1"), value.encode("latin-1"))) |
| 156 | if payload is not None: |
| 157 | body = json.dumps(payload).encode("utf-8") |
| 158 | scope_headers.append((b"content-type", b"application/json")) |
| 159 | return asyncio.run(self._asgi(path, method, body, scope_headers, query)) |
| 160 | |
| 161 | async def _asgi(self, path, method, body, scope_headers, query): |
| 162 | messages = [] |
| 163 | |
| 164 | async def receive(): |
| 165 | return {"type": "http.request", "body": body, "more_body": False} |
| 166 | |
| 167 | async def send(message): |
| 168 | messages.append(message) |
| 169 | |
| 170 | scope = {"type": "http", "method": method, "path": path, |
| 171 | "query_string": query.encode("utf-8"), "headers": scope_headers, |
| 172 | "client": ("127.0.0.1", 12345)} |
| 173 | await object_server.app(scope, receive, send) |
| 174 | start = next(m for m in messages if m["type"] == "http.response.start") |
| 175 | payload = b"".join(m.get("body", b"") for m in messages |
| 176 | if m["type"] == "http.response.body") |
| 177 | headers = {k.decode().lower(): v.decode() for k, v in start["headers"]} |
| 178 | return Response(start["status"], headers, payload) |
| 179 | |
| 180 | def execute(self, object_id, payload, headers): |
| 181 | return self.call(f"/objects/{object_id}", method="POST", payload=payload, |
| 182 | headers=headers) |
| 183 | |
| 184 | |
| 185 | @pytest.fixture |
| 186 | def make_site(tmp_path, monkeypatch): |
| 187 | def build(*packages, env=None): |
| 188 | site = Site(tmp_path, monkeypatch, packages, env=env) |
| 189 | # Enforcement only becomes effective once a non-admin identity path |
| 190 | # exists (docs/permissions-model.md), i.e. once a session does. |
| 191 | site.user("probe-user") |
| 192 | site.require_enforcement() |
| 193 | return site |
| 194 | return build |
| 195 | |
| 196 | |
| 197 | def _now(): |
| 198 | return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") |
| 199 | |
| 200 | |
| 201 | # ============================================================================= |
| 202 | # 1. Stale grants: execute rules for objects no manifest ships |
| 203 | # ============================================================================= |
| 204 | |
| 205 | def stale_execute_grants(): |
| 206 | """(package, object_id, principal) for every execute rule whose object_id is |
| 207 | not in the SAME package's manifest. Computed from the shipped files, so the |
| 208 | list is exact rather than remembered.""" |
| 209 | shipped_anywhere = set() |
| 210 | manifests = {} |
| 211 | for manifest_path in sorted(PACKAGES_ROOT.glob("*/dbbasic-package.json")): |
| 212 | manifest = json.loads(manifest_path.read_text()) |
| 213 | manifests[manifest["id"]] = manifest |
| 214 | shipped_anywhere.update(o["id"] for o in manifest.get("objects", [])) |
| 215 | stale = [] |
| 216 | for package_id, manifest in sorted(manifests.items()): |
| 217 | rules_path = PACKAGES_ROOT / package_id / "permissions" / "rules.json" |
| 218 | if not rules_path.exists(): |
| 219 | continue |
| 220 | mine = {o["id"] for o in manifest.get("objects", [])} |
| 221 | for rule in json.loads(rules_path.read_text())["rules"]: |
| 222 | object_id = rule.get("object_id") |
| 223 | if (rule.get("effect") == "allow" and object_id |
| 224 | and "execute" in rule.get("actions", []) and object_id not in mine): |
| 225 | precondition(object_id not in shipped_anywhere, |
| 226 | f"{object_id} is shipped by another package, not stale") |
| 227 | stale.append((package_id, object_id, rule["principal"])) |
| 228 | return stale |
| 229 | |
| 230 | |
| 231 | # The 14 grants that WERE stale (thirteen `public` page grants plus |
| 232 | # app-kitchen's), deleted from the packages' rules.json. Kept, hard-coded, so |
| 233 | # the end-to-end cases below go on proving that an object created later under |
| 234 | # one of these ids is refused; the static test asserts the live list is empty. |
| 235 | KNOWN_STALE = [ |
| 236 | ("app-articles", "site_articles", "public"), |
| 237 | ("app-catalog", "site_products", "public"), |
| 238 | ("app-catalog", "site_locations", "public"), |
| 239 | ("app-contacts", "site_contacts", "public"), |
| 240 | ("app-finance", "site_accounts", "public"), |
| 241 | ("app-finance", "site_journals", "public"), |
| 242 | ("app-invoices", "site_invoices", "public"), |
| 243 | ("app-kitchen", "system_kitchen_attention", "registered"), |
| 244 | ("app-links", "site_links", "public"), |
| 245 | ("app-notes", "site_notes", "public"), |
| 246 | ("app-orders", "site_orders", "public"), |
| 247 | ("app-projects", "site_projects", "public"), |
| 248 | ("app-tasks", "site_tasks", "public"), |
| 249 | ("app-templates", "site_templates", "public"), |
| 250 | ] |
| 251 | |
| 252 | |
| 253 | def test_no_package_grants_execute_on_an_object_it_does_not_ship(): |
| 254 | """A grant for an id nothing ships is a rule written for an object that |
| 255 | does not exist yet: whatever is later created under that id is public |
| 256 | (or registered) without anybody having decided so.""" |
| 257 | stale = stale_execute_grants() |
| 258 | assert stale == [], ( |
| 259 | f"{len(stale)} stale execute grants: " + ", ".join( |
| 260 | f"{pkg}:{oid}({who})" for pkg, oid, who in stale)) |
| 261 | |
| 262 | |
| 263 | def test_the_formerly_stale_ids_are_still_shipped_by_nobody(): |
| 264 | """Control for the e2e cases: they create an object under each id by |
| 265 | hand, which only proves anything while no package ships one. A package |
| 266 | that starts shipping one of these ids must write its own grant, and this |
| 267 | list loses that row.""" |
| 268 | shipped = set() |
| 269 | for manifest_path in PACKAGES_ROOT.glob("*/dbbasic-package.json"): |
| 270 | manifest = json.loads(manifest_path.read_text()) |
| 271 | shipped.update(o["id"] for o in manifest.get("objects", [])) |
| 272 | assert not shipped & {object_id for _, object_id, _ in KNOWN_STALE} |
| 273 | |
| 274 | |
| 275 | def _object_path(root, object_id): |
| 276 | kind, _, name = object_id.partition("_") |
| 277 | return root / kind / f"{name}.py" |
| 278 | |
| 279 | |
| 280 | SECRET_OBJECT = ('def GET(request):\n' |
| 281 | ' return {"secret": "created-later-by-an-operator"}\n') |
| 282 | |
| 283 | |
| 284 | @pytest.mark.parametrize("package_id,object_id,principal", [ |
| 285 | pytest.param(*row, id=row[1]) for row in KNOWN_STALE]) |
| 286 | def test_an_object_created_later_with_a_stale_id_is_not_executable_without_a_grant( |
| 287 | make_site, package_id, object_id, principal): |
| 288 | site = make_site(package_id) |
| 289 | alice = site.user("alice") |
| 290 | _object_path(site.root, object_id).parent.mkdir(parents=True, exist_ok=True) |
| 291 | _object_path(site.root, object_id).write_text(SECRET_OBJECT) |
| 292 | |
| 293 | # Control: the default-deny works for a brand-new id (so a 200 below is |
| 294 | # the stale grant and nothing else). |
| 295 | control_id = "site_brand_new_page" |
| 296 | _object_path(site.root, control_id).write_text(SECRET_OBJECT) |
| 297 | for who in ([], alice): |
| 298 | denied = site.call(f"/objects/{control_id}", headers=who) |
| 299 | precondition(denied.status == 403, f"default-deny control: {denied.status}") |
| 300 | # Control: the admin can run the object, so a 403 is a permission verdict. |
| 301 | precondition(site.call(f"/objects/{object_id}", headers=site.admin).status == 200, |
| 302 | "the object itself does not run") |
| 303 | |
| 304 | caller = [] if principal == "public" else alice |
| 305 | response = site.call(f"/objects/{object_id}", headers=caller) |
| 306 | assert response.status == 403 and "created-later" not in _text(response), ( |
| 307 | f"{principal} caller got {response.status}: {_text(response)[:120]}") |
| 308 | |
| 309 | |
| 310 | # ============================================================================= |
| 311 | # 2. Pages that read storage directly and are the only access gate |
| 312 | # ============================================================================= |
| 313 | |
| 314 | def _seed_orders(site): |
| 315 | """alice owns a sale order (with a vendor-side purchase order linked as a |
| 316 | drop-ship pair) and a standalone purchase order. bob owns nothing.""" |
| 317 | site.create("orders", { |
| 318 | "id": "so-1", "doc_type": "sale", "number": "SO-ALICE-1", |
| 319 | "customer_name": "Carol Customer", "status": "confirmed", |
| 320 | "customer_note": "ALICE-PRIVATE-NOTE", "linked_order_id": "po-1", |
| 321 | "owner_id": "alice"}) |
| 322 | site.create("orders", { |
| 323 | "id": "po-1", "doc_type": "purchase", "number": "PO-ALICE-1", |
| 324 | "customer_name": "Alice Secret Supplier", "status": "confirmed", |
| 325 | "linked_order_id": "so-1", "owner_id": "alice"}) |
| 326 | site.create("order_lines", { |
| 327 | "id": "ol-1", "order_id": "so-1", "description": "Alice widget", |
| 328 | "quantity": "2", "unit_price_cents": "1000", "line_total_cents": "2000", |
| 329 | "owner_id": "alice"}) |
| 330 | site.create("order_lines", { |
| 331 | "id": "ol-2", "order_id": "po-1", "description": "Alice vendor pallet", |
| 332 | "quantity": "2", "unit_price_cents": "400", "line_total_cents": "800", |
| 333 | "owner_id": "alice"}) |
| 334 | |
| 335 | |
| 336 | def _api_refuses_other_users_order(site, bob, order_id): |
| 337 | """Control: the collection's own rules refuse bob what the page shows him.""" |
| 338 | direct = site.call(f"/collections/orders/records/{order_id}", headers=bob) |
| 339 | precondition(direct.status == 404, f"API order read by bob: {direct.status}") |
| 340 | listing = site.call("/collections/orders/records", headers=bob) |
| 341 | precondition(listing.status == 200 and _json(listing)["records"] == [], |
| 342 | f"bob's order list is not empty: {_text(listing)[:200]}") |
| 343 | |
| 344 | |
| 345 | def test_kitchen_ticket_refuses_another_users_order(make_site): |
| 346 | site = make_site("app-kitchen") |
| 347 | alice, bob = site.user("alice"), site.user("bob") |
| 348 | _seed_orders(site) |
| 349 | _api_refuses_other_users_order(site, bob, "so-1") |
| 350 | own = site.call("/kitchen/so-1/ticket", headers=alice, html=True) |
| 351 | precondition(own.status == 200 and "ALICE-PRIVATE-NOTE" in _text(own), |
| 352 | f"owner cannot open her own ticket: {own.status}") |
| 353 | precondition(site.call("/kitchen/so-1/ticket", html=True).status == 403, |
| 354 | "anonymous visitors should already be refused by the execute rule") |
| 355 | |
| 356 | theirs = site.call("/kitchen/so-1/ticket", headers=bob, html=True) |
| 357 | text = _page_text(theirs) |
| 358 | assert not any(secret in text for secret in |
| 359 | ("ALICE-PRIVATE-NOTE", "Carol Customer", "Alice widget")), ( |
| 360 | f"bob got HTTP {theirs.status} with alice's customer, note and lines") |
| 361 | |
| 362 | |
| 363 | def test_dropship_margin_refuses_another_users_order(make_site): |
| 364 | site = make_site("app-orders") |
| 365 | alice, bob = site.user("alice"), site.user("bob") |
| 366 | _seed_orders(site) |
| 367 | _api_refuses_other_users_order(site, bob, "so-1") |
| 368 | own = site.call("/orders/so-1/margin", headers=alice, html=True) |
| 369 | precondition(own.status == 200 and "20.00 USD" in _text(own) and "8.00 USD" in _text(own), |
| 370 | f"owner cannot read her own margin page: {own.status} {_page_text(own)[-300:]}") |
| 371 | precondition(site.call("/orders/so-1/margin", html=True).status == 403, |
| 372 | "anonymous visitors should already be refused by the execute rule") |
| 373 | |
| 374 | theirs = site.call("/orders/so-1/margin", headers=bob, html=True) |
| 375 | text = _page_text(theirs) |
| 376 | assert not any(secret in text for secret in |
| 377 | ("20.00 USD", "8.00 USD", "12.00 USD", "Alice Secret Supplier")), ( |
| 378 | f"bob got HTTP {theirs.status}: revenue 20.00, cost 8.00, margin 12.00 (60%) of alice's order") |
| 379 | |
| 380 | |
| 381 | def test_receiving_sheet_refuses_another_users_purchase_order(make_site): |
| 382 | site = make_site("app-receiving") |
| 383 | alice, bob = site.user("alice"), site.user("bob") |
| 384 | _seed_orders(site) |
| 385 | _api_refuses_other_users_order(site, bob, "po-1") |
| 386 | own = site.call("/purchase-orders/po-1/receive", headers=alice, html=True) |
| 387 | precondition(own.status == 200 and "Alice Secret Supplier" in _text(own), |
| 388 | f"owner cannot open her own receiving sheet: {own.status}") |
| 389 | precondition(site.call("/purchase-orders/po-1/receive", html=True).status == 403, |
| 390 | "anonymous visitors should already be refused by the execute rule") |
| 391 | |
| 392 | theirs = site.call("/purchase-orders/po-1/receive", headers=bob, html=True) |
| 393 | text = _page_text(theirs) |
| 394 | assert not any(secret in text for secret in |
| 395 | ("Alice Secret Supplier", "Alice vendor pallet", "PO-ALICE-1")), ( |
| 396 | f"bob got HTTP {theirs.status} with alice's supplier, PO number and lines") |
| 397 | |
| 398 | |
| 399 | def _seed_shipped_order(site): |
| 400 | site.create("orders", { |
| 401 | "id": "so-5", "doc_type": "sale", "number": "SO-ALICE-5", |
| 402 | "customer_name": "Carol Customer", "customer_email": "carol@example.test", |
| 403 | "status": "shipped", "portal_token": "tok-alice-5", "owner_id": "alice"}) |
| 404 | site.create("order_lines", { |
| 405 | "id": "sl-1", "order_id": "so-5", "description": "Alice widget", |
| 406 | "quantity": "2", "unit_price_cents": "1000", "line_total_cents": "2000", |
| 407 | "owner_id": "alice"}) |
| 408 | site.create("shipments", { |
| 409 | "id": "sh-1", "order_id": "so-5", "direction": "outbound", "status": "delivered", |
| 410 | "owner_id": "alice"}) |
| 411 | site.create("shipment_lines", { |
| 412 | "id": "shl-1", "shipment_id": "sh-1", "order_line_id": "sl-1", "quantity": "2", |
| 413 | "owner_id": "alice"}) |
| 414 | |
| 415 | |
| 416 | def test_return_form_refuses_another_users_order(make_site): |
| 417 | site = make_site("app-returns") |
| 418 | alice, bob = site.user("alice"), site.user("bob") |
| 419 | _seed_shipped_order(site) |
| 420 | _api_refuses_other_users_order(site, bob, "so-5") |
| 421 | own = site.call("/returns/so-5", headers=alice, html=True) |
| 422 | precondition(own.status == 200 and "Carol Customer" in _text(own), |
| 423 | f"owner cannot open her own return form: {own.status}") |
| 424 | # Control: the anonymous door is closed without the token (page says so, 200). |
| 425 | anonymous = site.call("/returns/so-5", html=True) |
| 426 | precondition("Carol Customer" not in _text(anonymous), "anonymous sees the order") |
| 427 | |
| 428 | theirs = site.call("/returns/so-5", headers=bob, html=True) |
| 429 | text = _page_text(theirs) |
| 430 | assert not any(secret in text for secret in |
| 431 | ("Carol Customer", "SO-ALICE-5", "Alice widget")), ( |
| 432 | f"bob got HTTP {theirs.status} with alice's customer name, order number and lines") |
| 433 | |
| 434 | |
| 435 | def test_a_signed_in_stranger_cannot_authorize_a_return_on_someone_elses_order(make_site): |
| 436 | site = make_site("app-returns") |
| 437 | alice, bob = site.user("alice"), site.user("bob") |
| 438 | _seed_shipped_order(site) |
| 439 | before = len(site.rows("shipments")) |
| 440 | response = site.call("/returns/so-5", method="POST", headers=bob, html=True, |
| 441 | payload={"reason": "other", "qty_sl-1": "1"}) |
| 442 | precondition(response.status in (200, 403, 404, 409), f"unexpected {response.status}") |
| 443 | inbound = [s for s in site.rows("shipments") |
| 444 | if s["order_id"] == "so-5" and s["direction"] == "inbound"] |
| 445 | assert response.status in (403, 404) and not inbound and len(site.rows("shipments")) == before, ( |
| 446 | f"bob's POST got {response.status} and created {len(inbound)} inbound return shipment(s) on alice's order") |
| 447 | |
| 448 | |
| 449 | def _seed_page_views(site): |
| 450 | stamp = _now() |
| 451 | for i in range(3): |
| 452 | site.create("page_views", { |
| 453 | "host": "shop.example", "path": "/landing-secret-campaign", "method": "GET", |
| 454 | "status": "200", "ip": f"203.0.113.{i}", "user_agent": "Mozilla/5.0", |
| 455 | "session_id": f"sess-{i}", "created_at": stamp}) |
| 456 | |
| 457 | |
| 458 | def test_visitors_page_does_not_show_admin_only_analytics_to_a_registered_user(make_site): |
| 459 | site = make_site("app-analytics", env={"DBBASIC_ANALYTICS": "on"}) |
| 460 | bob = site.user("bob") |
| 461 | _seed_page_views(site) |
| 462 | # Controls: the collection itself is admin-only; the admin sees the data on the page. |
| 463 | precondition(site.call("/collections/page_views/records", headers=bob).status == 403, |
| 464 | "page_views should be admin-read-only through the API") |
| 465 | precondition(site.call("/collections/page_views/records").status == 403, "anonymous page_views") |
| 466 | admin_page = site.call("/visitors", headers=site.admin, html=True) |
| 467 | precondition(admin_page.status == 200 and "/landing-secret-campaign" in _text(admin_page), |
| 468 | f"admin cannot see the analytics page: {admin_page.status}") |
| 469 | precondition(site.call("/visitors", html=True).status == 403, "anonymous /visitors") |
| 470 | |
| 471 | theirs = site.call("/visitors", headers=bob, html=True) |
| 472 | text = _page_text(theirs) |
| 473 | # The regex lives outside the f-string: a backslash inside an f-string |
| 474 | # expression is a SyntaxError before Python 3.12, and this suite supports |
| 475 | # 3.10 (it broke collection of every module importing this one). |
| 476 | tiles = re.findall(r"<div class=.n.>(\d+)</div><div class=.k.>([^<]*)", text) |
| 477 | assert "/landing-secret-campaign" not in text and "unique visitors" not in text, ( |
| 478 | f"bob got HTTP {theirs.status}: {tiles}") |
| 479 | |
| 480 | |
| 481 | def _seed_agent(site): |
| 482 | site.create("agent_registry", { |
| 483 | "agent_id": "agent-x", "label": "Agent X", "status": "active", |
| 484 | "heartbeat_at": _now(), "spend_cap_minor": "1000", "capabilities": "compute", |
| 485 | "owner_id": "alice"}) |
| 486 | site.create("wallets", {"id": "w-agent", "owner_id": "agent-x", "kind": "balance"}) |
| 487 | site.create("wallet_entries", { |
| 488 | "wallet_id": "w-agent", "amount_minor": "-1500", "kind": "debit", |
| 489 | "owner_id": "agent-x"}) |
| 490 | |
| 491 | |
| 492 | def test_agent_registry_rows_are_readable_by_registered_users_through_the_api(make_site): |
| 493 | """Pins the part of the `agents` finding that is BY DESIGN: the registry |
| 494 | itself is registered-readable, so who the agents are is not a leak.""" |
| 495 | site = make_site("app-agents") |
| 496 | bob = site.user("bob") |
| 497 | site.create("agent_registry", { |
| 498 | "agent_id": "agent-x", "label": "Agent X", "status": "active", |
| 499 | "heartbeat_at": _now(), "owner_id": "alice"}) |
| 500 | listing = site.call("/collections/agent_registry/records", headers=bob) |
| 501 | assert listing.status == 200 |
| 502 | assert [r["agent_id"] for r in _json(listing)["records"]] == ["agent-x"] |
| 503 | |
| 504 | |
| 505 | def test_agents_board_does_not_expose_ledger_spend_the_api_hides(make_site): |
| 506 | site = make_site("app-agents", "app-billing") |
| 507 | bob = site.user("bob") |
| 508 | _seed_agent(site) |
| 509 | # Controls: bob cannot read that ledger row through the API (list is row |
| 510 | # filtered to nothing, direct read refused); anonymous is refused the page. |
| 511 | ledger = site.call("/collections/wallet_entries/records", headers=bob) |
| 512 | precondition(ledger.status == 200 and _json(ledger)["records"] == [], |
| 513 | f"bob can read wallet_entries: {_text(ledger)[:200]}") |
| 514 | precondition(site.call("/agents.json").status == 403, "anonymous /agents.json") |
| 515 | admin = _json(site.call("/agents.json", headers=site.admin)) |
| 516 | precondition(admin["agents"][0]["spend"]["committed_minor"] == 1500, |
| 517 | f"the fold does not see the ledger: {admin['agents']}") |
| 518 | |
| 519 | theirs = site.call("/agents.json", headers=bob) |
| 520 | precondition(theirs.status == 200 and _json(theirs)["agents"], |
| 521 | f"bob cannot reach the board at all: {theirs.status}") |
| 522 | agent = _json(theirs)["agents"][0] |
| 523 | assert agent["spend"] is None and agent["agent_id"] == "agent-x" and \ |
| 524 | "agent-x" not in _json(theirs)["over_cap"], ( |
| 525 | f"bob sees agent-x spend {agent['spend']} (cap 1000, committed 1500, over) " |
| 526 | f"derived from wallet_entries he cannot read") |
| 527 | |
| 528 | |
| 529 | # ============================================================================= |
| 530 | # 3. Thread moderation is client-side only |
| 531 | # ============================================================================= |
| 532 | |
| 533 | def _seed_thread(site): |
| 534 | for comment_id, body, status in ( |
| 535 | ("c-ok", "a fine comment", "published"), |
| 536 | ("c-removed", "REMOVED-BY-MODERATOR-BODY", "removed"), |
| 537 | ("c-flagged", "FLAGGED-SPAM-BODY", "flagged"), |
| 538 | ("c-pending", "PENDING-BODY", "pending")): |
| 539 | site.create("thread_comments", { |
| 540 | "id": comment_id, "parent_collection": "notes", "parent_id": "n1", |
| 541 | "body": body, "owner_id": "alice", "status": status}) |
| 542 | |
| 543 | |
| 544 | def test_thread_comments_api_does_not_return_moderated_comments_to_other_users(make_site): |
| 545 | site = make_site("app-thread") |
| 546 | alice, bob = site.user("alice"), site.user("bob") |
| 547 | _seed_thread(site) |
| 548 | precondition(site.call("/collections/thread_comments/records").status == 403, |
| 549 | "anonymous thread read should be refused") |
| 550 | listing = site.call("/collections/thread_comments/records", headers=bob, |
| 551 | query="parent_collection=notes&parent_id=n1") |
| 552 | precondition(listing.status == 200, f"bob cannot list comments: {listing.status}") |
| 553 | bodies = {r["body"] for r in _json(listing)["records"]} |
| 554 | precondition("a fine comment" in bodies, "the published comment is missing") |
| 555 | |
| 556 | direct = site.call("/collections/thread_comments/records/c-removed", headers=bob) |
| 557 | leaked = bodies & {"REMOVED-BY-MODERATOR-BODY", "FLAGGED-SPAM-BODY", "PENDING-BODY"} |
| 558 | if direct.status == 200: |
| 559 | leaked.add(_json(direct)["record"]["body"]) |
| 560 | assert not leaked, f"bob (not the author, not a moderator) read: {sorted(leaked)}" |
| 561 | |
| 562 | |
| 563 | def test_the_widgets_client_side_moderation_filter_has_the_fields_it_filters_on(make_site): |
| 564 | site = make_site("app-thread") |
| 565 | alice = site.user("alice") |
| 566 | _seed_thread(site) |
| 567 | listing = site.call("/collections/thread_comments/records", headers=alice, |
| 568 | query="parent_collection=notes&parent_id=n1") |
| 569 | precondition(listing.status == 200 and len(_json(listing)["records"]) >= 1, |
| 570 | f"alice (the author) cannot list: {listing.status}") |
| 571 | records = _json(listing)["records"] |
| 572 | # thread.py:92-95 hides rows where `(c.status || "published") !== "published"` |
| 573 | # unless `c.owner_id === viewer`. Both must be present for that to mean anything. |
| 574 | assert all("status" in r and "owner_id" in r for r in records), ( |
| 575 | f"keys the widget actually receives: {sorted(set().union(*[r.keys() for r in records]))}") |
| 576 | |
| 577 | |
| 578 | def test_profile_comments_enforce_moderation_with_a_row_filter(make_site): |
| 579 | """REFUTES the 'worker does it wrong' half and is the correct model for |
| 580 | thread: only approved rows are visible to anyone but their author.""" |
| 581 | site = make_site("app-worker") |
| 582 | alice, bob = site.user("alice"), site.user("bob") |
| 583 | site.create("profiles", {"id": "p1", "display_name": "Alice", "owner_id": "alice"}) |
| 584 | for comment_id, content, status in ( |
| 585 | ("pc-ok", "approved", "approved"), ("pc-pending", "PENDING-SECRET", "pending"), |
| 586 | ("pc-rejected", "REJECTED-SECRET", "rejected")): |
| 587 | site.create("profile_comments", { |
| 588 | "id": comment_id, "profile_id": "p1", "content": content, |
| 589 | "status": status, "owner_id": "alice"}) |
| 590 | for who in ([], bob): |
| 591 | listing = site.call("/collections/profile_comments/records", headers=who, |
| 592 | query="profile_id=p1") |
| 593 | assert listing.status == 200 |
| 594 | assert [r["id"] for r in _json(listing)["records"]] == ["pc-ok"] |
| 595 | assert site.call("/collections/profile_comments/records/pc-pending", headers=bob).status == 404 |
| 596 | own = site.call("/collections/profile_comments/records", headers=alice, query="profile_id=p1") |
| 597 | assert sorted(r["id"] for r in _json(own)["records"]) == ["pc-ok", "pc-pending", "pc-rejected"] |
| 598 | |
| 599 | |
| 600 | # ============================================================================= |
| 601 | # 4. run_template: private templates, every run readable, existence oracle |
| 602 | # ============================================================================= |
| 603 | |
| 604 | def _template(site, template_id, owner, *, public="false"): |
| 605 | site.create("templates", { |
| 606 | "id": template_id, "name": f"{owner} template", "handler": "echo", |
| 607 | "body": f"BODY-OF-{template_id} {{topic}}", |
| 608 | "instructions": f"INSTRUCTIONS-OF-{template_id}", "run_cost_cents": "0", |
| 609 | "is_public": public, "owner_id": owner}) |
| 610 | |
| 611 | |
| 612 | def test_a_user_cannot_run_another_users_private_template(make_site): |
| 613 | site = make_site("app-runner") |
| 614 | bob = site.user("bob") |
| 615 | site.user("alice") |
| 616 | _template(site, "tpl-private", "alice") |
| 617 | precondition(site.call("/collections/templates/records/tpl-private", headers=bob).status == 404, |
| 618 | "templates collection should refuse bob the private template") |
| 619 | precondition(site.execute("action_run_template", {"template_id": "tpl-private"}, []).status == 403, |
| 620 | "anonymous run") |
| 621 | own_template = "tpl-bobs" |
| 622 | _template(site, own_template, "bob") |
| 623 | ok = site.execute("action_run_template", {"template_id": own_template}, bob) |
| 624 | precondition(ok.status == 200 and _json(ok)["status"] == "queued", |
| 625 | f"bob cannot run his own template: {ok.status} {_text(ok)[:200]}") |
| 626 | |
| 627 | response = site.execute("action_run_template", {"template_id": "tpl-private", |
| 628 | "form_data": {"topic": "x"}}, bob) |
| 629 | stamped = [r for r in site.rows("template_runs") if r["template_id"] == "tpl-private"] |
| 630 | assert response.status in (403, 404) and not stamped, ( |
| 631 | f"bob's run of alice's PRIVATE template: HTTP {response.status}; stamped body " |
| 632 | f"{[r['rendered_body'] for r in stamped]} and instructions {[r['instructions'] for r in stamped]}") |
| 633 | |
| 634 | |
| 635 | def test_template_runs_are_only_readable_by_their_owner(make_site): |
| 636 | site = make_site("app-runner") |
| 637 | alice, bob = site.user("alice"), site.user("bob") |
| 638 | _template(site, "tpl-alice", "alice") |
| 639 | run = site.execute("action_run_template", |
| 640 | {"template_id": "tpl-alice", "form_data": {"topic": "ALICE-FORM-VALUE"}}, alice) |
| 641 | precondition(run.status == 200, f"alice cannot run her own template: {run.status}") |
| 642 | run_id = _json(run)["run_id"] |
| 643 | mine = site.call("/collections/template_runs/records", headers=alice) |
| 644 | precondition([r["id"] for r in _json(mine)["records"]] == [run_id], "owner cannot list her run") |
| 645 | precondition(site.call("/collections/template_runs/records").status == 403, "anonymous runs") |
| 646 | |
| 647 | theirs = site.call("/collections/template_runs/records", headers=bob) |
| 648 | direct = site.call(f"/collections/template_runs/records/{run_id}", headers=bob) |
| 649 | precondition(theirs.status in (200, 403), f"unexpected {theirs.status}") |
| 650 | visible = [r["id"] for r in (_json(theirs)["records"] if theirs.status == 200 else [])] |
| 651 | assert run_id not in visible and direct.status in (403, 404), ( |
| 652 | f"bob listed {len(visible)} run(s) of other users; direct GET -> {direct.status} " |
| 653 | f"{_text(direct)[:160] if direct.status == 200 else ''}") |
| 654 | |
| 655 | |
| 656 | def test_run_template_does_not_distinguish_a_private_template_from_a_missing_one(make_site): |
| 657 | site = make_site("app-runner") |
| 658 | carol = site.user("carol") |
| 659 | site.user("alice") |
| 660 | _template(site, "tpl-private", "alice") |
| 661 | missing = site.execute("action_run_template", {"template_id": "tpl-does-not-exist"}, carol) |
| 662 | precondition(missing.status == 404, f"missing template: {missing.status}") |
| 663 | private = site.execute("action_run_template", {"template_id": "tpl-private"}, carol) |
| 664 | assert private.status == missing.status, ( |
| 665 | f"carol: missing template -> {missing.status}, alice's private template -> {private.status}") |
| 666 | |
| 667 | |
| 668 | def test_run_template_does_not_distinguish_a_foreign_task_from_a_missing_one(make_site): |
| 669 | site = make_site("app-runner", "app-tasks") |
| 670 | carol = site.user("carol") |
| 671 | site.user("alice") |
| 672 | _template(site, "tpl-carol", "carol") |
| 673 | site.create("tasks", {"id": "task-alice", "title": "alice task", "owner_id": "alice"}) |
| 674 | missing = site.execute("action_run_template", |
| 675 | {"template_id": "tpl-carol", "task_id": "task-nope"}, carol) |
| 676 | precondition(missing.status == 404, f"missing task: {missing.status} {_text(missing)[:200]}") |
| 677 | foreign = site.execute("action_run_template", |
| 678 | {"template_id": "tpl-carol", "task_id": "task-alice"}, carol) |
| 679 | assert foreign.status == missing.status, ( |
| 680 | f"carol: missing task -> {missing.status}, alice's task -> {foreign.status}") |
| 681 | |
| 682 | |
| 683 | # ============================================================================= |
| 684 | # 5. resolve_run: no execute rule (owner branch dead) and fail-open ledger read |
| 685 | # ============================================================================= |
| 686 | |
| 687 | def _needs_review_run(site, run_id, owner="alice", price="500"): |
| 688 | site.create("templates", {"id": f"t-{run_id}", "name": "T", "body": "b", |
| 689 | "handler": "echo", "owner_id": owner}) \ |
| 690 | if not _has(site, "templates", f"t-{run_id}") else None |
| 691 | if not _has(site, "wallets", "w-alice"): |
| 692 | site.create("wallets", {"id": "w-alice", "owner_id": owner, "kind": "balance"}) |
| 693 | site.create("template_runs", { |
| 694 | "id": run_id, "template_id": f"t-{run_id}", "template_name": "T", "handler": "echo", |
| 695 | "status": "needs_review", "price_cents": price, "wallet_id": "w-alice", "owner_id": owner}) |
| 696 | |
| 697 | |
| 698 | def _has(site, collection, record_id): |
| 699 | try: |
| 700 | return site.row(collection, record_id) is not None |
| 701 | except Exception: |
| 702 | return False |
| 703 | |
| 704 | |
| 705 | def _resolve(site, run_id, headers, decision="charge"): |
| 706 | return site.execute("action_resolve_run", {"run_id": run_id, "decision": decision}, headers) |
| 707 | |
| 708 | |
| 709 | def test_the_owner_of_a_needs_review_run_can_resolve_it(make_site): |
| 710 | site = make_site("app-runner") |
| 711 | alice = site.user("alice") |
| 712 | _needs_review_run(site, "run-owner") |
| 713 | _needs_review_run(site, "run-admin") |
| 714 | # Control: the action works at all (admin), so a 403 below is a rule verdict. |
| 715 | done = _resolve(site, "run-admin", site.admin) |
| 716 | precondition(done.status == 200 and _json(done)["settlement"] == "settled", |
| 717 | f"admin resolve failed: {done.status} {_text(done)[:200]}") |
| 718 | response = _resolve(site, "run-owner", alice) |
| 719 | assert response.status == 200, ( |
| 720 | f"owner got HTTP {response.status} {_text(response)[:140]} " |
| 721 | f"(run still {site.row('template_runs', 'run-owner')['status']})") |
| 722 | |
| 723 | |
| 724 | def test_a_stranger_cannot_resolve_someone_elses_run(make_site): |
| 725 | """Must stay true after any fix to the previous test.""" |
| 726 | site = make_site("app-runner") |
| 727 | site.user("alice") |
| 728 | bob = site.user("bob") |
| 729 | _needs_review_run(site, "run-1") |
| 730 | response = _resolve(site, "run-1", bob) |
| 731 | assert response.status == 403 |
| 732 | assert site.row("template_runs", "run-1")["status"] == "needs_review" |
| 733 | assert [r for r in site.rows("wallet_entries")] == [] |
| 734 | |
| 735 | |
| 736 | def test_resolve_run_refuses_to_settle_when_it_cannot_read_the_ledger(make_site, monkeypatch): |
| 737 | site = make_site("app-runner") |
| 738 | _needs_review_run(site, "run-settled") |
| 739 | # The crash this guards: money written, status not yet updated. |
| 740 | site.create("wallet_entries", { |
| 741 | "wallet_id": "w-alice", "amount_minor": "500", "kind": "release", |
| 742 | "generated_from": "template_run/run-settled/release", "owner_id": "alice"}) |
| 743 | before = len(site.rows("wallet_entries")) |
| 744 | |
| 745 | # Control: with a readable ledger it recognises the settlement and writes nothing. |
| 746 | _needs_review_run(site, "run-control") |
| 747 | site.create("wallet_entries", { |
| 748 | "wallet_id": "w-alice", "amount_minor": "500", "kind": "release", |
| 749 | "generated_from": "template_run/run-control/release", "owner_id": "alice"}) |
| 750 | control_before = len(site.rows("wallet_entries")) |
| 751 | healthy = _resolve(site, "run-control", site.admin) |
| 752 | precondition(healthy.status == 200 and _json(healthy)["settlement"] == "already settled", |
| 753 | f"healthy ledger control: {_text(healthy)[:200]}") |
| 754 | precondition(len(site.rows("wallet_entries")) == control_before, "control wrote entries") |
| 755 | before = len(site.rows("wallet_entries")) |
| 756 | |
| 757 | real_read = object_records.read_collection_records |
| 758 | |
| 759 | def flaky_read(collection, *args, **kwargs): |
| 760 | caller = sys._getframe(1).f_code.co_filename |
| 761 | if collection == "wallet_entries" and caller.endswith("resolve_run.py"): |
| 762 | raise OSError("ledger temporarily unreadable") |
| 763 | return real_read(collection, *args, **kwargs) |
| 764 | |
| 765 | monkeypatch.setattr(object_records, "read_collection_records", flaky_read) |
| 766 | response = _resolve(site, "run-settled", site.admin) |
| 767 | monkeypatch.setattr(object_records, "read_collection_records", real_read) |
| 768 | added = site.rows("wallet_entries")[before:] |
| 769 | assert not added and response.status >= 400, ( |
| 770 | f"HTTP {response.status} {_text(response)[:80]}; wrote {[(e['kind'], e['amount_minor']) for e in added]} " |
| 771 | f"on top of the existing release") |
| 772 | |
| 773 | |
| 774 | # ============================================================================= |
| 775 | # 6 / 7. resolve_dispute and confirm_scan: no owner check |
| 776 | # ============================================================================= |
| 777 | |
| 778 | def _dispute(site, dispute_id, owner="alice"): |
| 779 | site.create("disputes", {"id": dispute_id, "kind": "other", "summary": "a dispute", |
| 780 | "status": "open", "owner_id": owner}) |
| 781 | |
| 782 | |
| 783 | def test_a_stranger_cannot_resolve_someone_elses_dispute(make_site): |
| 784 | site = make_site("app-disputes") |
| 785 | # Alice is staff (the action refuses everyone else outright); bob is a |
| 786 | # stranger with no role, refused by the staff check and by ownership. |
| 787 | alice, bob = site.user("alice", roles=["manager"]), site.user("bob") |
| 788 | _dispute(site, "d-1") |
| 789 | _dispute(site, "d-mine") |
| 790 | # Controls: the collection rules and the schema guard refuse bob; the owner may resolve. |
| 791 | precondition(site.call("/collections/disputes/records/d-1", headers=bob).status == 404, |
| 792 | "bob can read alice's dispute through the API") |
| 793 | via_api = site.call("/collections/disputes/records/d-1", method="PUT", headers=bob, |
| 794 | payload={"status": "resolved", "resolution_kind": "no_action", |
| 795 | "resolution_note": "x"}) |
| 796 | precondition(via_api.status == 403 and site.row("disputes", "d-1")["status"] == "open", |
| 797 | f"the API lets bob resolve: {via_api.status}") |
| 798 | mine = site.execute("action_resolve_dispute", |
| 799 | {"dispute_id": "d-mine", "resolution_kind": "no_action", "note": "mine"}, alice) |
| 800 | precondition(mine.status == 200 and site.row("disputes", "d-mine")["status"] == "resolved", |
| 801 | f"the owner cannot resolve her own dispute: {mine.status} {_text(mine)[:200]}") |
| 802 | |
| 803 | response = site.execute("action_resolve_dispute", |
| 804 | {"dispute_id": "d-1", "resolution_kind": "no_action", |
| 805 | "note": "bob closes alice's dispute"}, bob) |
| 806 | after = site.row("disputes", "d-1") |
| 807 | assert response.status in (403, 404) and after["status"] == "open", ( |
| 808 | f"bob got HTTP {response.status}; alice's dispute is now status={after['status']!r} " |
| 809 | f"resolved_by={after['resolved_by']!r} note={after['resolution_note']!r}") |
| 810 | |
| 811 | |
| 812 | def _scan(site, scan_id, owner): |
| 813 | site.create("scans", { |
| 814 | "id": scan_id, "filename": f"{scan_id}.jpg", "status": "extracted", |
| 815 | "extracted": json.dumps({"vendor": f"VENDOR-OF-{scan_id}", "total_cents": 4200, |
| 816 | "date": "2026-11-01"}), |
| 817 | "ocr_engine": "test", "owner_id": owner}) |
| 818 | |
| 819 | |
| 820 | def test_a_stranger_cannot_confirm_someone_elses_scan(make_site): |
| 821 | site = make_site("app-intake", "app-finance") |
| 822 | alice, bob = site.user("alice"), site.user("bob") |
| 823 | _scan(site, "scan-a", "alice") |
| 824 | precondition(site.call("/collections/scans/records/scan-a", headers=bob).status == 404, |
| 825 | "bob can read alice's scan through the API") |
| 826 | _scan(site, "scan-mine", "alice") |
| 827 | mine = site.execute("action_confirm_scan", {"scan_id": "scan-mine", "amount_cents": "4200", |
| 828 | "description": "mine"}, alice) |
| 829 | precondition(mine.status == 200, f"owner cannot confirm: {mine.status} {_text(mine)[:200]}") |
| 830 | expenses_before = len(site.rows("expenses")) |
| 831 | |
| 832 | response = site.execute("action_confirm_scan", {"scan_id": "scan-a", "amount_cents": "4200", |
| 833 | "description": "confirmed by bob"}, bob) |
| 834 | assert response.status in (403, 404) and site.row("scans", "scan-a")["status"] == "extracted" \ |
| 835 | and len(site.rows("expenses")) == expenses_before, ( |
| 836 | f"bob got HTTP {response.status}; scan-a is {site.row('scans', 'scan-a')['status']!r}; " |
| 837 | f"new expense owners: {[e['owner_id'] for e in site.rows('expenses')[expenses_before:]]}") |
| 838 | |
| 839 | |
| 840 | def test_confirm_scan_preview_does_not_disclose_another_users_scan(make_site): |
| 841 | site = make_site("app-intake", "app-finance") |
| 842 | site.user("alice") |
| 843 | bob = site.user("bob") |
| 844 | _scan(site, "scan-a", "alice") |
| 845 | precondition(site.call("/collections/scans/records/scan-a", headers=bob).status == 404, |
| 846 | "bob can read alice's scan through the API") |
| 847 | response = site.execute("action_confirm_scan", |
| 848 | {"scan_id": "scan-a", "preview": True, "amount_cents": "1"}, bob) |
| 849 | precondition(response.status in (200, 403, 404), f"unexpected {response.status}") |
| 850 | assert "VENDOR-OF-scan-a" not in _text(response), ( |
| 851 | f"bob's preview of alice's scan: HTTP {response.status} {_text(response)[:260]}") |
| 852 | |
| 853 | |
| 854 | def test_confirm_scan_ignores_a_caller_supplied_owner_id(make_site): |
| 855 | site = make_site("app-intake", "app-finance") |
| 856 | bob = site.user("bob") |
| 857 | site.user("carol") |
| 858 | _scan(site, "scan-bob", "bob") |
| 859 | # Control: with no owner_id the expense is bob's own. |
| 860 | _scan(site, "scan-bob-2", "bob") |
| 861 | plain = site.execute("action_confirm_scan", {"scan_id": "scan-bob-2", "amount_cents": "4200", |
| 862 | "description": "plain"}, bob) |
| 863 | precondition(plain.status == 200 and |
| 864 | [e["owner_id"] for e in site.rows("expenses")] == ["bob"], |
| 865 | f"control confirm: {plain.status} {_text(plain)[:200]}") |
| 866 | |
| 867 | response = site.execute("action_confirm_scan", |
| 868 | {"scan_id": "scan-bob", "amount_cents": "4200", |
| 869 | "description": "planted", "owner_id": "carol"}, bob) |
| 870 | planted = [e for e in site.rows("expenses") if e["description"] == "planted"] |
| 871 | assert not planted or planted[0]["owner_id"] == "bob", ( |
| 872 | f"bob (HTTP {response.status}) created an expense owned by {planted[0]['owner_id']!r}") |
| 873 | |
| 874 | |
| 875 | # ============================================================================= |
| 876 | # 8. customer_funds has no execute rule |
| 877 | # ============================================================================= |
| 878 | |
| 879 | def test_customer_funds_is_not_reachable_by_a_non_admin_session(make_site): |
| 880 | """REFUTED as an exposure. With no execute rule the default-deny applies: |
| 881 | anonymous and an ordinary signed-in user are refused by the permission |
| 882 | layer; only an admin-role session (or the admin token) reaches the page. |
| 883 | Residual: the page's own 'sign in' / 'admin identity required' messages are |
| 884 | unreachable for those callers, who get a bare JSON 403 instead.""" |
| 885 | site = make_site("app-billing", "app-settings") |
| 886 | alice = site.user("alice") |
| 887 | boss = site.user("boss", roles=["admin"]) |
| 888 | for path in ("/customer-funds", "/objects/site_customer_funds"): |
| 889 | for who, name in (([], "anonymous"), (alice, "alice")): |
| 890 | refused = site.call(path, headers=who, html=True) |
| 891 | assert refused.status == 403, (name, path, refused.status) |
| 892 | assert "no matching role rule" in _text(refused), _text(refused)[:200] |
| 893 | served = site.call("/customer-funds", headers=boss, html=True) |
| 894 | assert served.status == 200 |
| 895 | page = _page_text(served) |
| 896 | assert "signed in as <strong>boss</strong>" in page and "Not configured" in page, page[-400:] |
| 897 | |
| 898 | |
| 899 | # ============================================================================= |
| 900 | # 9. GET handlers that write |
| 901 | # ============================================================================= |
| 902 | |
| 903 | def _sent_document(site): |
| 904 | site.create("sent_documents", { |
| 905 | "id": "sd-1", "kind": "order", "source": "orders/ord-1", "token": "tok-doc-1", |
| 906 | "sent_to": "grace@example.test", "sent_at": _now(), "opened_at": "", |
| 907 | "owner_id": "alice"}) |
| 908 | return "tok-doc-1" |
| 909 | |
| 910 | |
| 911 | def test_opening_a_document_link_with_get_does_not_modify_the_record(make_site): |
| 912 | site = make_site("app-documents") |
| 913 | token = _sent_document(site) |
| 914 | # Control: a wrong token neither renders nor writes. |
| 915 | nothing = site.call("/d/not-a-token", html=True) |
| 916 | precondition(nothing.status == 404 and site.row("sent_documents", "sd-1")["opened_at"] == "", |
| 917 | f"unknown token control: {nothing.status}") |
| 918 | rev_before = object_records.compute_record_rev(site.row("sent_documents", "sd-1")) |
| 919 | |
| 920 | response = site.call(f"/d/{token}", html=True) # anonymous, no credentials |
| 921 | precondition(response.status in (200, 404), f"unexpected {response.status}") |
| 922 | row = site.row("sent_documents", "sd-1") |
| 923 | assert row["opened_at"] == "" and object_records.compute_record_rev(row) == rev_before, ( |
| 924 | f"anonymous GET /d/<token> -> {response.status}; opened_at is now {row['opened_at']!r}") |
| 925 | |
| 926 | |
| 927 | def _portal_invoice(site): |
| 928 | site.create("invoices", { |
| 929 | "id": "inv-1", "doc_type": "invoice", "number": "INV-1", "customer_name": "Grace", |
| 930 | "status": "sent", "total_cents": "1000", "portal_token": "tok-inv-1", |
| 931 | "portal_views": "0", "owner_id": "alice"}) |
| 932 | return "tok-inv-1" |
| 933 | |
| 934 | |
| 935 | def test_opening_the_invoice_portal_with_get_does_not_modify_the_invoice(make_site): |
| 936 | site = make_site("app-invoices") |
| 937 | token = _portal_invoice(site) |
| 938 | nothing = site.call("/pay/not-a-token", html=True) |
| 939 | precondition(nothing.status == 404 and site.row("invoices", "inv-1")["portal_views"] == "0", |
| 940 | f"unknown token control: {nothing.status}") |
| 941 | rev_before = object_records.compute_record_rev(site.row("invoices", "inv-1")) |
| 942 | |
| 943 | response = site.call(f"/pay/{token}", html=True) # anonymous, no credentials |
| 944 | precondition(response.status == 200 and "INV-1" in _text(response), |
| 945 | f"the portal did not render: {response.status}") |
| 946 | row = site.row("invoices", "inv-1") |
| 947 | assert row["portal_views"] == "0" and object_records.compute_record_rev(row) == rev_before, ( |
| 948 | f"anonymous GET /pay/<token> -> portal_views={row['portal_views']!r}, " |
| 949 | f"last_viewed_at={row['last_viewed_at']!r}, record rev changed=" |
| 950 | f"{object_records.compute_record_rev(row) != rev_before}") |
| 951 | |
| 952 | |
| 953 | # ============================================================================= |
| 954 | # 10. A deny rule with a row filter and a non-owner principal |
| 955 | # ============================================================================= |
| 956 | |
| 957 | def _policy_site(tmp_path, monkeypatch, deny_principal): |
| 958 | data = tmp_path / "data" |
| 959 | (data / "schemas").mkdir(parents=True) |
| 960 | (data / "schemas" / "notes.json").write_text(json.dumps({ |
| 961 | "name": "notes", "fields": [ |
| 962 | {"name": "id"}, {"name": "content"}, {"name": "status"}, {"name": "owner_id"}]})) |
| 963 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data)) |
| 964 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects")) |
| 965 | monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", ADMIN_TOKEN) |
| 966 | monkeypatch.setenv("DBBASIC_ENABLE_PERMISSION_ENFORCEMENT", "true") |
| 967 | monkeypatch.delenv("DBBASIC_ROW_FILTER_INDEX", raising=False) |
| 968 | object_permission_store.replace_policy({ |
| 969 | "access_mode": "role_based", |
| 970 | "rules": [ |
| 971 | {"effect": "deny", "principal": deny_principal, "actions": ["read"], |
| 972 | "collection": "notes", "row_filter": {"status": "archived"}, |
| 973 | "reason": "archived notes are put away"}, |
| 974 | {"effect": "allow", "principal": "registered", "actions": ["read"], |
| 975 | "collection": "notes", "reason": "everyone signed in reads notes"}]}, data) |
| 976 | site = Site.__new__(Site) |
| 977 | site.data = data |
| 978 | site.root = tmp_path / "objects" |
| 979 | site.admin = [("authorization", f"Token {ADMIN_TOKEN}")] |
| 980 | alice = site.user("alice") |
| 981 | for record in ({"id": "n1", "content": "open note", "status": "open", "owner_id": "bob"}, |
| 982 | {"id": "n2", "content": "archived note", "status": "archived", "owner_id": "bob"}, |
| 983 | {"id": "n3", "content": "alice archived", "status": "archived", "owner_id": "alice"}): |
| 984 | site.create("notes", record) |
| 985 | site.require_enforcement() |
| 986 | return site, alice |
| 987 | |
| 988 | |
| 989 | def test_a_filtered_deny_for_registered_hides_only_the_matching_rows(tmp_path, monkeypatch): |
| 990 | site, alice = _policy_site(tmp_path, monkeypatch, "registered") |
| 991 | # Controls: per-record decisions are exactly right, so the policy is sound. |
| 992 | assert site.call("/collections/notes/records/n1", headers=alice).status == 200 |
| 993 | assert site.call("/collections/notes/records/n2", headers=alice).status == 404 |
| 994 | assert site.call("/collections/notes/records/n3", headers=alice).status == 404 |
| 995 | listing = site.call("/collections/notes/records", headers=alice) |
| 996 | assert listing.status == 200 and [r["id"] for r in _json(listing)["records"]] == ["n1"], ( |
| 997 | f"list -> HTTP {listing.status} {_text(listing)[:120]}") |
| 998 | |
| 999 | |
| 1000 | def test_a_filtered_deny_for_the_owner_principal_hides_only_the_matching_rows(tmp_path, monkeypatch): |
| 1001 | """The documented-working case, as the contrast: the same deny with |
| 1002 | principal `owner` narrows the list instead of refusing it (alice owns n3 |
| 1003 | only, so only n3 goes; n2 is bob's and the owner-deny does not apply).""" |
| 1004 | site, alice = _policy_site(tmp_path, monkeypatch, "owner") |
| 1005 | listing = site.call("/collections/notes/records", headers=alice) |
| 1006 | assert listing.status == 200 |
| 1007 | assert [r["id"] for r in _json(listing)["records"]] == ["n1", "n2"] |