Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/test_object_access.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 18 minutes ago History
test_object_access.py · 15.4 KB · 329 lines
1"""object_access: the permission engine asked from inside an object.
2
3Two halves. The unit half pins what the helper itself promises (an
4identity is the four fields the server sets and nothing else; no identity
5is anonymous; an unreadable policy refuses everybody; missing and refused
6are one answer). The end-to-end half is the legitimate path for every page
7and action the 2026-11-28 access-control findings closed: the owner and an
8admin still get through, a guest with the order's token still gets through,
9and a stranger gets the same answer as a mistyped id. The refusals
10themselves are pinned in tests/test_findings_access_control.py; these are
11the "and we did not just lock everybody out" half.
12
13Everything runs the real ASGI app in process with enforcement on (the
14harness from test_findings_access_control), so a fix that only worked
15because the HTTP layer happened to refuse first would not pass here.
16"""
17
18from __future__ import annotations
19
20import json
21
22import pytest
23
24import object_access
25import object_permission_store
26import object_records
27from test_findings_access_control import ( # noqa: F401 (make_site is a fixture)
28 _json,
29 _page_text,
30 _seed_orders,
31 _seed_shipped_order,
32 _seed_thread,
33 _template,
34 make_site,
35)
36
37
38# =============================================================================
39# The helper
40# =============================================================================
41
42POLICY = {
43 "access_mode": "role_based",
44 "rules": [
45 {"effect": "allow", "principal": "registered", "actions": ["read", "update"],
46 "collection": "things", "row_filter": {"owner_id": "$user_id"}},
47 {"effect": "allow", "principal": "registered", "actions": ["read"],
48 "collection": "things", "row_filter": {"is_public": "true"}},
49 ],
50}
51
52
53@pytest.fixture
54def things(tmp_path):
55 data = tmp_path / "data"
56 (data / "schemas").mkdir(parents=True)
57 (data / "schemas" / "things.json").write_text(json.dumps({
58 "name": "things", "fields": [{"name": "id"}, {"name": "owner_id"},
59 {"name": "is_public"}]}))
60 object_permission_store.replace_policy(POLICY, data)
61 for record in ({"id": "t-ann", "owner_id": "ann", "is_public": "false"},
62 {"id": "t-pub", "owner_id": "bob", "is_public": "true"},
63 {"id": "t-bob", "owner_id": "bob", "is_public": "false"}):
64 object_records.create_collection_record("things", record, base_dir=data)
65 return data
66
67
68def test_an_identity_is_the_four_fields_the_server_sets_and_nothing_else(things):
69 """`is_admin` is not something the server puts in _identity; honouring
70 it would make a payload key an authority. Roles are the one mechanism."""
71 flagged = object_access.Access({"user_id": "eve", "is_admin": True}, base_dir=things)
72 assert not flagged.is_admin
73 assert flagged.get("things", "t-bob") is None
74 admin = object_access.Access({"user_id": "ops", "roles": ["admin"]}, base_dir=things)
75 assert admin.is_admin
76 assert admin.get("things", "t-bob")["id"] == "t-bob"
77
78
79def test_no_identity_is_anonymous_and_sees_nothing(things):
80 for identity in (None, {}, "not-a-mapping", {"user_id": ""}, {"user_id": None}):
81 access = object_access.Access(identity, base_dir=things)
82 assert not access.signed_in
83 assert access.get("things", "t-ann") is None
84 assert access.get("things", "t-pub") is None
85
86
87def test_a_role_given_as_a_bare_string_is_not_split_into_letters(things):
88 access = object_access.Access({"user_id": "eve", "roles": "admin"}, base_dir=things)
89 assert access.subject.roles == () and not access.is_admin
90
91
92def test_the_owner_and_the_rules_decide_exactly_as_the_api_would(things):
93 ann = object_access.Access({"user_id": "ann"}, base_dir=things)
94 assert ann.get("things", "t-ann")["id"] == "t-ann"
95 assert ann.get("things", "t-pub")["id"] == "t-pub" # is_public rule
96 assert ann.get("things", "t-bob") is None
97 assert ann.get("things", "t-pub", action="update") is None # read-only rule
98 rows = object_records.read_collection_records("things", base_dir=things)
99 assert [r["id"] for r in ann.visible("things", rows)] == ["t-ann", "t-pub"]
100
101
102def test_missing_and_refused_are_the_same_answer(things):
103 ann = object_access.Access({"user_id": "ann"}, base_dir=things)
104 assert ann.get("things", "t-bob") is None
105 assert ann.get("things", "no-such-thing") is None
106 assert ann.get("things", "") is None
107 assert ann.get("no_such_collection", "x") is None
108
109
110def test_an_unreadable_policy_refuses_everybody_admins_included(things):
111 """Without the policy there is no way to know who the admin roles are,
112 so the fail-closed answer is no for everyone."""
113 (things / "permissions" / "policy.json").write_text("{not json")
114 for identity in ({"user_id": "ann"}, {"user_id": "ops", "roles": ["admin"]}):
115 access = object_access.Access(identity, base_dir=things)
116 assert access.policy is None and not access.is_admin
117 assert access.get("things", "t-ann") is None
118 assert access.visible("things", [{"id": "t-ann", "owner_id": "ann"}]) == []
119
120
121def test_no_policy_file_still_lets_the_owner_and_an_admin_in(tmp_path):
122 """A box that never wrote a policy uses the conservative default (no
123 grants): the engine's owner fallback and admin role still apply, the
124 way they do for the API."""
125 data = tmp_path / "data"
126 data.mkdir()
127 row = {"id": "x", "owner_id": "ann"}
128 assert object_access.Access({"user_id": "ann"}, base_dir=data).can("read", "c", row)
129 assert object_access.Access({"user_id": "o", "roles": ["admin"]},
130 base_dir=data).can("update", "c", row)
131 assert not object_access.Access({"user_id": "bob"}, base_dir=data).can("read", "c", row)
132
133
134# =============================================================================
135# The legitimate paths, end to end
136# =============================================================================
137
138def _boss(site):
139 return site.user("boss", roles=["admin"])
140
141
142def test_an_admin_still_opens_any_kitchen_ticket(make_site):
143 site = make_site("app-kitchen")
144 boss = _boss(site)
145 _seed_orders(site)
146 page = site.call("/kitchen/so-1/ticket", headers=boss, html=True)
147 assert page.status == 200 and "ALICE-PRIVATE-NOTE" in page.body.decode()
148
149
150def test_an_admin_still_reads_any_dropship_margin(make_site):
151 site = make_site("app-orders")
152 boss = _boss(site)
153 _seed_orders(site)
154 for order_id in ("so-1", "po-1"): # it works from either end
155 page = site.call(f"/orders/{order_id}/margin", headers=boss, html=True)
156 assert page.status == 200 and "12.00 USD" in _page_text(page)
157
158
159def test_a_sale_whose_purchase_order_the_caller_cannot_read_shows_no_vendor_cost(make_site):
160 """Owner of the sale, not of the vendor-side purchase order: the
161 vendor's price is exactly what is being protected, so the page says
162 there is no pair rather than printing it."""
163 site = make_site("app-orders")
164 alice = site.user("alice")
165 _seed_orders(site)
166 object_records.update_collection_record(
167 "orders", "po-1", {"owner_id": "vendor-desk"}, base_dir=site.data)
168 page = site.call("/orders/so-1/margin", headers=alice, html=True)
169 assert page.status == 409
170 assert "8.00 USD" not in _page_text(page) and "Alice Secret Supplier" not in _page_text(page)
171
172
173def test_an_admin_still_opens_any_receiving_sheet(make_site):
174 site = make_site("app-receiving")
175 boss = _boss(site)
176 _seed_orders(site)
177 page = site.call("/purchase-orders/po-1/receive", headers=boss, html=True)
178 assert page.status == 200 and "Alice Secret Supplier" in page.body.decode()
179
180
181def test_the_return_form_still_opens_for_the_owner_an_admin_and_the_token(make_site):
182 site = make_site("app-returns")
183 alice, boss, bob = site.user("alice"), _boss(site), site.user("bob")
184 _seed_shipped_order(site)
185 for headers, query in ((alice, ""), (boss, ""), ([], "token=tok-alice-5")):
186 page = site.call("/returns/so-5", headers=headers, html=True, query=query)
187 assert page.status == 200 and "Carol Customer" in page.body.decode(), (headers, query)
188 # A signed-in account holding the link is NOT let in by it (app-returns
189 # 0.6.3): the token is a guest's credential, and a session acts as the
190 # person it names. It used to be ("a guest who has an account"), and any
191 # account with a buyer's forwarded link got an RMA authorized in its own
192 # name. The refusal says how the buyer gets in: signed out.
193 page = site.call("/returns/so-5", headers=bob, html=True, query="token=tok-alice-5")
194 assert page.status == 404 and "Carol Customer" not in page.body.decode()
195 assert "sign out" in page.body.decode()
196 # And a stranger's refusal is the same page as a mistyped id.
197 refused = site.call("/returns/so-5", headers=bob, html=True)
198 missing = site.call("/returns/no-such-order", headers=bob, html=True)
199 assert refused.status == missing.status == 404
200 assert _page_text(refused) == _page_text(missing)
201
202
203@pytest.mark.parametrize("who", ["owner", "admin", "guest-token"])
204def test_a_return_can_still_be_raised_by_the_owner_an_admin_and_the_token_holder(
205 make_site, who):
206 site = make_site("app-returns")
207 alice, boss = site.user("alice"), _boss(site)
208 _seed_shipped_order(site)
209 headers, payload = {"owner": (alice, {}), "admin": (boss, {}),
210 "guest-token": ([], {"token": "tok-alice-5"})}[who]
211 response = site.call("/returns/so-5", method="POST", headers=headers, html=True,
212 payload={"reason": "damaged", "qty_sl-1": "1", **payload})
213 assert response.status == 200, _page_text(response)[-300:]
214 inbound = [s for s in site.rows("shipments")
215 if s["order_id"] == "so-5" and s["direction"] == "inbound"]
216 assert len(inbound) == 1
217 assert inbound[0]["owner_id"] == "alice" # the order's owner, whoever asked
218
219
220def test_an_admin_can_still_confirm_anyones_scan_and_it_lands_in_their_books(make_site):
221 site = make_site("app-intake", "app-finance")
222 site.user("alice")
223 boss = _boss(site)
224 site.create("scans", {
225 "id": "scan-a", "filename": "a.jpg", "status": "extracted",
226 "extracted": json.dumps({"vendor": "V", "total_cents": 4200, "date": "2026-11-01"}),
227 "ocr_engine": "test", "owner_id": "alice"})
228 done = site.execute("action_confirm_scan",
229 {"scan_id": "scan-a", "amount_cents": "4200",
230 "description": "by the bookkeeper", "owner_id": "boss"}, boss)
231 assert done.status == 200, done.body[:200]
232 assert [e["owner_id"] for e in site.rows("expenses")] == ["alice"]
233
234
235def test_an_admin_can_still_resolve_anyones_dispute(make_site):
236 site = make_site("app-disputes")
237 site.user("alice")
238 boss = _boss(site)
239 site.create("disputes", {"id": "d-1", "kind": "other", "summary": "a dispute",
240 "status": "open", "owner_id": "alice"})
241 done = site.execute("action_resolve_dispute",
242 {"dispute_id": "d-1", "resolution_kind": "no_action",
243 "note": "closed by support"}, boss)
244 assert done.status == 200, done.body[:200]
245 assert site.row("disputes", "d-1")["status"] == "resolved"
246
247
248def test_a_public_template_can_still_be_run_by_anyone_signed_in(make_site):
249 site = make_site("app-runner")
250 bob = site.user("bob")
251 _template(site, "tpl-shared", "alice", public="true")
252 ok = site.execute("action_run_template", {"template_id": "tpl-shared"}, bob)
253 assert ok.status == 200 and _json(ok)["status"] == "queued"
254 run = site.row("template_runs", _json(ok)["run_id"])
255 assert run["owner_id"] == "bob" # the run is the runner's
256
257
258def test_an_admin_still_reads_every_template_run(make_site):
259 site = make_site("app-runner")
260 alice, bob, boss = site.user("alice"), site.user("bob"), _boss(site)
261 _template(site, "tpl-a", "alice")
262 _template(site, "tpl-b", "bob")
263 ids = {_json(site.execute("action_run_template", {"template_id": t}, who))["run_id"]
264 for t, who in (("tpl-a", alice), ("tpl-b", bob))}
265 listing = site.call("/collections/template_runs/records", headers=boss)
266 assert {r["id"] for r in _json(listing)["records"]} == ids
267
268
269def test_an_agent_still_sees_its_own_spend(make_site):
270 """The ledger is keyed by the agent id; the agent's own session may read
271 it through the API, so the board shows it the spend."""
272 site = make_site("app-agents", "app-billing")
273 agent = site.user("agent-x")
274 site.create("agent_registry", {
275 "agent_id": "agent-x", "label": "Agent X", "status": "active",
276 "spend_cap_minor": "1000", "owner_id": "alice"})
277 site.create("wallets", {"id": "w-agent", "owner_id": "agent-x", "kind": "balance"})
278 site.create("wallet_entries", {"wallet_id": "w-agent", "amount_minor": "-1500",
279 "kind": "debit", "owner_id": "agent-x"})
280 board = _json(site.call("/agents.json", headers=agent))
281 assert board["agents"][0]["spend"]["committed_minor"] == 1500
282 assert board["over_cap"] == ["agent-x"]
283
284
285def test_an_author_still_sees_their_own_moderated_comment_and_its_status(make_site):
286 site = make_site("app-thread")
287 alice = site.user("alice")
288 _seed_thread(site)
289 listing = site.call("/collections/thread_comments/records", headers=alice,
290 query="parent_collection=notes&parent_id=n1")
291 by_id = {r["id"]: r for r in _json(listing)["records"]}
292 assert set(by_id) == {"c-ok", "c-removed", "c-flagged", "c-pending"}
293 assert by_id["c-removed"]["status"] == "removed"
294 assert by_id["c-removed"]["owner_id"] == "alice"
295
296
297def test_a_moderator_reads_every_comment_and_another_user_only_published_ones(make_site):
298 site = make_site("app-thread")
299 mod, bob = site.user("mod", roles=["moderator"]), site.user("bob")
300 _seed_thread(site)
301 seen = {}
302 for name, headers in (("mod", mod), ("bob", bob)):
303 listing = site.call("/collections/thread_comments/records", headers=headers,
304 query="parent_collection=notes&parent_id=n1")
305 seen[name] = {r["id"] for r in _json(listing)["records"]}
306 assert seen["mod"] == {"c-ok", "c-removed", "c-flagged", "c-pending"}
307 assert seen["bob"] == {"c-ok"}
308
309
310def test_a_comment_written_before_moderation_existed_is_still_readable(make_site):
311 """A blank status is what the schema defaults to published (every write
312 path stamps the default, so a blank only exists in a row put in the
313 file some other way, e.g. an import); it must not vanish for everyone
314 else. Appended raw, the only way such a row exists."""
315 site = make_site("app-thread")
316 bob = site.user("bob")
317 site.create("thread_comments", {"id": "c-seed", "parent_collection": "other",
318 "parent_id": "x", "body": "makes the file",
319 "owner_id": "alice"})
320 path = site.data / "collections" / "thread_comments" / "records.tsv"
321 header = path.read_text().splitlines()[0].split("\t")
322 row = {"id": "c-old", "parent_collection": "notes", "parent_id": "n1",
323 "body": "from before", "owner_id": "alice", "status": ""}
324 with path.open("a") as handle:
325 handle.write("\t".join(row.get(name, "") for name in header) + "\n")
326 assert site.row("thread_comments", "c-old")["status"] == ""
327 listing = site.call("/collections/thread_comments/records", headers=bob,
328 query="parent_collection=notes&parent_id=n1")
329 assert [r["id"] for r in _json(listing)["records"]] == ["c-old"]