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_relation_requires_collections.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_relation_requires_collections.py · 13.1 KB · 311 lines
1"""Every shipped pointer that declares `relation.requires`, probed over HTTP.
2
3The refund hole (tests/test_relation_requires.py) was one instance of a shape
4every owner-scoped package shipped: "registered users create rows whose
5owner_id is their own", with nothing asking about the row the new one points
6at. A line on somebody's order, a stock move on somebody's product, a journal
7line in somebody's books, a message in somebody's thread, a dispute (and so a
8refund or a credit) about somebody's payment -- each child was the writer's and
9acted on a parent that was not.
10
11For each collection, through the real ASGI app with enforcement on, as a
12registered non-admin who owns nothing involved: mallory writes a complete,
13otherwise valid row of her own pointing at a parent ann owns, and is refused by
14the check (400 exactly like a missing record when she cannot see the parent,
15403 naming the field when she can see it but may not act on it). The same
16write by ann, pointing at her own parent, is not refused by the check. Where
17the shipped rules let a registered user update the row, re-pointing her own
18row at ann's parent is refused too.
19
20A target every registered user may read (a public forum topic, a shared
21denomination) with `requires: read` is where the check is meant to let mallory
22through; those cases assert exactly that.
23
24Rows are synthesized from each schema (required fields filled by type; parents
25written in-process, owned by whoever needs them) so a field added to a schema
26does not need this file edited. OVERRIDES holds what a type cannot guess.
27"""
28
29from __future__ import annotations
30
31import json
32from pathlib import Path
33
34import pytest
35
36import object_field_permissions
37import object_ids
38import object_permissions
39import object_records
40from scripts.try_package import Sandbox
41
42ROOT = Path(__file__).resolve().parents[1]
43PACKAGES = ROOT / "packages"
44
45# Values a field's type cannot supply: money with a ceiling, a quantity a gate
46# measures, a state a hook insists on at create.
47OVERRIDES = {
48 "invoices": {"total_cents": "1000000", "status": "sent"},
49 "orders": {"status": "confirmed"},
50 "payments": {"amount_cents": "100"},
51 "supplier_payments": {"currency": "EUR"},
52 "disputes": {"status": "open"},
53 "return_authorizations": {"status": "requested"},
54 "time_logs": {"status": "draft"},
55 "expenses": {"status": "draft"},
56 "fin_journals": {"status": "draft"},
57 # Long closed, so the journals the other probes write are in an open period.
58 "fin_closed_periods": {"start_date": "2001-01-01", "end_date": "2001-01-31"},
59 "receipt_lines": {"quantity_received": "1"},
60 # Work and disposals are recorded against an asset in service (hook_assets).
61 "fixed_assets": {"status": "in_service", "placed_in_service_on": "2026-01-15",
62 "book_life_months": "60"},
63 # A sale names its evidence (required_when); the probe date is in the past.
64 "asset_disposals": {"evidence_refs": "probe bill of sale"},
65}
66
67
68def _schemas():
69 found = {}
70 for path in sorted(PACKAGES.glob("*/schemas/*.json")):
71 schema = json.loads(path.read_text())
72 if isinstance(schema, dict) and schema.get("name"):
73 found[schema["name"]] = (path.parts[-3], schema)
74 return found
75
76
77SCHEMAS = _schemas()
78
79
80def _rules():
81 rules = []
82 for path in sorted(PACKAGES.glob("*/permissions/rules.json")):
83 rules.extend(json.loads(path.read_text()).get("rules", []))
84 return rules
85
86
87RULES = _rules()
88
89
90def _registered_may(action, collection):
91 return any(rule.get("effect") == "allow" and rule.get("collection") == collection
92 and rule.get("principal") == "registered"
93 and (action in rule.get("actions", []) or "*" in rule.get("actions", []))
94 for rule in RULES)
95
96
97def _requirements():
98 found = []
99 for collection, (_package, schema) in SCHEMAS.items():
100 for field in schema.get("fields", []):
101 relation = field.get("relation") if isinstance(field, dict) else None
102 if isinstance(relation, dict) and relation.get("requires"):
103 found.append((collection, field["name"], relation["collection"], relation["requires"]))
104 return found
105
106
107REQUIREMENTS = _requirements()
108PROBED = sorted({c for c, *_ in REQUIREMENTS
109 if _registered_may("create", c) or _registered_may("update", c)})
110
111
112def _target(field):
113 relation = field.get("relation")
114 if isinstance(relation, str):
115 return relation
116 if isinstance(relation, dict):
117 return relation.get("collection")
118 return None
119
120
121def _value(field):
122 kind = str(field.get("type") or "text").lower()
123 validation = field.get("validation") or {}
124 if field.get("enum"):
125 return str(field["enum"][0])
126 if kind in ("integer", "int"):
127 return str(max(1, int(validation.get("min", 1))))
128 if kind in ("number", "float", "currency"):
129 return "1"
130 if kind == "date":
131 return "2026-11-02"
132 if kind in ("datetime", "timestamp"):
133 return "2026-11-02T10:00:00Z"
134 if kind in ("boolean", "bool"):
135 return "false"
136 # Distinct per row, so a unique key (bank_lines' line hash) never makes
137 # one probe refuse the next.
138 return f"probe {object_ids.new_uuid4()[:8]}"
139
140
141# Collections whose `unique` key is their parent pointer (an asset is
142# disposed of once; one tax figure per asset and year).
143ONE_PER_PARENT = {"asset_disposals", "asset_tax_entries"}
144
145
146def make(box, owner, collection, cache, **given):
147 """A valid row of `collection` owned by `owner`, written in-process (a
148 trusted writer: no hook, every schema rule and locked check). Parents
149 its required pointers need are made the same way, for the same owner."""
150 _package, schema = SCHEMAS[collection]
151 record = {"id": object_ids.new_uuid4()}
152 # One row per parent (unique): each made row gets parents of its own.
153 parents = {} if collection in ONE_PER_PARENT else cache
154 for field in schema.get("fields", []):
155 name = field["name"]
156 if name in given or name == "id" or field.get("type") == "computed" or field.get("read_only"):
157 continue
158 if name in ("owner_id", "user_id", "created_by"):
159 record[name] = owner
160 continue
161 target = _target(field)
162 if target:
163 if field.get("required"):
164 record[name] = parent(box, owner, target, parents)
165 continue
166 if field.get("required"):
167 record[name] = _value(field)
168 record.update(OVERRIDES.get(collection, {}))
169 record.update(given)
170 if collection == "refunds":
171 # Stamped from the payment by hook_refunds on the API path, which an
172 # in-process write does not run; LOCKED_CHECK insists on it.
173 record["invoice_id"] = object_records.get_collection_record(
174 "payments", record["payment_id"], base_dir=box.data_dir)["invoice_id"]
175 return object_records.create_collection_record(collection, record, base_dir=box.data_dir)["id"]
176
177
178def parent(box, owner, collection, cache):
179 key = (owner, collection)
180 if key not in cache:
181 cache[key] = make(box, owner, collection, cache)
182 return cache[key]
183
184
185def registered_may_write(field, owner="ann"):
186 """Whether the field's schema permissions let a plain signed-in owner of
187 the row write it. A pointer they may not write at all (invoice_lines.
188 invoice_id since app-invoices 0.15.0) has no relation check to probe:
189 the field permission refuses it first, for ann as much as for mallory."""
190 access = object_field_permissions.field_access(
191 field, subject=object_permissions.PermissionSubject(user_id=owner),
192 policy=object_permissions.PermissionPolicy(access_mode="role_based"),
193 record={"owner_id": owner})
194 return access in (None, object_field_permissions.EDIT)
195
196
197def _field(collection, name):
198 return next(f for f in SCHEMAS[collection][1].get("fields", []) if f.get("name") == name)
199
200
201def payload(box, owner, collection, field_name, parent_id, cache):
202 """A complete HTTP body for `collection`: required fields filled, other
203 required pointers at the writer's own parents, `field_name` at parent_id."""
204 _package, schema = SCHEMAS[collection]
205 owner_field = next((f for f in schema.get("fields", []) if f.get("name") == "owner_id"), {})
206 # The server stamps owner_id from the session; a schema that makes it
207 # server-only (thread_comments) refuses a client that sends it.
208 body = {} if owner_field.get("permissions") else {"owner_id": owner}
209 for field in schema.get("fields", []):
210 name = field["name"]
211 if name in ("id", "owner_id") or field.get("type") == "computed" or field.get("read_only"):
212 continue
213 target = _target(field)
214 if name == field_name:
215 body[name] = parent_id
216 elif target:
217 if field.get("required"):
218 body[name] = parent(box, owner, target, cache)
219 elif field.get("required"):
220 body[name] = _value(field)
221 body.update(OVERRIDES.get(collection, {}))
222 # Only what a signed-in owner may write: a staff-only field (an
223 # invoice's status and total since app-invoices 0.15.0) would be refused
224 # for its own sake and hide the pointer check this probes.
225 body = {name: value for name, value in body.items()
226 if name == "owner_id" or name not in {f["name"] for f in schema.get("fields", [])}
227 or registered_may_write(_field(collection, name), owner)}
228 body[field_name] = parent_id
229 return body
230
231
232def refused_by_check(status, body, field_name, target, parent_id):
233 if not isinstance(body, dict):
234 return False
235 if status == 400 and body.get("error") == (
236 f"Record field '{field_name}' references a missing record: {target}/{parent_id}"):
237 return True
238 return status == 403 and body.get("code") == "forbidden" and body.get("field") == field_name
239
240
241@pytest.fixture(scope="module")
242def box():
243 packages = sorted({SCHEMAS[c][0] for c in PROBED}
244 | {SCHEMAS[t][0] for c, _f, t, _a in REQUIREMENTS if c in PROBED})
245 with Sandbox(packages) as sandbox:
246 sandbox.add_user("ann")
247 sandbox.add_user("mallory")
248 yield sandbox
249
250
251@pytest.fixture
252def live(box, monkeypatch):
253 # conftest points DBBASIC_DATA_DIR at a fresh directory per test; this
254 # module shares one installed sandbox, so point it back.
255 monkeypatch.setenv("DBBASIC_DATA_DIR", str(box.data_dir))
256 return box
257
258
259def probe(box, collection):
260 """[(field, target, action, mallory status/body, ann status/body,
261 mallory re-point status/body or None, mallory may read the parent)]"""
262 cache = {}
263 results = []
264 for coll, field_name, target, action in REQUIREMENTS:
265 if coll != collection:
266 continue
267 if not registered_may_write(_field(coll, field_name)):
268 continue
269 anns = parent(box, "ann", target, cache)
270 readable = box.call("mallory", "GET", f"/collections/{target}/records/{anns}")[0] == 200
271 path = f"/collections/{collection}/records"
272 mallory = ann = repoint = None
273 if _registered_may("create", collection):
274 mallory = box.call("mallory", "POST", path,
275 payload(box, "mallory", collection, field_name, anns, cache))
276 ann = box.call("ann", "POST", path, payload(box, "ann", collection, field_name, anns, cache))
277 if _registered_may("update", collection):
278 own = make(box, "mallory", collection, cache)
279 repoint = box.call("mallory", "PUT", f"{path}/{own}", {field_name: anns})
280 results.append((field_name, target, action, mallory, ann, repoint, readable, anns))
281 return results
282
283
284@pytest.mark.parametrize("collection", PROBED)
285def test_a_registered_user_cannot_point_a_row_at_a_record_she_may_not_act_on(live, collection):
286 for field_name, target, action, mallory, ann, repoint, readable, anns in probe(live, collection):
287 where = f"{collection}.{field_name} -> {target} ({action})"
288 let_through = readable and action == "read"
289 for answer in (mallory, repoint):
290 if answer is None:
291 continue
292 refused = refused_by_check(*answer, field_name, target, anns)
293 assert refused != let_through, (where, answer)
294 # ann pointing at her OWN parent is let through -- where a signed-in
295 # owner may act on that parent at all. A payment is read-only to its
296 # owner since app-payments 0.8.0 (the owner is usually the customer
297 # who paid), so a dispute naming one is staff's to file.
298 if ann is not None and _registered_may(action, target):
299 assert not refused_by_check(*ann, field_name, target, anns), (where, ann)
300
301
302def test_every_collection_with_a_requirement_is_probed():
303 """A requirement on a collection no registered user may write is real
304 (an operator may grant one) but has nothing to probe here; the list is
305 the shipped ones a registered user can reach."""
306 assert "disputes" in PROBED and "stock_moves" in PROBED
307 # Refunds and payments are staff-only since app-payments 0.7.0 / 0.8.0 (no
308 # registered create or update), so their pointer checks are pinned in
309 # tests/test_relation_requires.py with a role granted create, rather than
310 # probed here.
311 assert "refunds" not in PROBED and "payments" not in PROBED