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_pages_converted_to_views.py · 20.3 KB · 409 lines
| 1 | """Three page objects became view records; a viewer must see and be able to do |
| 2 | exactly what the pages let them. |
| 3 | |
| 4 | /payments (app-payments 0.6.0), /calendar (app-events 0.2.0) and /forum |
| 5 | (app-forum 0.3.0) were hand-written page objects (81, 100 and 137 lines of |
| 6 | chrome around the shared list and form generators, with no rule in them). They |
| 7 | are now seeded `views` rows served by site_view_render. Deleting a page is only |
| 8 | safe if nothing the page did is lost, and the thing most worth losing nothing |
| 9 | of is ACCESS: pages were the source of most access bugs, because a page that |
| 10 | reads storage itself is its own gate. These pages never did -- every row they |
| 11 | showed came from /collections/<c>/records under the viewer's own session -- so |
| 12 | the claim to prove is that the generated view asks for the same rows, as the |
| 13 | same viewer, and offers the same actions. |
| 14 | |
| 15 | How the comparison works. Both the old pages and the view renderer are shells: |
| 16 | the rows are fetched by the browser. So the equivalence is taken in three |
| 17 | parts, for the owner, another user, an admin and an anonymous visitor: |
| 18 | |
| 19 | 1. What the page ASKS for (the old page rendered from the commit that still |
| 20 | had it, `git show b014147:<path>`, run in-process with the viewer's |
| 21 | identity; the new page fetched from the real ASGI app and its view record |
| 22 | read back as the viewer): which collections are listed, whether the viewer |
| 23 | id is passed (it decides which rows get Edit/Delete), the search box, the |
| 24 | sort select, the row-link pattern, and which collection each Add form |
| 25 | writes to. |
| 26 | 2. What the engine ANSWERS to that ask for that viewer (the one request both |
| 27 | generators make), which is the access claim: a view can never show a row |
| 28 | the record API would refuse, because it has no other way to get one. |
| 29 | 3. What the viewer may DO with what they see: the row actions the generator |
| 30 | offers (own rows only), and the engine's verdict on each, including the |
| 31 | ones it refuses (a payment is never deleted, whatever the page offers). |
| 32 | |
| 33 | Differences that are deliberate are asserted too, so they cannot grow: |
| 34 | signed-out visitors got a sign-in sentence from the payments and calendar |
| 35 | pages and now get the empty frame of the same view (the engine still returns |
| 36 | them nothing); the forum Add buttons were hidden from visitors and are now |
| 37 | shown (the engine still refuses the write). |
| 38 | """ |
| 39 | |
| 40 | from __future__ import annotations |
| 41 | |
| 42 | import json |
| 43 | import re |
| 44 | import shutil |
| 45 | import subprocess |
| 46 | from pathlib import Path |
| 47 | from types import SimpleNamespace |
| 48 | |
| 49 | import pytest |
| 50 | |
| 51 | from test_findings_access_control import ( # noqa: F401 (make_site is a fixture) |
| 52 | ADMIN_TOKEN, ROOT, Site, _json, _text, make_site, precondition) |
| 53 | |
| 54 | BASELINE = "b014147" # the last tree that still shipped the three page objects |
| 55 | |
| 56 | PAGES = { |
| 57 | "payments": { |
| 58 | "package": "app-payments", "url": "/payments", |
| 59 | "old": "packages/app-payments/objects/site/payments.py", |
| 60 | "view": "view_payments", "collections": ["payments"], |
| 61 | }, |
| 62 | "calendar": { |
| 63 | "package": "app-events", "url": "/calendar", |
| 64 | "old": "packages/app-events/objects/site/calendar.py", |
| 65 | "view": "view_calendar", "collections": ["events"], |
| 66 | }, |
| 67 | "forum": { |
| 68 | "package": "app-forum", "url": "/forum", |
| 69 | "old": "packages/app-forum/objects/site/forum.py", |
| 70 | "view": "view_forum", "collections": ["forum_categories", "forum_topics"], |
| 71 | }, |
| 72 | } |
| 73 | |
| 74 | |
| 75 | # -- the old page ------------------------------------------------------------ |
| 76 | |
| 77 | def _old_source(page): |
| 78 | if shutil.which("git") is None: |
| 79 | pytest.skip("no git to read the retired page from") |
| 80 | shown = subprocess.run(["git", "-C", str(ROOT), "show", f"{BASELINE}:{PAGES[page]['old']}"], |
| 81 | capture_output=True, text=True, timeout=60) |
| 82 | if shown.returncode != 0: |
| 83 | pytest.skip(f"{BASELINE} is not in this checkout's history: {shown.stderr.strip()[:120]}") |
| 84 | return shown.stdout |
| 85 | |
| 86 | |
| 87 | def _render_old(page, user_id): |
| 88 | """Run the retired page's GET with the viewer's identity, as the server would |
| 89 | (it supplies `_logger`; the page reads nothing else).""" |
| 90 | namespace = {"_logger": SimpleNamespace(info=lambda *a, **k: None)} |
| 91 | exec(compile(_old_source(page), PAGES[page]["old"], "exec"), namespace) |
| 92 | identity = {"user_id": user_id} if user_id else {} |
| 93 | return namespace["GET"]({"_identity": identity})["body"] |
| 94 | |
| 95 | |
| 96 | def _old_facts(html): |
| 97 | """What the old page's script asks the generators for, read from its HTML.""" |
| 98 | owner = re.search(r"const OWNER_ID = ('(?:[^']*)'|\"(?:[^\"]*)\");", html) |
| 99 | viewer = owner.group(1).strip("'\"") if owner else "" |
| 100 | lists = [] |
| 101 | for collection, cfg in re.findall(r'dbbasicList\("(\w+)", (\{.*?\})\);', html, flags=re.S): |
| 102 | href = re.search(r'href: \(r\) => "([^"]*)" \+ r\.id', cfg) |
| 103 | lists.append({ |
| 104 | "collection": collection, |
| 105 | "owner": "owner: OWNER_ID" in cfg and bool(viewer), # an empty id matches no row |
| 106 | "search": "search:" in cfg, |
| 107 | "sort": "sort:" in cfg, |
| 108 | "href": (href.group(1) + "{id}") if href else None, |
| 109 | }) |
| 110 | forms = set(re.findall(r'dbbasicForm\("(\w+)"', html)) |
| 111 | # The calendar's quick-add posts to the records API itself. |
| 112 | forms |= set(re.findall(r'fetch\("/collections/(\w+)/records"', html)) |
| 113 | return { |
| 114 | "viewer": viewer, |
| 115 | "gated": "to see" in html and "dbbasicList" not in html, # the sign-in sentence |
| 116 | "lists": lists, |
| 117 | "add_forms": forms, |
| 118 | # An Add button is what lets a viewer open one of those forms. The |
| 119 | # calendar's quick-add strip is always open, so it counts as one. |
| 120 | "add_buttons": len(re.findall(r'<button[^>]*id="add\w*"', html)) |
| 121 | + (1 if 'id="capture-form"' in html else 0), |
| 122 | } |
| 123 | |
| 124 | |
| 125 | # -- the new page ------------------------------------------------------------- |
| 126 | |
| 127 | def _new_facts(site, page, headers): |
| 128 | """The same facts from the real page: GET the route, read the shell's viewer |
| 129 | and view ids, then read the view record AS THE VIEWER (the renderer does).""" |
| 130 | spec = PAGES[page] |
| 131 | response = site.call(spec["url"], headers=headers, html=True) |
| 132 | assert response.status == 200, (response.status, _text(response)[:200]) |
| 133 | html = _text(response) |
| 134 | view_id = re.search(r"const VIEW_ID = '([^']*)'", html).group(1) |
| 135 | viewer = re.search(r"const VIEWER_ID = '([^']*)'", html).group(1) |
| 136 | assert view_id == spec["view"] |
| 137 | record = site.call(f"/collections/views/records/{view_id}", headers=headers) |
| 138 | assert record.status == 200, "the view must be readable by every viewer" |
| 139 | blocks = json.loads(_json(record)["record"]["blocks"]) |
| 140 | lists, forms = [], set() |
| 141 | for block in blocks: |
| 142 | assert block["kind"] == "list" |
| 143 | lists.append({ |
| 144 | "collection": block["collection"], |
| 145 | "owner": bool(block.get("owner_scoped")) and bool(viewer), |
| 146 | "search": bool(block.get("search")), |
| 147 | "sort": bool(block.get("sort")), |
| 148 | "href": block.get("href_template"), |
| 149 | }) |
| 150 | if block.get("add"): |
| 151 | forms.add(block["collection"]) |
| 152 | return {"viewer": viewer, "lists": lists, "add_forms": forms, "blocks": blocks} |
| 153 | |
| 154 | |
| 155 | # -- data --------------------------------------------------------------------- |
| 156 | |
| 157 | def _seed(site, page): |
| 158 | """alice owns one row of each collection, bob one, nobody else any.""" |
| 159 | if page == "payments": |
| 160 | site.create("invoices", {"id": "inv-x", "number": "INV-X", "customer_name": "Cust", "status": "sent", "total_cents": "10000", "owner_id": "alice"}) |
| 161 | for pid, owner in (("pay-alice", "alice"), ("pay-bob", "bob")): |
| 162 | site.create("payments", {"id": pid, "invoice_id": "inv-x", "amount_cents": "1000", |
| 163 | "method": "cash", "received_on": "2026-11-01", "status": "received", "owner_id": owner}) |
| 164 | elif page == "calendar": |
| 165 | for eid, owner in (("ev-alice", "alice"), ("ev-bob", "bob")): |
| 166 | site.create("events", {"id": eid, "title": f"{owner}'s event", "purpose": "meeting", |
| 167 | "starts_at": "2026-12-01T10:00:00", "owner_id": owner}) |
| 168 | else: |
| 169 | for cid, owner in (("cat-alice", "alice"), ("cat-bob", "bob")): |
| 170 | site.create("forum_categories", {"id": cid, "name": f"{owner} cat", "slug": cid, |
| 171 | "owner_id": owner}) |
| 172 | for tid, owner in (("top-alice", "alice"), ("top-bob", "bob")): |
| 173 | site.create("forum_topics", {"id": tid, "category_id": "cat-alice", "title": f"{owner} topic", |
| 174 | "content": "c", "views": "3", "is_pinned": "true", |
| 175 | "owner_id": owner}) |
| 176 | |
| 177 | |
| 178 | def _rows(site, collection, headers): |
| 179 | """The one request both generators make for a list.""" |
| 180 | response = site.call(f"/collections/{collection}/records", headers=headers, query="limit=500") |
| 181 | if response.status != 200: |
| 182 | return response.status |
| 183 | return sorted(r["id"] for r in _json(response)["records"]) |
| 184 | |
| 185 | |
| 186 | def _offered_actions(rows_by_id, owners, viewer): |
| 187 | """The generator offers Edit/Delete on a row only when both the viewer id |
| 188 | and the row's owner_id are present and equal (list.py isMine).""" |
| 189 | return sorted(i for i, owner in owners.items() if viewer and owner and owner == viewer and i in rows_by_id) |
| 190 | |
| 191 | |
| 192 | @pytest.fixture |
| 193 | def world(make_site): |
| 194 | def build(page): |
| 195 | site = make_site(PAGES[page]["package"]) |
| 196 | site.viewers = { |
| 197 | "alice": site.user("alice"), "bob": site.user("bob"), |
| 198 | "admin": site.admin, "anonymous": [], |
| 199 | } |
| 200 | _seed(site, page) |
| 201 | return site |
| 202 | return build |
| 203 | |
| 204 | |
| 205 | VIEWERS = ["alice", "bob", "admin", "anonymous"] |
| 206 | |
| 207 | |
| 208 | # ============================================================================= |
| 209 | # 1 + 2 + 3. the equivalence, per page and viewer |
| 210 | # ============================================================================= |
| 211 | |
| 212 | @pytest.mark.parametrize("page", list(PAGES)) |
| 213 | def test_the_view_asks_for_what_the_page_asked_for_as_the_same_viewer(world, page): |
| 214 | site = world(page) |
| 215 | for who in VIEWERS: |
| 216 | headers = site.viewers[who] |
| 217 | new = _new_facts(site, page, headers) |
| 218 | old = _old_facts(_render_old(page, new["viewer"] or None)) |
| 219 | if old["gated"]: |
| 220 | # Signed-out payments/calendar: the old page requested nothing at all. |
| 221 | # The new one requests the lists; the next test shows the engine |
| 222 | # answers a visitor with nothing, so the visible result is the same. |
| 223 | assert who == "anonymous" and not old["lists"] |
| 224 | continue |
| 225 | assert old["viewer"] == new["viewer"], who |
| 226 | assert new["lists"] == old["lists"], who |
| 227 | assert new["add_forms"] == old["add_forms"], who |
| 228 | new_buttons = sum(1 for lst in new["blocks"] if lst.get("add")) |
| 229 | if who == "anonymous": |
| 230 | # Deliberate: the forum hid its Add buttons from visitors; the view |
| 231 | # shows them (test_forum_visitors_read_everything... pins the refusal). |
| 232 | assert (old["add_buttons"], new_buttons) == (0, 2) |
| 233 | else: |
| 234 | assert old["add_buttons"] == new_buttons, who |
| 235 | |
| 236 | |
| 237 | @pytest.mark.parametrize("page", list(PAGES)) |
| 238 | def test_every_viewer_is_shown_exactly_the_rows_the_record_api_gives_them(world, page): |
| 239 | site = world(page) |
| 240 | expected = { |
| 241 | "payments": {"alice": ["pay-alice"], "bob": ["pay-bob"], |
| 242 | "admin": ["pay-alice", "pay-bob"], "anonymous": 403}, |
| 243 | "calendar": {"alice": ["ev-alice"], "bob": ["ev-bob"], |
| 244 | "admin": ["ev-alice", "ev-bob"], "anonymous": 403}, |
| 245 | "forum": {w: ["top-alice", "top-bob"] for w in VIEWERS}, |
| 246 | }[page] |
| 247 | for collection in PAGES[page]["collections"]: |
| 248 | for who in VIEWERS: |
| 249 | got = _rows(site, collection, site.viewers[who]) |
| 250 | want = expected[who] if collection in ("payments", "events", "forum_topics") else ( |
| 251 | ["cat-alice", "cat-bob"]) |
| 252 | if want == 403: |
| 253 | assert got in (401, 403), (collection, who, got) |
| 254 | else: |
| 255 | assert got == want, (collection, who, got) |
| 256 | |
| 257 | |
| 258 | @pytest.mark.parametrize("page", list(PAGES)) |
| 259 | def test_the_signed_out_difference_is_cosmetic_the_visitor_still_gets_no_data(world, page): |
| 260 | """The old payments/calendar pages replaced themselves with a sign-in |
| 261 | sentence for a visitor; the view shows its frame and the engine returns the |
| 262 | list nothing. Same data, different words -- and the forum, which is public |
| 263 | read, shows a visitor the same rows in both.""" |
| 264 | site = world(page) |
| 265 | old = _old_facts(_render_old(page, None)) |
| 266 | new = _new_facts(site, page, []) |
| 267 | private = page in ("payments", "calendar") |
| 268 | assert old["gated"] is private |
| 269 | for collection in PAGES[page]["collections"]: |
| 270 | rows = _rows(site, collection, []) |
| 271 | assert (rows in (401, 403)) is private, (collection, rows) |
| 272 | assert new["viewer"] == "" |
| 273 | |
| 274 | |
| 275 | @pytest.mark.parametrize("page", list(PAGES)) |
| 276 | def test_row_actions_offered_are_the_same_and_the_engine_decides_them(world, page): |
| 277 | site = world(page) |
| 278 | owners = { |
| 279 | "payments": {"pay-alice": "alice", "pay-bob": "bob"}, |
| 280 | "calendar": {"ev-alice": "alice", "ev-bob": "bob"}, |
| 281 | "forum": {"top-alice": "alice", "top-bob": "bob", "cat-alice": "alice", "cat-bob": "bob"}, |
| 282 | }[page] |
| 283 | for who in VIEWERS: |
| 284 | new = _new_facts(site, page, site.viewers[who]) |
| 285 | old = _old_facts(_render_old(page, new["viewer"] or None)) |
| 286 | if old["gated"]: |
| 287 | continue |
| 288 | for old_list, new_list in zip(old["lists"], new["lists"]): |
| 289 | # The generator's own rule (list.py isMine): both ids present and equal, |
| 290 | # and only if the list was handed the viewer at all. |
| 291 | def offered(facts, lst): |
| 292 | viewer = facts["viewer"] if lst["owner"] else "" |
| 293 | return _offered_actions(owners, owners, viewer) |
| 294 | assert offered(old, old_list) == offered(new, new_list), (who, old_list["collection"]) |
| 295 | # The calendar never offered row actions (it passes no owner), and still doesn't. |
| 296 | if page == "calendar": |
| 297 | assert offered(new, new_list) == [] |
| 298 | |
| 299 | |
| 300 | # -- permission refusals: the engine's verdicts, unchanged by deleting the pages --- |
| 301 | |
| 302 | def test_payments_other_users_cannot_touch_an_owners_payment_and_nobody_deletes_one(world): |
| 303 | site = world("payments") |
| 304 | alice, bob, anon = site.viewers["alice"], site.viewers["bob"], [] |
| 305 | path = "/collections/payments/records/pay-alice" |
| 306 | assert site.call(path, headers=bob).status in (403, 404) |
| 307 | assert site.call(path, headers=anon).status in (401, 403, 404) |
| 308 | assert site.call(path, method="PUT", payload={"notes": "x"}, headers=bob).status in (403, 404) |
| 309 | # Both generators offer the owner a delete button; the engine refuses it (a |
| 310 | # recorded payment is never deleted), exactly as before the page went. |
| 311 | assert site.call(path, method="DELETE", headers=alice).status in (403, 405) |
| 312 | assert site.row("payments", "pay-alice")["id"] == "pay-alice" |
| 313 | |
| 314 | |
| 315 | def test_calendar_a_visitor_cannot_add_an_event_and_a_user_cannot_add_one_as_someone_else(world): |
| 316 | site = world("calendar") |
| 317 | record = {"id": "ev-new", "title": "t", "starts_at": "2026-12-02T10:00:00", "purpose": "meeting"} |
| 318 | assert site.call("/collections/events/records", method="POST", |
| 319 | payload=dict(record, owner_id="alice"), headers=[]).status in (401, 403) |
| 320 | # The old quick-add posted owner_id from the page; the form does the same. The |
| 321 | # engine is the gate for both. |
| 322 | forged = site.call("/collections/events/records", method="POST", |
| 323 | payload=dict(record, id="ev-forged", owner_id="alice"), headers=site.viewers["bob"]) |
| 324 | assert forged.status in (400, 403, 404, 409, 422), forged.status |
| 325 | assert not [r for r in site.rows("events") if r["id"] == "ev-forged" and r["owner_id"] == "alice"] |
| 326 | own = site.call("/collections/events/records", method="POST", |
| 327 | payload=dict(record, id="ev-own", owner_id="bob"), headers=site.viewers["bob"]) |
| 328 | assert own.status in (200, 201), (own.status, _text(own)[:200]) |
| 329 | |
| 330 | |
| 331 | def test_forum_visitors_read_everything_but_write_nothing_and_users_edit_only_their_own(world): |
| 332 | site = world("forum") |
| 333 | assert site.call("/collections/forum_topics/records/top-alice", headers=[]).status == 200 |
| 334 | for collection, rec in (("forum_topics", {"id": "t-new", "category_id": "cat-alice", "title": "t", |
| 335 | "content": "c", "owner_id": "x"}), |
| 336 | ("forum_categories", {"id": "c-new", "name": "n", "slug": "n", "owner_id": "x"})): |
| 337 | # The view shows a visitor the Add button; the engine refuses what it posts. |
| 338 | assert site.call(f"/collections/{collection}/records", method="POST", |
| 339 | payload=rec, headers=[]).status in (401, 403) |
| 340 | bob = site.viewers["bob"] |
| 341 | assert site.call("/collections/forum_topics/records/top-alice", method="PUT", |
| 342 | payload={"title": "hijack"}, headers=bob).status in (403, 404) |
| 343 | assert site.call("/collections/forum_topics/records/top-alice", method="DELETE", |
| 344 | headers=bob).status in (403, 404) |
| 345 | assert site.row("forum_topics", "top-alice")["title"] == "alice topic" |
| 346 | own = site.call("/collections/forum_topics/records/top-bob", method="PUT", |
| 347 | payload={"title": "mine"}, headers=bob) |
| 348 | assert own.status == 200, (own.status, _text(own)[:200]) |
| 349 | |
| 350 | |
| 351 | # ============================================================================= |
| 352 | # the conversion itself |
| 353 | # ============================================================================= |
| 354 | |
| 355 | @pytest.mark.parametrize("page", list(PAGES)) |
| 356 | def test_the_page_object_is_gone_and_its_grant_is_retracted(world, page): |
| 357 | spec = PAGES[page] |
| 358 | site = world(page) |
| 359 | object_id = "site_" + ("forum" if page == "forum" else page) |
| 360 | manifest = json.loads((ROOT / "packages" / spec["package"] / "dbbasic-package.json").read_text()) |
| 361 | assert object_id not in {o["id"] for o in manifest["objects"]} |
| 362 | assert not (ROOT / spec["old"]).exists() |
| 363 | rules = json.loads((ROOT / "packages" / spec["package"] / "permissions" / "rules.json").read_text()) |
| 364 | assert object_id not in {r.get("object_id") for r in rules["rules"]} |
| 365 | assert object_id in {r.get("object_id") for r in rules.get("retracted", [])} |
| 366 | # Nothing answers at the old object id, even for an admin. |
| 367 | assert site.call(f"/objects/{object_id}", headers=site.admin).status == 404 |
| 368 | # And nothing may be created there later by the leftover grant. |
| 369 | for who in ([], site.viewers["alice"]): |
| 370 | assert site.call(f"/objects/{object_id}", headers=who).status in (401, 403, 404) |
| 371 | |
| 372 | |
| 373 | @pytest.mark.parametrize("page", list(PAGES)) |
| 374 | def test_the_view_is_public_but_only_an_admin_can_change_it(world, page): |
| 375 | site = world(page) |
| 376 | view_id = PAGES[page]["view"] |
| 377 | path = f"/collections/views/records/{view_id}" |
| 378 | for who in VIEWERS: |
| 379 | assert site.call(path, headers=site.viewers[who]).status == 200, who |
| 380 | for who in ("alice", "bob", "anonymous"): |
| 381 | refused = site.call(path, method="PUT", payload={"blocks": "[]"}, headers=site.viewers[who]) |
| 382 | assert refused.status in (401, 403, 404), (who, refused.status) |
| 383 | assert site.call(path, method="DELETE", headers=site.viewers[who]).status in (401, 403, 404) |
| 384 | |
| 385 | |
| 386 | def test_every_option_the_seeded_blocks_use_is_one_the_renderer_reads(): |
| 387 | """An unread key in a block is silently ignored: the page would render |
| 388 | without the search box or the owner's row actions and nothing would say so.""" |
| 389 | renderer = (ROOT / "packages/app-views/objects/site/view_render.py").read_text() |
| 390 | read = set(re.findall(r"block\.(\w+)", renderer)) |
| 391 | for page, spec in PAGES.items(): |
| 392 | seed = ROOT / "packages" / spec["package"] / "seed" / "views.tsv" |
| 393 | import csv |
| 394 | with open(seed, newline="") as handle: |
| 395 | rows = [r for r in csv.DictReader(handle, delimiter="\t") if r["id"] == spec["view"]] |
| 396 | assert len(rows) == 1, page |
| 397 | for block in json.loads(rows[0]["blocks"]): |
| 398 | assert set(block) - {"kind"} <= read, (page, set(block) - read) |
| 399 | |
| 400 | |
| 401 | def test_forum_pinned_solved_and_views_stay_visible_as_columns(): |
| 402 | """The old topic row folded `pinned . solved . N views` into a subtitle. The |
| 403 | view has no subtitle composition, so the schema says table and the three |
| 404 | facts are columns -- losing none of them.""" |
| 405 | schema = json.loads((ROOT / "packages/app-forum/schemas/forum_topics.json").read_text()) |
| 406 | assert schema["views"]["list_mode"] == "table" |
| 407 | assert {"is_pinned", "is_solved", "views", "title"} <= set(schema["views"]["list_fields"]) |
| 408 | old = _old_source("forum") |
| 409 | assert all(fact in old for fact in ("r.is_pinned", "r.is_solved", "r.views")) |