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_package_permission_retraction.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_package_permission_retraction.py · 32.2 KB · 704 lines
1"""A package upgrade brings the installed policy in line with what the package
2now ships -- without touching a rule the operator wrote or edited.
3
4Before this, `object_packages._merge_permission_rules` only ever APPENDED. A
5package that deleted a rule (the 14 stale execute grants) or tightened one
6(template_runs and thread_comments reads gained a row filter, which is a
7different rule) fixed fresh installs only: a box that already had the package
8kept the old, wider rule beside the new one, and an allow rule that is still
9there still allows.
10
11Three sources of truth, in the order they are trusted:
12
131. the package's recorded baseline (`data/package_baselines/<id>.json`,
14 `permissions`): the rules it shipped at the last install. A rule in the
15 baseline that the package no longer ships is retired automatically;
162. the fragment's explicit `retracted` list: rules an earlier version
17 shipped. This is what reaches a box installed before baselines recorded
18 permissions, where (1) has nothing to compare against;
193. the `package` tag on the live rule. Only a rule tagged as THIS package's
20 and identical (everything but `reason`) to a retired one is removed. A
21 rule the operator edited no longer matches; a rule the operator wrote has
22 no tag. Both are kept and reported.
23"""
24
25from __future__ import annotations
26
27import asyncio
28import json
29import shutil
30import subprocess
31from pathlib import Path
32
33import pytest
34
35import object_identity
36import object_package_baselines
37import object_package_changes
38import object_packages
39import object_permission_store
40import object_permissions
41import object_records
42import object_server
43
44ROOT = Path(__file__).resolve().parents[1]
45PACKAGES_ROOT = ROOT / "packages"
46ADMIN_TOKEN = "unit-test-only-admin-token"
47
48
49# --- a synthetic package -----------------------------------------------------
50
51READ_ALL = {"effect": "allow", "principal": "registered", "actions": ["read"],
52 "collection": "things", "reason": "everybody reads everything"}
53READ_OWN = {"effect": "allow", "principal": "registered", "actions": ["read"],
54 "collection": "things", "row_filter": {"owner_id": "$user_id"},
55 "reason": "a person reads their own things"}
56PAGE = {"effect": "allow", "principal": "public", "actions": ["execute"],
57 "object_id": "site_things", "reason": "the things page is public"}
58WRITE_OWN = {"effect": "allow", "principal": "registered",
59 "actions": ["create", "update", "delete"], "collection": "things",
60 "row_filter": {"owner_id": "$user_id"}, "reason": "a person manages their own things"}
61
62
63def _manifest(package_id, version):
64 return {"id": package_id, "name": package_id, "version": version,
65 "objects": [], "schemas": [], "permissions": [{"path": "permissions/rules.json"}]}
66
67
68def _ship(root, package_id, version, rules, retracted=None):
69 """Write (or rewrite: a new version) a package that ships only rules."""
70 package_dir = root / package_id
71 (package_dir / "permissions").mkdir(parents=True, exist_ok=True)
72 (package_dir / object_packages.MANIFEST_FILE).write_text(
73 json.dumps(_manifest(package_id, version)))
74 fragment = {"rules": rules}
75 if retracted is not None:
76 fragment["retracted"] = retracted
77 (package_dir / "permissions" / "rules.json").write_text(json.dumps(fragment))
78
79
80class Box:
81 def __init__(self, tmp_path):
82 self.packages = tmp_path / "packages"
83 self.data = tmp_path / "data"
84 self.objects = tmp_path / "objects"
85 self.objects.mkdir()
86
87 def ship(self, package_id, version, rules, retracted=None):
88 _ship(self.packages, package_id, version, rules, retracted)
89
90 def install(self, package_id="app-things"):
91 return object_packages.install_package(
92 package_id, root=self.packages, base_dir=self.data,
93 object_roots=[self.objects], allow_replace=True)
94
95 def dry_run(self, package_id="app-things"):
96 return object_packages.dry_run_package(
97 package_id, root=self.packages, base_dir=self.data, object_roots=[self.objects])
98
99 def policy(self):
100 return object_permission_store.load_policy(self.data)
101
102 def rules(self):
103 return [_shape(rule) for rule in self.policy().rules]
104
105 def forget_shipped_rules(self, package_id="app-things"):
106 """Make this a box installed BEFORE baselines recorded permissions:
107 the rules are in the policy, tagged, and nothing says who shipped
108 what."""
109 path = object_package_baselines.baseline_path(package_id, base_dir=self.data)
110 baseline = json.loads(path.read_text())
111 baseline.pop("permissions", None)
112 path.write_text(json.dumps(baseline))
113
114 def edit_policy(self, edit):
115 payload = object_permissions.policy_to_dict(self.policy())
116 edit(payload["rules"])
117 object_permission_store.replace_policy(payload, self.data)
118
119
120def _shape(rule):
121 """A rule as (package tag, the fields that identify it)."""
122 payload = rule if isinstance(rule, dict) else object_permissions.rule_to_dict(rule)
123 return (payload.get("package"), payload["principal"], tuple(sorted(payload["actions"])),
124 payload.get("collection") or payload.get("object_id"),
125 json.dumps(payload.get("row_filter") or {}, sort_keys=True))
126
127
128def _retractions(result, action=None):
129 entries = result["permission_retractions"]
130 return [entry for entry in entries if action is None or entry["action"] == action]
131
132
133@pytest.fixture
134def box(tmp_path):
135 return Box(tmp_path)
136
137
138# =============================================================================
139# The gap, and the baseline that closes it going forward
140# =============================================================================
141
142def test_an_upgrade_removes_a_rule_the_package_no_longer_ships(box):
143 """The stale-grant case: version 2 deletes the public page grant."""
144 box.ship("app-things", "1", [READ_OWN, PAGE])
145 box.install()
146 assert _shape({**PAGE, "package": "app-things"}) in box.rules()
147
148 box.ship("app-things", "2", [READ_OWN])
149 upgrade = box.install()
150
151 assert box.rules() == [_shape({**READ_OWN, "package": "app-things"})]
152 removed = _retractions(upgrade, "remove")
153 assert [(e["status"], e["because"], e["rule"]["object_id"]) for e in removed] == [
154 ("removed", "no_longer_shipped", "site_things")]
155 # Anonymous execution of an object later created under that id is refused.
156 assert not object_permissions.check_permission(
157 None, "execute", policy=box.policy(), object_id="site_things").allowed
158
159
160def test_an_upgrade_replaces_a_tightened_rule_instead_of_keeping_both(box):
161 """The template_runs case: the same grant with a row filter added is a
162 DIFFERENT rule, so append-only left the wide one in force beside it."""
163 box.ship("app-things", "1", [READ_ALL])
164 box.install()
165 box.ship("app-things", "2", [READ_OWN])
166 upgrade = box.install()
167
168 assert box.rules() == [_shape({**READ_OWN, "package": "app-things"})]
169 assert len(_retractions(upgrade, "remove")) == 1
170 bob = object_permissions.PermissionSubject(user_id="bob")
171 assert not object_permissions.check_permission(
172 bob, "read", policy=box.policy(), collection="things",
173 record={"id": "t1", "owner_id": "alice"}).allowed
174 assert object_permissions.check_permission(
175 bob, "read", policy=box.policy(), collection="things",
176 record={"id": "t2", "owner_id": "bob"}).allowed
177
178
179def test_a_reinstall_of_the_same_version_changes_nothing_and_reports_nothing(box):
180 box.ship("app-things", "1", [READ_OWN, PAGE])
181 box.install()
182 before = box.rules()
183 again = box.install()
184 assert box.rules() == before
185 assert again["permission_retractions"] == []
186 assert again["permissions"][0]["new_rules"] == 0
187
188
189def test_the_baseline_records_what_the_package_shipped(box):
190 box.ship("app-things", "1", [READ_OWN, PAGE])
191 box.install()
192 baseline = object_package_baselines.load_baseline("app-things", base_dir=box.data)
193 assert sorted(_shape(rule) for rule in baseline["permissions"]) == sorted(
194 [_shape(READ_OWN), _shape(PAGE)])
195
196
197# =============================================================================
198# What the operator wrote or edited is never removed
199# =============================================================================
200
201def test_an_upgrade_keeps_a_rule_the_operator_added(box):
202 box.ship("app-things", "1", [READ_ALL])
203 box.install()
204 mine = {"effect": "allow", "principal": "role:support", "actions": ["read", "update"],
205 "collection": "things", "reason": "support fixes things"}
206 box.edit_policy(lambda rules: rules.append(mine))
207
208 box.ship("app-things", "2", [READ_OWN])
209 box.install()
210
211 assert _shape(mine) in box.rules()
212 assert _shape({**READ_ALL, "package": "app-things"}) not in box.rules()
213
214
215def test_an_upgrade_keeps_a_package_rule_the_operator_edited_and_says_so(box):
216 """The operator narrowed the page grant from public to registered and
217 left the package tag on it (GET the policy, edit, PUT it back). It is no
218 longer the rule the package shipped, so retiring that rule must not
219 take the operator's version with it."""
220 box.ship("app-things", "1", [READ_OWN, PAGE])
221 box.install()
222
223 def narrow(rules):
224 for rule in rules:
225 if rule.get("object_id") == "site_things":
226 rule["principal"] = "registered"
227 box.edit_policy(narrow)
228 edited = _shape({**PAGE, "principal": "registered", "package": "app-things"})
229 # v1 reinstalled would put the shipped rule back beside the edit (the
230 # append behaviour, unchanged); v2 no longer ships it at all.
231 box.ship("app-things", "2", [READ_OWN])
232 upgrade = box.install()
233
234 assert edited in box.rules()
235 kept = _retractions(upgrade, "keep")
236 assert [(e["status"], e["because"], _shape(e["rule"])) for e in kept] == [
237 ("kept", "unaccounted", edited)]
238 assert _retractions(upgrade, "remove") == []
239
240
241def test_an_operator_rule_identical_to_a_retired_one_is_kept_and_reported(box):
242 """The operator wrote the same grant by hand before the package was
243 installed: the merge found it present and never tagged it. Nothing
244 records it as the package's, so the package may not take it away -- but
245 the operator is told it is now the only thing keeping that door open."""
246 object_permission_store.replace_policy({"rules": [dict(PAGE)]}, box.data)
247 box.ship("app-things", "1", [READ_OWN, PAGE])
248 box.install()
249 assert _shape(PAGE) in box.rules() # untagged: the operator's
250
251 box.ship("app-things", "2", [READ_OWN])
252 upgrade = box.install()
253
254 assert _shape(PAGE) in box.rules()
255 kept = _retractions(upgrade, "keep")
256 assert [(e["because"], _shape(e["rule"])) for e in kept] == [("operator_rule", _shape(PAGE))]
257
258
259def test_another_packages_identical_rule_is_not_removed(box):
260 """Two packages ship the same rule; the first to install is the one
261 tagged. When that one stops shipping it, the other still does, so the
262 rule stays and changes hands rather than vanishing until the other's
263 next install."""
264 box.ship("app-things", "1", [READ_OWN, PAGE])
265 box.ship("app-other", "1", [PAGE])
266 box.install("app-things")
267 box.install("app-other")
268 assert box.rules().count(_shape({**PAGE, "package": "app-things"})) == 1
269
270 box.ship("app-things", "2", [READ_OWN])
271 upgrade = box.install("app-things")
272
273 assert _shape({**PAGE, "package": "app-other"}) in box.rules()
274 assert [(e["status"], e["because"]) for e in _retractions(upgrade, "reassign")] == [
275 ("reassigned", "still_shipped_by:app-other")]
276 # And when the second package drops it too, it goes.
277 box.ship("app-other", "2", [])
278 box.install("app-other")
279 assert box.rules() == [_shape({**READ_OWN, "package": "app-things"})]
280
281
282# =============================================================================
283# A box installed before baselines recorded permissions
284# =============================================================================
285
286def test_a_legacy_box_keeps_an_unshipped_rule_nothing_retracts_and_reports_it(box):
287 """With no record of what the old version shipped, a tagged rule the
288 package does not ship is either an old shipped rule or the operator's
289 edit of one. Those cannot be told apart, so it is not removed; it is
290 reported on every install until somebody decides."""
291 box.ship("app-things", "1", [READ_ALL, PAGE])
292 box.install()
293 box.forget_shipped_rules()
294
295 box.ship("app-things", "2", [READ_OWN])
296 upgrade = box.install()
297
298 assert _shape({**READ_ALL, "package": "app-things"}) in box.rules()
299 assert sorted(e["because"] for e in _retractions(upgrade)) == ["unaccounted", "unaccounted"]
300 assert _retractions(upgrade, "remove") == []
301
302
303def test_a_legacy_box_drops_exactly_the_rules_the_package_retracts(box):
304 box.ship("app-things", "1", [READ_ALL, PAGE, WRITE_OWN])
305 box.install()
306 box.forget_shipped_rules()
307
308 box.ship("app-things", "2", [READ_OWN, WRITE_OWN], retracted=[
309 {**READ_ALL, "reason": "replaced by the owner-filtered read"},
310 {**PAGE, "reason": "the page is gone"}])
311 upgrade = box.install()
312
313 assert sorted(box.rules()) == sorted([
314 _shape({**READ_OWN, "package": "app-things"}),
315 _shape({**WRITE_OWN, "package": "app-things"})])
316 removed = _retractions(upgrade, "remove")
317 assert sorted((e["because"], e["why"]) for e in removed) == [
318 ("retracted", "replaced by the owner-filtered read"),
319 ("retracted", "the page is gone")]
320
321
322def test_a_retraction_spares_the_operators_edit_of_the_retracted_rule(box):
323 box.ship("app-things", "1", [READ_ALL])
324 box.install()
325 box.forget_shipped_rules()
326
327 def narrow(rules):
328 rules[0]["row_filter"] = {"status": "published"}
329 box.edit_policy(narrow)
330
331 box.ship("app-things", "2", [READ_OWN], retracted=[READ_ALL])
332 upgrade = box.install()
333
334 edited = _shape({**READ_ALL, "row_filter": {"status": "published"}, "package": "app-things"})
335 assert edited in box.rules()
336 assert _retractions(upgrade, "remove") == []
337
338
339def test_a_retracted_rule_tagged_for_another_package_is_left_alone(box):
340 box.ship("app-other", "1", [PAGE])
341 box.install("app-other")
342 box.ship("app-things", "1", [READ_OWN], retracted=[PAGE])
343 install = box.install("app-things")
344 assert _shape({**PAGE, "package": "app-other"}) in box.rules()
345 assert _retractions(install, "remove") == []
346
347
348def test_a_package_may_not_ship_a_rule_it_also_retracts(box):
349 box.ship("app-things", "1", [READ_OWN, PAGE], retracted=[PAGE])
350 assert any("both ships and retracts" in warning for warning in box.dry_run()["warnings"])
351 with pytest.raises(object_packages.PackageInstallError, match="both ships and retracts"):
352 box.install()
353 assert box.policy().rules == ()
354
355
356@pytest.mark.parametrize("retracted, message", [
357 ("nope", "retracted must be a list"),
358 ([{"effect": "allow"}], "retracted permission rule is invalid"),
359 (["x"], "retracted rules must be objects"),
360])
361def test_an_invalid_retracted_list_blocks_the_install(box, retracted, message):
362 box.ship("app-things", "1", [READ_OWN], retracted=retracted)
363 with pytest.raises(object_packages.PackageInstallError, match=message):
364 box.install()
365
366
367# =============================================================================
368# The operator can see what happened
369# =============================================================================
370
371def test_a_dry_run_lists_what_an_install_would_remove_and_writes_nothing(box):
372 box.ship("app-things", "1", [READ_ALL, PAGE])
373 box.install()
374 before = box.rules()
375 box.ship("app-things", "2", [READ_OWN])
376
377 plan = box.dry_run()
378
379 assert sorted((e["action"], e["because"]) for e in plan["permission_retractions"]) == [
380 ("remove", "no_longer_shipped"), ("remove", "no_longer_shipped")]
381 assert all("status" not in entry for entry in plan["permission_retractions"])
382 assert box.rules() == before
383
384
385def test_the_package_change_log_keeps_the_removed_rules(box):
386 """The install response scrolls away; data/package_changes is the durable
387 record, and a removed grant has to be reconstructible from it."""
388 box.ship("app-things", "1", [READ_OWN, PAGE])
389 box.install()
390 box.ship("app-things", "2", [READ_OWN])
391 upgrade = box.install()
392
393 details = object_package_changes.dry_run_change_details(upgrade)
394 assert [(e["action"], e["rule"]["object_id"], e["rule"]["principal"])
395 for e in details["permission_retractions"]] == [("remove", "site_things", "public")]
396 stored = object_package_changes.append_package_change(
397 package_id="app-things", action="installed", details=details, base_dir=box.data)
398 assert stored["details"]["permission_retractions"][0]["rule"]["actions"] == ["execute"]
399
400
401def test_the_unshipped_report_lists_rules_no_installed_package_ships(box):
402 mine = {"effect": "allow", "principal": "role:support", "actions": ["read"],
403 "collection": "things", "reason": "support reads things"}
404 box.ship("app-things", "1", [READ_ALL, PAGE])
405 box.install()
406 box.forget_shipped_rules()
407 box.edit_policy(lambda rules: rules.append(mine))
408 box.ship("app-things", "2", [READ_OWN], retracted=[PAGE]) # on disk, not yet installed
409
410 report = object_packages.unshipped_permission_rules(roots=[box.packages], base_dir=box.data)
411
412 listed = {_shape(entry["rule"]): entry["state"] for entry in report["rules"]}
413 assert listed == {
414 _shape(mine): "operator",
415 _shape({**PAGE, "package": "app-things"}): "retracted",
416 _shape({**READ_ALL, "package": "app-things"}): "unaccounted",
417 }
418 assert report["installed_packages"] == ["app-things"]
419 assert report["policy_rules"] == 3 and report["count"] == 3
420
421 box.install()
422 after = object_packages.unshipped_permission_rules(roots=[box.packages], base_dir=box.data)
423 assert {_shape(e["rule"]): e["state"] for e in after["rules"]} == {
424 _shape(mine): "operator",
425 _shape({**READ_ALL, "package": "app-things"}): "unaccounted",
426 }
427
428
429def test_the_unshipped_report_names_a_rule_whose_package_is_gone(box):
430 box.ship("app-things", "1", [PAGE])
431 box.install()
432 shutil.rmtree(box.packages / "app-things")
433 report = object_packages.unshipped_permission_rules(roots=[box.packages], base_dir=box.data)
434 assert [(e["state"], e["package"]) for e in report["rules"]] == [
435 ("package_missing", "app-things")]
436
437
438# =============================================================================
439# The real packages: a box installed before today's rule changes, upgraded
440# =============================================================================
441
442# What the packages shipped before d281173 (the 14 stale execute grants) and
443# aa217fe (unfiltered reads of template_runs and thread_comments), written
444# out rather than derived from the `retracted` lists they are checked against.
445OLD_RULES = {
446 "app-articles": [("public", ["execute"], {"object_id": "site_articles"})],
447 "app-catalog": [("public", ["execute"], {"object_id": "site_products"}),
448 ("public", ["execute"], {"object_id": "site_locations"})],
449 "app-contacts": [("public", ["execute"], {"object_id": "site_contacts"})],
450 "app-finance": [("public", ["execute"], {"object_id": "site_accounts"}),
451 ("public", ["execute"], {"object_id": "site_journals"})],
452 "app-invoices": [("public", ["execute"], {"object_id": "site_invoices"})],
453 "app-kitchen": [("registered", ["execute"], {"object_id": "system_kitchen_attention"})],
454 "app-links": [("public", ["execute"], {"object_id": "site_links"})],
455 "app-notes": [("public", ["execute"], {"object_id": "site_notes"})],
456 "app-orders": [("public", ["execute"], {"object_id": "site_orders"})],
457 "app-projects": [("public", ["execute"], {"object_id": "site_projects"})],
458 "app-tasks": [("public", ["execute"], {"object_id": "site_tasks"})],
459 "app-templates": [("public", ["execute"], {"object_id": "site_templates"})],
460 "app-runner": [("registered", ["read"], {"collection": "template_runs"})],
461 "app-thread": [("registered", ["read"], {"collection": "thread_comments"})],
462}
463
464
465def _old_rule(principal, actions, target):
466 return {"effect": "allow", "principal": principal, "actions": actions, **target,
467 "reason": "as shipped before 2026-11-28"}
468
469
470def _package_closure(names):
471 ordered = []
472
473 def visit(name):
474 if name in ordered:
475 return
476 manifest = json.loads((PACKAGES_ROOT / name / "dbbasic-package.json").read_text())
477 for dep in manifest.get("dependencies", []):
478 visit(dep if isinstance(dep, str) else dep["id"])
479 ordered.append(name)
480
481 for name in names:
482 visit(name)
483 return ordered
484
485
486def _legacy_install(package_id, data, objects):
487 """Install today's package, then put the policy and baseline back the way
488 a pre-2026-11-28 box has them: the old rules present and tagged, and no
489 record of which rules the package shipped."""
490 for name in _package_closure([package_id]):
491 object_packages.install_package(
492 name, root=PACKAGES_ROOT, base_dir=data, object_roots=[objects])
493 payload = object_permissions.policy_to_dict(object_permission_store.load_policy(data))
494 for principal, actions, target in OLD_RULES[package_id]:
495 payload["rules"].append({**_old_rule(principal, actions, target), "package": package_id})
496 object_permission_store.replace_policy(payload, data)
497 path = object_package_baselines.baseline_path(package_id, base_dir=data)
498 baseline = json.loads(path.read_text())
499 baseline.pop("permissions", None)
500 path.write_text(json.dumps(baseline))
501
502
503@pytest.mark.parametrize("package_id", sorted(OLD_RULES))
504def test_upgrading_a_box_installed_before_the_rule_changes_drops_the_old_rules(
505 package_id, tmp_path):
506 data, objects = tmp_path / "data", tmp_path / "objects"
507 objects.mkdir()
508 _legacy_install(package_id, data, objects)
509 old = [_shape({**_old_rule(*rule), "package": package_id}) for rule in OLD_RULES[package_id]]
510 live = [_shape(rule) for rule in object_permission_store.load_policy(data).rules]
511 assert all(shape in live for shape in old) # the legacy state is real
512
513 upgrade = object_packages.install_package(
514 package_id, root=PACKAGES_ROOT, base_dir=data, object_roots=[objects],
515 allow_replace=True)
516
517 live = [_shape(rule) for rule in object_permission_store.load_policy(data).rules]
518 assert [shape for shape in old if shape in live] == []
519 removed = [_shape(entry["rule"]) for entry in _retractions(upgrade, "remove")]
520 assert sorted(removed) == sorted(old)
521 assert all(entry["because"] == "retracted" and entry["why"]
522 for entry in _retractions(upgrade, "remove"))
523 # Nothing the package ships today was taken with them.
524 shipped = json.loads((PACKAGES_ROOT / package_id / "permissions" / "rules.json").read_text())
525 for rule in shipped["rules"]:
526 assert _shape({**rule, "package": package_id}) in live
527
528
529def test_no_package_retracts_a_rule_that_any_package_ships():
530 """A retraction naming a rule some package still ships would remove it on
531 a legacy box (no baseline says the other package ships it) until that
532 package's next install put it back."""
533 shipped, retracted = {}, []
534 for manifest_path in sorted(PACKAGES_ROOT.glob("*/dbbasic-package.json")):
535 manifest = json.loads(manifest_path.read_text())
536 for entry in manifest.get("permissions", []):
537 fragment = json.loads((manifest_path.parent / entry["path"]).read_text())
538 for rule in fragment["rules"]:
539 key = object_packages._rule_merge_key(object_permissions.rule_from_dict(rule))
540 shipped[key] = manifest["id"]
541 for rule in fragment.get("retracted", []):
542 assert rule.get("reason"), f"{manifest['id']}: a retraction says why"
543 retracted.append((manifest["id"], object_packages._rule_merge_key(
544 object_permissions.rule_from_dict(rule))))
545 assert retracted, "the 2026-11-28 retractions are gone"
546 assert [(package, shipped[key]) for package, key in retracted if key in shipped] == []
547
548
549# --- through the real HTTP API, enforcement on --------------------------------
550
551class Site:
552 def __init__(self, tmp_path, monkeypatch):
553 self.data = tmp_path / "data"
554 self.root = tmp_path / "objects"
555 self.root.mkdir(parents=True, exist_ok=True)
556 monkeypatch.setenv("DBBASIC_DATA_DIR", str(self.data))
557 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(self.root))
558 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", ADMIN_TOKEN)
559 monkeypatch.setenv("DBBASIC_ENABLE_PERMISSION_ENFORCEMENT", "true")
560 for name in ("DBBASIC_OBJECT_TIMEOUT_SECONDS", "DBBASIC_WORKER_POOL_SIZE",
561 "DBBASIC_ROW_FILTER_INDEX", "DBBASIC_TRUSTED_IN_PROCESS_OBJECTS",
562 "DBBASIC_ALLOW_UNREADY_PERMISSION_ENFORCEMENT",
563 "DBBASIC_ENABLE_SESSION_ADMIN_GATES", "DBBASIC_PACKAGES_DIR",
564 "DBBASIC_PRIVATE_PACKAGES_DIR"):
565 monkeypatch.delenv(name, raising=False)
566 self.admin = [("authorization", f"Token {ADMIN_TOKEN}")]
567
568 def user(self, user_id):
569 object_identity.create_user({"user_id": user_id, "roles": []}, base_dir=self.data)
570 session = object_identity.create_session({"user_id": user_id}, base_dir=self.data)
571 return [("authorization", f"Bearer {session['token']}")]
572
573 def call(self, path, method="GET", payload=None, headers=()):
574 body = json.dumps(payload).encode("utf-8") if payload is not None else b""
575 scope_headers = [(b"accept", b"application/json"), (b"content-type", b"application/json")]
576 scope_headers += [(k.encode("latin-1"), v.encode("latin-1")) for k, v in headers]
577 messages = []
578
579 async def receive():
580 return {"type": "http.request", "body": body, "more_body": False}
581
582 async def send(message):
583 messages.append(message)
584
585 scope = {"type": "http", "method": method, "path": path, "query_string": b"",
586 "headers": scope_headers, "client": ("127.0.0.1", 12345)}
587 asyncio.run(object_server.app(scope, receive, send))
588 start = next(m for m in messages if m["type"] == "http.response.start")
589 raw = b"".join(m.get("body", b"") for m in messages if m["type"] == "http.response.body")
590 return start["status"], json.loads(raw.decode("utf-8"))
591
592
593def test_an_upgraded_box_stops_showing_other_users_runs_over_the_api(tmp_path, monkeypatch):
594 """The consequence, end to end: on a box that had app-runner before the
595 read rule was tightened, bob could list alice's runs after the upgrade
596 because the old unfiltered rule was still in the policy."""
597 site = Site(tmp_path, monkeypatch)
598 _legacy_install("app-runner", site.data, site.root)
599 alice, bob = site.user("alice"), site.user("bob")
600 object_records.create_collection_record(
601 "templates", {"id": "t1", "name": "T", "body": "b", "handler": "echo",
602 "owner_id": "alice"}, base_dir=site.data, preserve_read_only=True)
603 object_records.create_collection_record(
604 "template_runs", {"id": "run-1", "template_id": "t1", "template_name": "T",
605 "handler": "echo", "status": "succeeded", "owner_id": "alice",
606 "output": "ALICE-OUTPUT"},
607 base_dir=site.data, preserve_read_only=True)
608 status, flags = site.call("/permissions/status", headers=site.admin)
609 assert status == 200 and flags["permissions"]["enforcement_enabled"]
610 # The legacy box really does leak (the state the upgrade has to fix).
611 status, body = site.call("/collections/template_runs/records/run-1", headers=bob)
612 assert status == 200 and body["record"]["output"] == "ALICE-OUTPUT"
613
614 object_packages.install_package(
615 "app-runner", root=PACKAGES_ROOT, base_dir=site.data, object_roots=[site.root],
616 allow_replace=True)
617
618 status, _ = site.call("/collections/template_runs/records/run-1", headers=bob)
619 assert status in (403, 404)
620 status, body = site.call("/collections/template_runs/records", headers=bob)
621 assert status == 200 and body["records"] == []
622 status, body = site.call("/collections/template_runs/records/run-1", headers=alice)
623 assert status == 200 and body["record"]["output"] == "ALICE-OUTPUT"
624
625
626def test_the_unshipped_endpoint_is_admin_only_and_reports_the_policy(tmp_path, monkeypatch):
627 site = Site(tmp_path, monkeypatch)
628 monkeypatch.setenv("DBBASIC_PACKAGES_DIR", str(PACKAGES_ROOT))
629 _legacy_install("app-notes", site.data, site.root)
630 alice = site.user("alice")
631
632 assert site.call("/permissions/unshipped")[0] in (401, 403)
633 assert site.call("/permissions/unshipped", headers=alice)[0] in (401, 403)
634 assert site.call("/permissions/unshipped", method="POST", headers=site.admin)[0] == 405
635
636 status, body = site.call("/permissions/unshipped", headers=site.admin)
637 assert status == 200 and body["status"] == "ok"
638 assert [(e["state"], e["package"], e["rule"]["object_id"]) for e in body["rules"]] == [
639 ("retracted", "app-notes", "site_notes")]
640
641
642# =============================================================================
643# The retraction lists are complete (read from this checkout's git history)
644# =============================================================================
645
646def _git(*args):
647 return subprocess.run(["git", "-C", str(ROOT), *args], capture_output=True,
648 text=True, timeout=120)
649
650
651def _rule_key(rule):
652 return object_packages._rule_merge_key(object_permissions.rule_from_dict(rule))
653
654
655def test_every_rule_a_package_shipped_and_then_dropped_is_retracted():
656 """A box installed before baselines recorded rules only loses a withdrawn
657 rule if the package RETRACTS it, and nothing reminds an author to write
658 that entry: deleting or tightening a rule in rules.json looks finished,
659 passes every other test, and fixes fresh installs only -- the bug this
660 file exists for.
661
662 So this reads every version of every package's permissions file that
663 git can reach from HEAD and requires each rule that was ever shipped,
664 and is not shipped now, to be in that package's `retracted` list. If it
665 fails, paste the printed rules into `retracted` (with a `reason` saying
666 why they went). Local history only; skipped where there is none (an
667 export without .git), and a shallow clone simply checks less.
668 """
669 if shutil.which("git") is None or _git("rev-parse", "--is-inside-work-tree").returncode != 0:
670 pytest.skip("no git history to read")
671
672 missing = []
673 for manifest_path in sorted(PACKAGES_ROOT.glob("*/dbbasic-package.json")):
674 manifest = json.loads(manifest_path.read_text())
675 for entry in manifest.get("permissions", []):
676 relative = f"packages/{manifest_path.parent.name}/{entry['path']}"
677 fragment = json.loads((ROOT / relative).read_text())
678 accounted = {_rule_key(rule) for rule in fragment["rules"]}
679 accounted |= {_rule_key(rule) for rule in fragment.get("retracted", [])}
680 commits = _git("log", "--format=%H", "--", relative)
681 if commits.returncode != 0:
682 pytest.skip(f"git log failed: {commits.stderr.strip()[:200]}")
683 for commit in commits.stdout.split():
684 shown = _git("show", f"{commit}:{relative}")
685 if shown.returncode != 0:
686 continue # the commit that deleted or moved the file
687 try:
688 old = json.loads(shown.stdout)
689 except json.JSONDecodeError:
690 continue
691 for rule in (old.get("rules", []) if isinstance(old, dict) else old):
692 try:
693 key = _rule_key(rule)
694 except (ValueError, AttributeError):
695 continue # never installable, so never installed
696 if key not in accounted:
697 accounted.add(key)
698 slim = {k: v for k, v in rule.items() if k != "reason"}
699 missing.append(f"{manifest['id']} (last shipped in {commit[:7]}): "
700 f"{json.dumps(slim)}")
701 assert missing == [], (
702 f"{len(missing)} rule(s) were shipped and are no longer shipped, but are not in "
703 "their package's `retracted` list, so an installed box keeps them:\n "
704 + "\n ".join(missing))