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_owner_fallback_opt_out.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, 19 minutes ago History
test_owner_fallback_opt_out.py · 34.0 KB · 671 lines
1"""A package can switch the owner fallback off for a collection.
2
3The engine's last resort (docs/permissions-model.md, the decision flowchart)
4is the owner fallback: with no rule matching, whoever a record's `owner_id`,
5`user_id` or `created_by` names may read, update and delete it. That is the
6documented default and it is not changed here.
7
8What it meant for a package that deliberately grants only READ on a
9collection -- template_runs ("READ ONLY, and the absence of update is the
10enforcement of the state machine"), wallet_entries ("No create/update/
11delete") -- is that the absence enforced nothing in the engine: asked about
12the owner's own row, `check_permission` said yes.
13
14Where that answer reaches, as measured by the tests below:
15
16- NOT the generic record API on a stock install. PUT and DELETE first ask the
17 collection-level question with no record (so a missing id cannot be told
18 from a forbidden one), the fallback needs a record, and with no update or
19 delete rule on the collection that first question is a 403. So the
20 reported "a run's owner can PUT their own run" does not reproduce there.
21- The record API as soon as ANY allow rule for that action lets the subject
22 through the first question -- a role rule with a row filter is enough. The
23 record-level check then falls through to the owner fallback for a row the
24 filter does not cover.
25- Every in-object check, `object_access.Access.can("update", ...)`, which has
26 no first question at all.
27
28The opt-out is a rule, so it installs, upgrades and retires like any other:
29
30 {"effect": "deny", "principal": "owner_fallback",
31 "actions": ["update", "delete"], "collection": "template_runs"}
32
33It removes the fallback and nothing else. An explicit allow rule still
34grants (it is consulted first), admins are decided before any rule, and
35in-process writers never ask.
36"""
37
38from __future__ import annotations
39
40import asyncio
41import json
42from datetime import datetime, timezone
43from pathlib import Path
44
45import pytest
46
47import object_access
48import object_identity
49import object_packages
50import object_permission_store
51import object_permissions as permissions
52import object_records
53import object_server
54
55ROOT = Path(__file__).resolve().parents[1]
56PACKAGES_ROOT = ROOT / "packages"
57ADMIN_TOKEN = "unit-test-only-admin-token"
58
59OWNER = permissions.PermissionSubject(user_id="7")
60STRANGER = permissions.PermissionSubject(user_id="8")
61ADMIN = permissions.PermissionSubject(user_id="1", roles=("admin",))
62MINE = {"id": "r1", "owner_id": "7", "status": "succeeded"}
63
64
65def opt_out(actions=("update", "delete"), **where):
66 return permissions.PermissionRule.deny(
67 permissions.OWNER_FALLBACK, actions, reason="runs are immutable to their owner", **where)
68
69
70def policy(*rules):
71 return permissions.PermissionPolicy(access_mode="role_based", rules=tuple(rules))
72
73
74READ_OWN = permissions.PermissionRule.allow(
75 "registered", ["read"], collection="runs", row_filter={"owner_id": "$user_id"},
76 reason="a person reads their own runs")
77
78
79def ask(subject, action, active, record=MINE, collection="runs", **kwargs):
80 return permissions.check_permission(
81 subject, action, policy=active, collection=collection, record=record, **kwargs)
82
83
84# =============================================================================
85# The engine
86# =============================================================================
87
88@pytest.mark.parametrize("action", ["update", "delete"])
89def test_the_default_is_unchanged_an_owner_may_change_their_own_row_with_no_rule(action):
90 """The documented fallback, pinned so the opt-out below is seen to be
91 the only thing that takes it away."""
92 decision = ask(OWNER, action, policy(READ_OWN))
93 assert decision.allowed and decision.reason == "record owner"
94 assert not ask(STRANGER, action, policy(READ_OWN)).allowed
95
96
97@pytest.mark.parametrize("action", ["update", "delete"])
98def test_an_opt_out_refuses_the_owner_what_no_rule_grants(action):
99 decision = ask(OWNER, action, policy(READ_OWN, opt_out(collection="runs")))
100 assert not decision.allowed
101 assert (decision.code, decision.http_status) == ("forbidden", 403)
102 assert decision.reason == "runs are immutable to their owner"
103
104
105def test_an_opt_out_names_its_actions_and_leaves_the_rest_of_the_fallback():
106 active = policy(opt_out(collection="runs")) # no read rule at all
107 assert ask(OWNER, "read", active).reason == "record owner"
108 assert not ask(OWNER, "update", active).allowed
109 everything = policy(opt_out(actions=("*",), collection="runs"))
110 assert not ask(OWNER, "read", everything).allowed
111
112
113def test_an_explicit_grant_still_grants_what_the_opt_out_withholds():
114 """The difference from an ordinary deny, and the reason this is its own
115 thing: a deny would beat the grant. Packages that grant an owner update
116 on purpose keep working whatever opt-outs sit beside the grant."""
117 write_own = permissions.PermissionRule.allow(
118 "registered", ["update"], collection="runs",
119 row_filter={"owner_id": "$user_id", "status": "draft"}, reason="drafts are editable")
120 active = policy(READ_OWN, write_own, opt_out(collection="runs"))
121 draft = {**MINE, "status": "draft"}
122 assert ask(OWNER, "update", active, record=draft).reason == "drafts are editable"
123 assert not ask(OWNER, "update", active).allowed # settled: the filter says no
124 # ...and without the opt-out the fallback made that filter decorative.
125 assert ask(OWNER, "update", policy(READ_OWN, write_own)).reason == "record owner"
126
127
128def test_an_opt_out_is_not_a_deny_for_anybody_else():
129 support = permissions.PermissionRule.allow(
130 "role:support", ["update"], collection="runs", reason="support repairs runs")
131 active = policy(support, opt_out(collection="runs"))
132 helper = permissions.PermissionSubject(user_id="9", roles=("support",))
133 owner_in_support = permissions.PermissionSubject(user_id="7", roles=("support",))
134 assert ask(helper, "update", active).reason == "support repairs runs"
135 assert ask(owner_in_support, "update", active).reason == "support repairs runs"
136
137
138def test_an_admin_is_decided_before_the_opt_out():
139 for action in ("read", "update", "delete"):
140 assert ask(ADMIN, action, policy(opt_out(actions=("*",), collection="runs"))).allowed
141
142
143def test_an_opt_out_covers_only_the_resource_it_names():
144 active = policy(opt_out(collection="runs"))
145 assert ask(OWNER, "update", active, collection="notes").reason == "record owner"
146 everywhere = policy(opt_out()) # no collection: the whole policy
147 assert not ask(OWNER, "update", everywhere, collection="notes").allowed
148
149
150@pytest.mark.parametrize("key", permissions.OWNER_KEYS)
151def test_an_opt_out_covers_every_owner_key(key):
152 """A grant row names its grantee in `user_id`; that makes the grantee an
153 owner as far as the fallback is concerned."""
154 row = {"id": "g1", key: "7"}
155 assert ask(OWNER, "update", policy(), record=row).reason == "record owner"
156 assert not ask(OWNER, "update", policy(opt_out(collection="runs")), record=row).allowed
157
158
159def test_an_opt_out_with_a_row_filter_covers_the_rows_it_names():
160 settled = opt_out(collection="runs", row_filter={"status": "succeeded"})
161 assert not ask(OWNER, "update", policy(settled)).allowed
162 assert ask(OWNER, "update", policy(settled), record={**MINE, "status": "queued"}).allowed
163
164
165def test_an_opt_out_outside_its_time_window_does_nothing():
166 expired = opt_out(collection="runs", expires_at="2026-01-01T00:00:00Z")
167 now = datetime(2026, 11, 28, tzinfo=timezone.utc)
168 assert ask(OWNER, "update", policy(expired), now=now).reason == "record owner"
169
170
171def test_an_opt_out_covers_the_user_object_convention_too():
172 """`u_7_report` belongs to user 7 with no rule; an opt-out naming the
173 object is the "future stricter policy" the ownership docs anticipate."""
174 def source(active):
175 return permissions.check_permission(
176 OWNER, "source", policy=active, object_id="u_7_report")
177 assert source(policy()).reason == "object owner"
178 assert not source(policy(opt_out(actions=("source",), object_id="u_7_report"))).allowed
179
180
181def test_owner_fallback_is_not_a_principal_anyone_is():
182 """As an allow it would grant nothing and look like it granted
183 something, so it does not parse; as a deny it never matches a subject in
184 the deny pass (it is not about a subject)."""
185 with pytest.raises(ValueError, match="owner_fallback"):
186 permissions.rule_from_dict({"effect": "allow", "principal": "owner_fallback",
187 "actions": ["update"], "collection": "runs"})
188 parsed = permissions.rule_from_dict({"effect": "deny", "principal": "owner_fallback",
189 "actions": ["update"], "collection": "runs"})
190 assert permissions.rule_from_dict(permissions.rule_to_dict(parsed)) == parsed
191 write_all = permissions.PermissionRule.allow("registered", ["update"], collection="runs")
192 assert ask(STRANGER, "update", policy(write_all, opt_out(collection="runs"))).allowed
193 assert not permissions.principal_matches("owner_fallback", OWNER, policy(), record=MINE)
194
195
196def test_the_row_filter_planner_still_offers_a_superset():
197 """The planner is untouched: it still proposes the owner's rows, and the
198 engine -- the only authority on a returned row -- refuses them."""
199 active = policy(opt_out(actions=("read",), collection="runs"))
200 plan = permissions.plan_row_filter(OWNER, "read", policy=active, collection="runs")
201 assert not plan.all_rows and "owner_id" in plan.fields()
202 assert not ask(OWNER, "read", active).allowed
203
204
205# =============================================================================
206# The shipped packages
207# =============================================================================
208
209def _shipped():
210 rules, schemas = [], {}
211 for manifest_path in sorted(PACKAGES_ROOT.glob("*/dbbasic-package.json")):
212 manifest = json.loads(manifest_path.read_text())
213 for entry in manifest.get("permissions", []):
214 fragment = json.loads((manifest_path.parent / entry["path"]).read_text())
215 rules += [(manifest["id"], rule) for rule in fragment["rules"]]
216 for entry in manifest.get("schemas", []):
217 schemas[entry["collection"]] = (
218 manifest["id"], json.loads((manifest_path.parent / entry["path"]).read_text()))
219 return rules, schemas
220
221
222def _full_policy(rules):
223 return permissions.PermissionPolicy(
224 access_mode="role_based",
225 rules=tuple(permissions.rule_from_dict({**rule, "package": package})
226 for package, rule in rules))
227
228
229# Every collection whose package says, in its own rule or schema text, that
230# the people it belongs to do not change (or do not remove) its rows.
231OPTED_OUT = {
232 "agent_registry": ("app-agents", {"update", "delete"}),
233 "ai_usage": ("app-shell", {"update", "delete"}),
234 "attention_counts": ("app-nav", {"update", "delete"}),
235 "backorders": ("app-catalog", {"delete"}),
236 "stock_moves": ("app-catalog", {"update", "delete"}),
237 "payments": ("app-payments", {"update", "delete"}),
238 "refunds": ("app-payments", {"update", "delete"}),
239 "bank_lines": ("app-banking", {"delete"}),
240 "bank_statement_imports": ("app-banking", {"update", "delete"}),
241 "conversions": ("app-analytics", {"update", "delete"}),
242 "disputes": ("app-disputes", {"delete"}),
243 # Reason codes are cited by voids and corrections; whoever seeded one
244 # must not rename or delete it out from under them (retire: active false).
245 "correction_reasons": ("app-counter", {"update", "delete"}),
246 # A manager's approval is given once; the approver does not edit it.
247 "counter_approvals": ("app-counter", {"update", "delete"}),
248 # Goodwill given and a remake's links are facts, not drafts.
249 "goodwill": ("app-counter", {"update", "delete"}),
250 "remakes": ("app-counter", {"update", "delete"}),
251 "waste_logs": ("app-counter", {"update", "delete"}),
252 "expense_categories": ("app-finance", {"update", "delete"}),
253 "fringe_benefits": ("app-finance", {"read", "update", "delete"}),
254 "mileage_logs": ("app-finance", {"delete"}),
255 "mileage_rates": ("app-finance", {"update", "delete"}),
256 "vehicles": ("app-finance", {"delete"}),
257 # The books are the business's, kept by role:finance and role:owner
258 # (decision 5, 2026-11-30); a composed journal's row owner is often the
259 # customer whose payment it books.
260 "fin_accounts": ("app-finance", {"read", "update", "delete"}),
261 "fin_journals": ("app-finance", {"read", "update", "delete"}),
262 "fin_journal_lines": ("app-finance", {"read", "update", "delete"}),
263 "fin_recurring": ("app-finance", {"read", "update", "delete"}),
264 "fin_closed_periods": ("app-finance", {"read", "update", "delete"}),
265 "loss_events": ("app-assets", {"delete"}),
266 "invoice_lines": ("app-invoices", {"delete"}),
267 "invoices": ("app-invoices", {"delete"}),
268 # Applying a credit moves money on an invoice: staff's, not its owner's.
269 "invoice_credits": ("app-invoices", {"update", "delete"}),
270 # A payment the supplier has been told about (remitted) is a fact both
271 # companies hold; the grant to its owner is filtered on remitted=false.
272 "supplier_payments": ("app-bills", {"update", "delete"}),
273 # A received document and a sent one (with the partner's receipt) are
274 # evidence: their owner reads them; only the exchange writes them.
275 "exchange_inbox": ("app-exchange", {"update", "delete"}),
276 "exchange_outbox": ("app-exchange", {"update", "delete"}),
277 "page_views": ("app-analytics", {"update", "delete"}),
278 "pickup_slots": ("app-pickup", {"update", "delete"}),
279 "project_access": ("app-projects", {"update"}),
280 "promotion_redemptions": ("app-promotions", {"update", "delete"}),
281 "promotions": ("app-promotions", {"update", "delete"}),
282 "rates": ("app-finance", {"update", "delete"}),
283 "receipt_lines": ("app-receiving", {"delete"}),
284 "receipts": ("app-receiving", {"delete"}),
285 "record_shares": ("app-share", {"update", "delete"}),
286 "reorder_suggestions": ("app-catalog", {"delete"}),
287 "return_authorizations": ("app-returns", {"delete"}),
288 "scheduler_runs": ("system-dashboard", {"update", "delete"}),
289 "sent_documents": ("app-documents", {"delete"}),
290 "shipment_lines": ("app-shipping", {"delete"}),
291 "shipments": ("app-shipping", {"delete"}),
292 "subscriptions": ("app-billing", {"delete"}),
293 "template_runs": ("app-runner", {"update", "delete"}),
294 "usage_events": ("app-billing", {"update", "delete"}),
295 "usage_summaries": ("app-billing", {"update", "delete"}),
296 "value_account_counts": ("app-banking", {"update", "delete"}),
297 "wallet_entries": ("app-billing", {"update", "delete"}),
298 "wallets": ("app-billing", {"delete"}),
299}
300
301# Collections where the fallback is still the only thing granting an owner
302# update or delete, and the package's text does not say whether that is
303# meant. Left as they are, listed so that the list is a decision somebody
304# made rather than an accident: (collection, action, owner key).
305UNDECIDED = {
306 # Role-managed registries: the "owner" is whichever manager created the row.
307 ("attention_sources", "update", "owner_id"), ("attention_sources", "delete", "owner_id"),
308 ("billing_plans", "update", "owner_id"), ("billing_plans", "delete", "owner_id"),
309 ("nav_entries", "update", "owner_id"), ("nav_entries", "delete", "owner_id"),
310 ("rate_cards", "update", "owner_id"), ("rate_cards", "delete", "owner_id"),
311 # No rules shipped at all; app-shop writes these through its own actions.
312 ("cart_items", "update", "owner_id"), ("cart_items", "delete", "owner_id"),
313 ("carts", "update", "owner_id"), ("carts", "delete", "owner_id"),
314 # The rule grants create/read/update and is silent about delete.
315 ("expenses", "delete", "owner_id"), ("scans", "delete", "owner_id"),
316 # A post may be created and read; whether its author may edit or retract it is unsaid.
317 ("feed_posts", "update", "owner_id"), ("feed_posts", "delete", "owner_id"),
318 ("shell_commands", "update", "owner_id"),
319 # A grantee removing their own grant (leaving a project). The one case the
320 # record API serves on a stock install: the delete rule for project owners
321 # lets every signed-in user past the collection-level question.
322 ("project_access", "delete", "user_id"),
323}
324
325
326def _fallback_only_owner_writes(rules, schemas):
327 """(collection, action, owner key) wherever a plain signed-in user gets
328 update or delete on a row they own from the fallback and from no rule."""
329 active = _full_policy(rules)
330 me = permissions.PermissionSubject(user_id="u1")
331 found = set()
332 for collection, (_package, schema) in schemas.items():
333 fields = [field.get("name") for field in schema.get("fields", [])]
334 for key in (k for k in permissions.OWNER_KEYS if k in fields):
335 row = {name: "__matches_no_filter__" for name in fields}
336 row.update({k: "someone-else" for k in permissions.OWNER_KEYS if k in fields})
337 row[key] = "u1"
338 for action in ("update", "delete"):
339 decision = permissions.check_permission(
340 me, action, policy=active, collection=collection, record=row)
341 if decision.allowed and decision.reason == "record owner":
342 found.add((collection, action, key))
343 return found
344
345
346def test_the_shipped_opt_outs_are_exactly_the_audited_list():
347 rules, schemas = _shipped()
348 shipped = {}
349 for package, rule in rules:
350 if rule["principal"] != permissions.OWNER_FALLBACK:
351 continue
352 assert rule["effect"] == "deny" and rule.get("reason"), (package, rule)
353 assert schemas[rule["collection"]][0] == package, (
354 f"{package} opts out a collection it does not ship: {rule['collection']}")
355 assert rule["collection"] not in shipped, f"two opt-outs for {rule['collection']}"
356 shipped[rule["collection"]] = (package, set(rule["actions"]))
357 assert shipped == OPTED_OUT
358
359
360def test_no_shipped_opt_out_shadows_a_grant_the_same_package_makes():
361 """An opt-out beside a grant for the same action would read as if the
362 grant were withdrawn. It would not be (the grant wins), which is exactly
363 why it must not be there to mislead.
364
365 A grant with a row filter is the exception, and the reason the opt-out
366 exists (test_an_explicit_grant_still_grants_what_the_opt_out_withholds):
367 mileage_logs lets a driver delete their own DRAFT trips, and without the
368 opt-out the fallback handed them every other trip of theirs too, the
369 filter decorative. Beside a filtered grant the opt-out withdraws exactly
370 the rows the filter leaves out, which is what it reads as."""
371 rules, _schemas = _shipped()
372 for collection, (package, actions) in OPTED_OUT.items():
373 for other_package, rule in rules:
374 if (rule.get("collection") == collection and rule["effect"] == "allow"
375 and rule["principal"] in ("registered", "owner", "public")
376 and not rule.get("row_filter", {}).keys() - {"owner_id", "user_id", "created_by"}):
377 assert not actions & set(rule["actions"]), (collection, other_package, rule)
378
379
380def test_every_owner_write_the_fallback_alone_grants_is_a_recorded_decision():
381 """A tripwire. If this fails you added a collection whose rows carry an
382 owner key, or took update/delete out of a grant, and the owner fallback
383 now grants the owner that action with no rule saying so (in-object
384 checks through object_access see it; so does the record API once any
385 other rule for the action exists). Decide: ship an `owner_fallback`
386 deny for it (and add it to OPTED_OUT), grant it explicitly, or add it to
387 UNDECIDED with a reason."""
388 rules, schemas = _shipped()
389 assert _fallback_only_owner_writes(rules, schemas) == UNDECIDED
390
391
392@pytest.mark.parametrize("collection", sorted(OPTED_OUT))
393def test_on_a_full_install_the_owner_of_an_opted_out_row_cannot_change_it(collection):
394 rules, schemas = _shipped()
395 active = _full_policy(rules)
396 _package, actions = OPTED_OUT[collection]
397 fields = [field.get("name") for field in schemas[collection][1].get("fields", [])]
398 me = permissions.PermissionSubject(user_id="u1")
399 boss = permissions.PermissionSubject(user_id="boss", roles=("admin",))
400 for key in (k for k in permissions.OWNER_KEYS if k in fields):
401 row = {name: "__matches_no_filter__" for name in fields}
402 row[key] = "u1"
403 for action in sorted(actions):
404 assert not permissions.check_permission(
405 me, action, policy=active, collection=collection, record=row).allowed
406 assert permissions.check_permission(
407 boss, action, policy=active, collection=collection, record=row).allowed
408
409
410# =============================================================================
411# Through the real HTTP API, enforcement on, app-runner really installed
412# =============================================================================
413
414class Site:
415 def __init__(self, tmp_path, monkeypatch, packages):
416 self.data = tmp_path / "data"
417 self.root = tmp_path / "objects"
418 self.root.mkdir(parents=True, exist_ok=True)
419 monkeypatch.setenv("DBBASIC_DATA_DIR", str(self.data))
420 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(self.root))
421 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", ADMIN_TOKEN)
422 monkeypatch.setenv("DBBASIC_ENABLE_PERMISSION_ENFORCEMENT", "true")
423 for name in ("DBBASIC_OBJECT_TIMEOUT_SECONDS", "DBBASIC_WORKER_POOL_SIZE",
424 "DBBASIC_ROW_FILTER_INDEX", "DBBASIC_TRUSTED_IN_PROCESS_OBJECTS",
425 "DBBASIC_ALLOW_UNREADY_PERMISSION_ENFORCEMENT",
426 "DBBASIC_ENABLE_SESSION_ADMIN_GATES"):
427 monkeypatch.delenv(name, raising=False)
428 for package in self._closure(packages):
429 object_packages.install_package(
430 package, root=PACKAGES_ROOT, base_dir=self.data, object_roots=[self.root])
431 self.admin = [("authorization", f"Token {ADMIN_TOKEN}")]
432
433 @staticmethod
434 def _closure(names):
435 ordered = []
436
437 def visit(name):
438 if name in ordered:
439 return
440 manifest = json.loads((PACKAGES_ROOT / name / "dbbasic-package.json").read_text())
441 for dep in manifest.get("dependencies", []):
442 visit(dep if isinstance(dep, str) else dep["id"])
443 ordered.append(name)
444
445 for name in names:
446 visit(name)
447 return ordered
448
449 def user(self, user_id, roles=()):
450 object_identity.create_user({"user_id": user_id, "roles": list(roles)}, base_dir=self.data)
451 session = object_identity.create_session({"user_id": user_id}, base_dir=self.data)
452 return [("authorization", f"Bearer {session['token']}")]
453
454 def create(self, collection, record):
455 return object_records.create_collection_record(
456 collection, record, base_dir=self.data, preserve_read_only=True)
457
458 def row(self, collection, record_id):
459 return object_records.get_collection_record(collection, record_id, base_dir=self.data)
460
461 def add_rule(self, rule):
462 payload = permissions.policy_to_dict(object_permission_store.load_policy(self.data))
463 payload["rules"].append(rule)
464 object_permission_store.replace_policy(payload, self.data)
465
466 def drop_opt_outs(self, collection):
467 """The policy as it was before the opt-out shipped."""
468 payload = permissions.policy_to_dict(object_permission_store.load_policy(self.data))
469 payload["rules"] = [rule for rule in payload["rules"]
470 if not (rule["principal"] == permissions.OWNER_FALLBACK
471 and rule.get("collection") == collection)]
472 object_permission_store.replace_policy(payload, self.data)
473
474 def call(self, path, method="GET", payload=None, headers=()):
475 body = json.dumps(payload).encode("utf-8") if payload is not None else b""
476 scope_headers = [(b"accept", b"application/json"), (b"content-type", b"application/json")]
477 scope_headers += [(k.encode("latin-1"), v.encode("latin-1")) for k, v in headers]
478 messages = []
479
480 async def receive():
481 return {"type": "http.request", "body": body, "more_body": False}
482
483 async def send(message):
484 messages.append(message)
485
486 scope = {"type": "http", "method": method, "path": path, "query_string": b"",
487 "headers": scope_headers, "client": ("127.0.0.1", 12345)}
488 asyncio.run(object_server.app(scope, receive, send))
489 start = next(m for m in messages if m["type"] == "http.response.start")
490 raw = b"".join(m.get("body", b"") for m in messages if m["type"] == "http.response.body")
491 return start["status"], json.loads(raw.decode("utf-8"))
492
493
494RUN = "/collections/template_runs/records/run-1"
495
496
497@pytest.fixture
498def runner(tmp_path, monkeypatch):
499 site = Site(tmp_path, monkeypatch, ["app-runner"])
500 site.alice = site.user("alice")
501 site.create("templates", {"id": "t1", "name": "T", "body": "b", "handler": "echo",
502 "owner_id": "alice"})
503 site.create("template_runs", {
504 "id": "run-1", "template_id": "t1", "template_name": "T", "handler": "echo",
505 "status": "succeeded", "price_cents": "500", "owner_id": "alice", "output": "ORIGINAL"})
506 status, flags = site.call("/permissions/status", headers=site.admin)
507 assert status == 200 and flags["permissions"]["enforcement_enabled"], flags
508 return site
509
510
511SUPPORT_RULE = {"effect": "allow", "principal": "role:support", "actions": ["update", "delete"],
512 "collection": "template_runs", "row_filter": {"status": "needs_review"},
513 "reason": "support settles the runs that are waiting on a person"}
514
515
516def test_a_runs_owner_cannot_update_or_delete_it_through_the_api(runner):
517 """The reported case. It is refused on a stock install with or without
518 the opt-out, by the collection-level question the record API asks before
519 it looks the record up -- so this pins the answer, not the fix."""
520 status, body = runner.call(RUN, "PUT", {"output": "FORGED"}, runner.alice)
521 assert status == 403, body
522 status, body = runner.call(RUN, "DELETE", headers=runner.alice)
523 assert status == 403, body
524 assert runner.row("template_runs", "run-1")["output"] == "ORIGINAL"
525
526 runner.drop_opt_outs("template_runs")
527 assert runner.call(RUN, "PUT", {"output": "FORGED"}, runner.alice)[0] == 403
528 assert runner.call(RUN, "DELETE", headers=runner.alice)[0] == 403
529 # The owner still reads their run.
530 status, body = runner.call(RUN, headers=runner.alice)
531 assert status == 200 and body["record"]["output"] == "ORIGINAL"
532
533
534def test_another_rule_for_the_action_does_not_reopen_the_owners_own_rows(runner):
535 """Where the fallback did reach the API: one allow rule for update lets
536 its role through the collection-level question, and for a row the rule's
537 filter does not cover the record-level check fell through to "record
538 owner". A support user could rewrite the output and price of their own
539 settled run, and delete it."""
540 runner.add_rule(SUPPORT_RULE)
541 owner_in_support = runner.user("sam", roles=["support"])
542 runner.create("template_runs", {
543 "id": "run-sam", "template_id": "t1", "template_name": "T", "handler": "echo",
544 "status": "succeeded", "price_cents": "500", "owner_id": "sam", "output": "ORIGINAL"})
545 path = "/collections/template_runs/records/run-sam"
546
547 status, body = runner.call(path, "PUT", {"output": "FORGED", "price_cents": "0"},
548 owner_in_support)
549 assert status == 403, body
550 status, body = runner.call(path, "DELETE", headers=owner_in_support)
551 assert status == 403, body
552 assert runner.row("template_runs", "run-sam")["output"] == "ORIGINAL"
553 assert runner.row("template_runs", "run-sam")["price_cents"] == "500"
554
555
556def test_without_the_opt_out_that_same_request_went_through(runner):
557 """The control for the test above: same box, the opt-out taken back out.
558 Neither a read-only field nor the status transition guard stops it --
559 output and price_cents are ordinary fields and status is not touched."""
560 runner.add_rule(SUPPORT_RULE)
561 runner.drop_opt_outs("template_runs")
562 owner_in_support = runner.user("sam", roles=["support"])
563 runner.create("template_runs", {
564 "id": "run-sam", "template_id": "t1", "template_name": "T", "handler": "echo",
565 "status": "succeeded", "price_cents": "500", "owner_id": "sam", "output": "ORIGINAL"})
566 path = "/collections/template_runs/records/run-sam"
567
568 status, body = runner.call(path, "PUT", {"output": "FORGED", "price_cents": "0"},
569 owner_in_support)
570 assert status == 200, body
571 assert runner.row("template_runs", "run-sam")["output"] == "FORGED"
572 assert runner.call(path, "DELETE", headers=owner_in_support)[0] == 200
573
574
575def test_the_explicit_grant_beside_the_opt_out_still_works_through_the_api(runner):
576 """The legitimate path the support rule was written for."""
577 runner.add_rule(SUPPORT_RULE)
578 support = runner.user("sam", roles=["support"])
579 runner.create("template_runs", {
580 "id": "run-review", "template_id": "t1", "template_name": "T", "handler": "echo",
581 "status": "needs_review", "price_cents": "500", "owner_id": "alice"})
582 status, body = runner.call("/collections/template_runs/records/run-review", "PUT",
583 {"error": "checked with the provider"}, support)
584 assert status == 200, body
585 assert runner.row("template_runs", "run-review")["error"] == "checked with the provider"
586
587
588def test_an_admin_and_an_in_process_writer_still_change_a_run(runner):
589 status, body = runner.call(RUN, "PUT", {"error": "operator note"}, runner.admin)
590 assert status == 200, body
591 boss = runner.user("boss", roles=["admin"])
592 status, body = runner.call(RUN, "PUT", {"error": "second note"}, boss)
593 assert status == 200, body
594 # What the runner and the sweeper do: storage, no permission question.
595 object_records.update_collection_record(
596 "template_runs", "run-1", {"output": "REWRITTEN BY THE RUNNER"}, base_dir=runner.data)
597 assert runner.row("template_runs", "run-1")["output"] == "REWRITTEN BY THE RUNNER"
598 assert runner.call(RUN, "DELETE", headers=runner.admin)[0] == 200
599
600
601def test_the_owner_still_settles_their_own_needs_review_run_through_the_action(runner):
602 """The owner's one legitimate way to move a run: action_resolve_run asks
603 the engine whether they may READ it, then writes in process."""
604 runner.create("wallets", {"id": "w-alice", "owner_id": "alice", "kind": "balance"})
605 runner.create("template_runs", {
606 "id": "run-review", "template_id": "t1", "template_name": "T", "handler": "echo",
607 "status": "needs_review", "price_cents": "500", "wallet_id": "w-alice",
608 "owner_id": "alice"})
609 status, body = runner.call("/objects/action_resolve_run", "POST",
610 {"run_id": "run-review", "decision": "charge"}, runner.alice)
611 assert status == 200, body
612 assert runner.row("template_runs", "run-review")["status"] == "succeeded"
613
614
615def test_an_object_asking_the_engine_gets_the_same_refusal(runner):
616 """object_access has no collection-level first question, so before the
617 opt-out it told any page or action that the owner may update and delete
618 their run -- the answer hooks and actions are now being written to
619 trust."""
620 run = runner.row("template_runs", "run-1")
621 owner = object_access.Access({"user_id": "alice"}, base_dir=runner.data)
622 assert owner.can("read", "template_runs", run)
623 assert not owner.can("update", "template_runs", run)
624 assert not owner.can("delete", "template_runs", run)
625 assert owner.get("template_runs", "run-1", action="update") is None
626 boss = object_access.Access({"user_id": "ops", "roles": ["admin"]}, base_dir=runner.data)
627 assert boss.can("update", "template_runs", run) and boss.can("delete", "template_runs", run)
628
629 runner.drop_opt_outs("template_runs")
630 before = object_access.Access({"user_id": "alice"}, base_dir=runner.data)
631 assert before.can("update", "template_runs", run) and before.can("delete", "template_runs", run)
632
633
634def test_a_wallet_entry_is_not_its_owners_to_change(tmp_path, monkeypatch):
635 """Money never mutates (docs/logic-decisions.md #3): the ledger's own
636 rule says "No create/update/delete", and the engine now agrees."""
637 site = Site(tmp_path, monkeypatch, ["app-billing"])
638 alice = site.user("alice")
639 site.create("wallets", {"id": "w1", "owner_id": "alice", "kind": "balance"})
640 entry = site.create("wallet_entries", {
641 "id": "e1", "wallet_id": "w1", "amount_minor": "-500", "kind": "debit",
642 "owner_id": "alice"})
643 path = "/collections/wallet_entries/records/e1"
644 assert site.call(path, headers=alice)[0] == 200
645 assert site.call(path, "PUT", {"amount_minor": "500"}, alice)[0] == 403
646 assert site.call(path, "DELETE", headers=alice)[0] == 403
647 owner = object_access.Access({"user_id": "alice"}, base_dir=site.data)
648 assert owner.can("read", "wallet_entries", entry)
649 assert not owner.can("update", "wallet_entries", entry)
650 assert not owner.can("delete", "wallet_entries", entry)
651 assert not owner.can("delete", "wallets", site.row("wallets", "w1"))
652 # The owner's explicit grant on the wallet itself is untouched.
653 assert owner.can("update", "wallets", site.row("wallets", "w1"))
654 assert site.row("wallet_entries", "e1")["amount_minor"] == "-500"
655
656
657def test_a_grantee_cannot_raise_their_own_project_grant(tmp_path, monkeypatch):
658 """project_access names the grantee in `user_id`, which made the grantee
659 the row's owner: read -> write on their own grant was one update away
660 from anything that asked the engine."""
661 site = Site(tmp_path, monkeypatch, ["app-projects"])
662 site.user("bob")
663 site.create("projects", {"id": "p1", "name": "P", "owner_id": "alice"})
664 grant = site.create("project_access", {
665 "id": "g1", "project_id": "p1", "user_id": "bob", "permission": "read"})
666 grantee = object_access.Access({"user_id": "bob"}, base_dir=site.data)
667 assert grantee.can("read", "project_access", grant)
668 assert not grantee.can("update", "project_access", grant)
669 site.drop_opt_outs("project_access")
670 assert object_access.Access({"user_id": "bob"}, base_dir=site.data).can(
671 "update", "project_access", grant)