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_restore_policy_diff.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_package_restore_policy_diff.py · 16.4 KB · 395 lines
1"""A restore shows the permission-policy difference it would make, and is
2applied only against the difference the operator saw.
3
4A package restore puts back the snapshot's data/permissions/policy.json. A
5deny rule added since the install -- to close a hole -- silently vanished
6with it, and the box was looser after the rollback than before it, with
7nothing on the way saying so.
8"""
9
10import json
11
12import pytest
13
14import object_policy_diff
15from test_object_server import (
16 auth_headers,
17 enable_admin_token,
18 request,
19 write_package,
20 write_source,
21)
22
23ALLOW_NOTES = {"effect": "allow", "principal": "role:editor", "actions": ["read", "update"],
24 "collection": "notes"}
25DENY_NOTES_DELETE = {"effect": "deny", "principal": "role:editor", "actions": ["delete"],
26 "collection": "notes", "reason": "closed after an incident"}
27
28
29def _policy(*rules, **extra):
30 return {"access_mode": "role_based", "rules": list(rules), **extra}
31
32
33@pytest.fixture
34def env(tmp_path, monkeypatch):
35 packages_root = tmp_path / "packages"
36 data_dir = tmp_path / "data"
37 object_root = tmp_path / "objects"
38 write_source(object_root / "site" / "home.py", "def GET(request): return {'before': True}\n")
39 write_package(
40 packages_root,
41 "hello-world",
42 {
43 "id": "hello-world",
44 "name": "Hello World",
45 "version": "0.1.0",
46 "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
47 },
48 files=(("objects/hello/world.py", "def GET(request): return {'new': True}\n"),),
49 )
50 monkeypatch.setenv("DBBASIC_PACKAGES_DIR", str(packages_root))
51 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
52 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(object_root))
53 monkeypatch.setenv("DBBASIC_ENABLE_PACKAGE_INSTALLS", "true")
54 monkeypatch.setenv("DBBASIC_ENABLE_PACKAGE_RESTORE", "true")
55 monkeypatch.delenv("DBBASIC_BACKUPS_DIR", raising=False)
56 enable_admin_token(monkeypatch)
57 return data_dir, object_root
58
59
60def _write_policy(data_dir, payload):
61 path = data_dir / "permissions" / "policy.json"
62 path.parent.mkdir(parents=True, exist_ok=True)
63 path.write_text(json.dumps(payload))
64 return path
65
66
67def _install():
68 status, _, result = request(
69 "/packages/hello-world/install", method="POST",
70 body=json.dumps({"allow_replace": True}).encode(), headers=auth_headers(),
71 )
72 assert status == 201, result
73 return result["changes"]["installed"]
74
75
76def _restore(body):
77 return request(
78 "/packages/hello-world/restore", method="POST",
79 body=json.dumps(body).encode(), headers=auth_headers(),
80 )
81
82
83def _package_actions():
84 status, _, history = request("/packages/hello-world/changes", headers=auth_headers())
85 assert status == 200, history
86 return [entry["action"] for entry in history["changes"]]
87
88
89def _installed_then_tightened(data_dir):
90 _write_policy(data_dir, _policy(ALLOW_NOTES))
91 change = _install()
92 # Since the install: a deny added to close a hole.
93 _write_policy(data_dir, _policy(ALLOW_NOTES, DENY_NOTES_DELETE))
94 return change
95
96
97def test_preview_shows_a_loosening_difference_and_changes_nothing(env):
98 data_dir, object_root = env
99 change = _installed_then_tightened(data_dir)
100 actions_before = _package_actions()
101
102 status, _, preview = _restore({"change_id": change["change_id"], "preview": True})
103
104 assert status == 200, preview
105 assert preview["preview"] is True
106 diff = preview["policy_diff"]
107 assert diff["changed"] is True and diff["loosens"] is True
108 removed = [c for c in diff["changes"] if c["kind"] == "rule_removed"]
109 assert len(removed) == 1 and removed[0]["effect"] == "loosens"
110 assert removed[0]["before"]["actions"] == ["delete"]
111 assert preview["policy_diff_hash"].startswith("sha256:")
112 assert "LOOSENS" in preview["policy_diff_text"]
113 assert "deny role:editor delete on collection notes" in preview["policy_diff_text"]
114 # Nothing restored, nothing logged.
115 assert (object_root / "hello" / "world.py").exists()
116 assert "deny" in (data_dir / "permissions" / "policy.json").read_text()
117 assert _package_actions() == actions_before
118
119
120def test_apply_without_the_previewed_hash_is_refused_with_the_difference(env):
121 data_dir, object_root = env
122 change = _installed_then_tightened(data_dir)
123
124 status, _, refused = _restore({"change_id": change["change_id"], "confirm": "restore-runtime"})
125
126 assert status == 409, refused
127 assert "LOOSENS" in refused["error"]
128 assert refused["policy_diff"]["loosens"] is True
129 assert refused["policy_diff_hash"].startswith("sha256:")
130 assert (object_root / "hello" / "world.py").exists()
131 assert "deny" in (data_dir / "permissions" / "policy.json").read_text()
132 assert _package_actions()[0] == "failed"
133
134
135def test_apply_with_the_previewed_hash_restores_and_records_the_difference(env):
136 data_dir, object_root = env
137 change = _installed_then_tightened(data_dir)
138 _, _, preview = _restore({"change_id": change["change_id"], "preview": True})
139
140 status, _, restored = _restore({
141 "change_id": change["change_id"], "confirm": "restore-runtime",
142 "policy_diff_hash": preview["policy_diff_hash"],
143 })
144
145 assert status == 200, restored
146 assert not (object_root / "hello" / "world.py").exists()
147 assert json.loads((data_dir / "permissions" / "policy.json").read_text())["rules"] == [
148 ALLOW_NOTES]
149 details = restored["changes"]["rolled_back"]["details"]
150 assert details["policy_diff_hash"] == preview["policy_diff_hash"]
151 assert details["policy_diff"]["loosens"] is True
152
153
154def test_a_policy_changed_after_the_preview_is_refused(env):
155 data_dir, object_root = env
156 change = _installed_then_tightened(data_dir)
157 _, _, preview = _restore({"change_id": change["change_id"], "preview": True})
158 # Someone tightens further between the preview and the apply.
159 _write_policy(data_dir, _policy(ALLOW_NOTES, DENY_NOTES_DELETE,
160 {**DENY_NOTES_DELETE, "actions": ["create"]}))
161
162 status, _, refused = _restore({
163 "change_id": change["change_id"], "confirm": "restore-runtime",
164 "policy_diff_hash": preview["policy_diff_hash"],
165 })
166
167 assert status == 409, refused
168 assert "not the one previewed" in refused["error"]
169 assert refused["policy_diff_hash"] != preview["policy_diff_hash"]
170 assert (object_root / "hello" / "world.py").exists()
171
172
173def test_an_unreadable_policy_refuses_the_restore(env):
174 data_dir, object_root = env
175 change = _install()
176 (data_dir / "permissions").mkdir(parents=True, exist_ok=True)
177 (data_dir / "permissions" / "policy.json").write_text("{not json")
178 actions_before = _package_actions()
179
180 status, _, refused = _restore({"change_id": change["change_id"], "preview": True})
181 assert status == 409 and "cannot be computed" in refused["error"]
182 assert _package_actions() == actions_before # a preview logs nothing
183
184 for body in (
185 {"change_id": change["change_id"], "confirm": "restore-runtime"},
186 {"change_id": change["change_id"], "confirm": "restore-runtime",
187 "policy_diff_hash": "sha256:" + "0" * 64},
188 ):
189 status, _, refused = _restore(body)
190 assert status == 409, refused
191 assert "cannot be computed" in refused["error"]
192 assert (object_root / "hello" / "world.py").exists()
193
194
195def test_no_policy_difference_needs_no_hash(env):
196 data_dir, object_root = env
197 _write_policy(data_dir, _policy(ALLOW_NOTES))
198 change = _install()
199
200 status, _, restored = _restore({"change_id": change["change_id"], "confirm": "restore-runtime"})
201
202 assert status == 200, restored
203 assert restored["policy_diff"]["changed"] is False
204 assert not (object_root / "hello" / "world.py").exists()
205
206
207def test_a_tightening_restore_is_not_called_loosening(env):
208 data_dir, _ = env
209 _write_policy(data_dir, _policy(ALLOW_NOTES, DENY_NOTES_DELETE))
210 change = _install()
211 _write_policy(data_dir, _policy(ALLOW_NOTES)) # the deny was dropped since
212
213 status, _, preview = _restore({"change_id": change["change_id"], "preview": True})
214
215 assert status == 200, preview
216 assert preview["policy_diff"]["changed"] is True
217 assert preview["policy_diff"]["loosens"] is False
218 assert "LOOSENS" not in preview["policy_diff_text"]
219
220
221def test_a_policy_the_snapshot_lacks_is_diffed_against_the_default(env):
222 """No policy.json in the snapshot: the prune removes the live one and the
223 default (role_based, no rules) applies -- that is the difference shown."""
224 data_dir, _ = env
225 change = _install()
226 _write_policy(data_dir, _policy(ALLOW_NOTES, DENY_NOTES_DELETE))
227
228 status, _, preview = _restore({"change_id": change["change_id"], "preview": True})
229
230 assert status == 200, preview
231 kinds = sorted((c["kind"], c["effect"]) for c in preview["policy_diff"]["changes"])
232 assert kinds == [("rule_removed", "loosens"), ("rule_removed", "tightens")]
233
234
235# --- the classification itself ---------------------------------------------------
236
237def _diff(current, snapshot, current_fields=None, snapshot_fields=None):
238 import object_permissions
239
240 def norm(payload):
241 return object_permissions.policy_to_dict(object_permissions.policy_from_dict(payload))
242
243 return object_policy_diff.compute_policy_diff(
244 norm(current), norm(snapshot), current_fields, snapshot_fields)
245
246
247def _effects(diff):
248 return [(c["kind"], c["effect"]) for c in diff["changes"]]
249
250
251def test_rule_changes_are_classified_by_what_they_allow():
252 wider = {**ALLOW_NOTES, "actions": ["read", "update", "delete"]}
253 assert _effects(_diff(_policy(ALLOW_NOTES), _policy(wider))) == [("rule_changed", "loosens")]
254 assert _effects(_diff(_policy(wider), _policy(ALLOW_NOTES))) == [("rule_changed", "tightens")]
255 filtered = {**ALLOW_NOTES, "row_filter": {"owner_id": "$user_id"}}
256 # A row filter that changes either way cannot be proven to tighten.
257 assert _effects(_diff(_policy(filtered), _policy(ALLOW_NOTES))) == [("rule_changed", "loosens")]
258 assert _effects(_diff(_policy(ALLOW_NOTES), _policy({**ALLOW_NOTES, "reason": "x"}))) == [
259 ("rule_changed", "neutral")]
260 assert _effects(_diff(_policy(), _policy(ALLOW_NOTES))) == [("rule_added", "loosens")]
261 assert _effects(_diff(_policy(), _policy(DENY_NOTES_DELETE))) == [("rule_added", "tightens")]
262 other = {**ALLOW_NOTES, "collection": "tasks"}
263 assert _effects(_diff(_policy(ALLOW_NOTES, other), _policy(other, ALLOW_NOTES))) == [
264 ("rules_reordered", "loosens")]
265
266
267def test_roles_and_access_mode_are_classified():
268 diff = _diff(_policy(user_roles={"7": ["viewer"]}),
269 _policy(user_roles={"7": ["admin"]}, admin_roles=["admin", "superuser", "ops"]))
270 assert sorted(_effects(diff)) == [
271 ("admin_role_added", "loosens"),
272 ("user_role_added", "loosens"),
273 ("user_role_removed", "tightens"),
274 ]
275 assert _effects(_diff(_policy(), {**_policy(), "access_mode": "public"})) == [
276 ("access_mode", "loosens")]
277 assert _effects(_diff({**_policy(), "access_mode": "registered"}, _policy())) == [
278 ("access_mode", "tightens")]
279
280
281def test_field_permissions_are_classified():
282 hidden = {("people", "salary"): ({"role:staff": "hidden"}, "hidden")}
283 readable = {("people", "salary"): ({"role:staff": "read"}, "hidden")}
284 assert _effects(_diff(_policy(), _policy(), hidden, readable)) == [("field_permissions", "loosens")]
285 assert _effects(_diff(_policy(), _policy(), readable, hidden)) == [("field_permissions", "tightens")]
286 # Permissions gone (or the field / schema gone): unrestricted.
287 assert _effects(_diff(_policy(), _policy(), hidden, {})) == [("field_permissions", "loosens")]
288
289
290def test_the_hash_binds_the_difference_and_the_snapshot():
291 diff = _diff(_policy(), _policy(ALLOW_NOTES))
292 same = _diff(_policy(), _policy(ALLOW_NOTES))
293 assert object_policy_diff.policy_diff_hash(diff, change_id="a") == \
294 object_policy_diff.policy_diff_hash(same, change_id="a")
295 assert object_policy_diff.policy_diff_hash(diff, change_id="a") != \
296 object_policy_diff.policy_diff_hash(diff, change_id="b")
297 other = _diff(_policy(), _policy({**ALLOW_NOTES, "actions": ["read"]}))
298 assert object_policy_diff.policy_diff_hash(diff, change_id="a") != \
299 object_policy_diff.policy_diff_hash(other, change_id="a")
300
301
302# --- the CLI restore ---------------------------------------------------------------
303
304def _cli_backup_with_policy(tmp_path, snapshot_policy, live_policy):
305 import object_backup
306
307 objects_dir, data_dir = tmp_path / "objects", tmp_path / "data"
308 write_source(objects_dir / "site" / "home.py", "def GET(request): return {}\n")
309 _write_policy(data_dir, snapshot_policy)
310 backup = tmp_path / "runtime.tar.gz"
311 object_backup.create_runtime_backup(backup, objects_dir=objects_dir, data_dir=data_dir)
312 _write_policy(data_dir, live_policy)
313 return backup, objects_dir, data_dir
314
315
316def _cli(*args):
317 import object_backup
318
319 return object_backup.main(["restore", *map(str, args)])
320
321
322def test_cli_preview_prints_the_policy_difference_and_writes_nothing(tmp_path, capsys):
323 live = _policy(ALLOW_NOTES, DENY_NOTES_DELETE)
324 backup, objects_dir, data_dir = _cli_backup_with_policy(tmp_path, _policy(ALLOW_NOTES), live)
325
326 code = _cli(backup, "--objects-dir", objects_dir, "--data-dir", data_dir, "--preview")
327
328 out = capsys.readouterr().out
329 assert code == 0
330 assert "LOOSENS" in out
331 assert "- [rule removed] deny role:editor delete on collection notes" in out
332 assert json.loads((data_dir / "permissions" / "policy.json").read_text()) == live
333
334 code = _cli(backup, "--objects-dir", objects_dir, "--data-dir", data_dir, "--preview", "--json")
335 payload = json.loads(capsys.readouterr().out)
336 assert code == 0 and payload["policy_diff"]["loosens"] is True
337
338
339def test_cli_overwrite_that_changes_policy_needs_yes(tmp_path, capsys, monkeypatch):
340 live = _policy(ALLOW_NOTES, DENY_NOTES_DELETE)
341 backup, objects_dir, data_dir = _cli_backup_with_policy(tmp_path, _policy(ALLOW_NOTES), live)
342 args = (backup, "--objects-dir", objects_dir, "--data-dir", data_dir, "--overwrite", "--prune-extra")
343
344 # Not a terminal, no --yes: refused after showing the difference.
345 monkeypatch.setattr("sys.stdin.isatty", lambda: False, raising=False)
346 code = _cli(*args)
347 out = capsys.readouterr().out
348 assert code == 1
349 assert "LOOSENS" in out and "--yes" in out
350 assert json.loads((data_dir / "permissions" / "policy.json").read_text()) == live
351
352 code = _cli(*args, "--json")
353 payload = json.loads(capsys.readouterr().out)
354 assert code == 1 and payload["ok"] is False and payload["policy_diff"]["loosens"] is True
355
356 code = _cli(*args, "--yes")
357 capsys.readouterr()
358 assert code == 0
359 assert json.loads((data_dir / "permissions" / "policy.json").read_text())["rules"] == [ALLOW_NOTES]
360
361
362def test_cli_overwrite_asks_on_a_terminal(tmp_path, capsys, monkeypatch):
363 live = _policy(ALLOW_NOTES, DENY_NOTES_DELETE)
364 backup, objects_dir, data_dir = _cli_backup_with_policy(tmp_path, _policy(ALLOW_NOTES), live)
365 args = (backup, "--objects-dir", objects_dir, "--data-dir", data_dir, "--overwrite")
366 monkeypatch.setattr("sys.stdin.isatty", lambda: True, raising=False)
367
368 monkeypatch.setattr("builtins.input", lambda prompt: "no")
369 assert _cli(*args) == 1
370 assert json.loads((data_dir / "permissions" / "policy.json").read_text()) == live
371
372 monkeypatch.setattr("builtins.input", lambda prompt: "yes")
373 assert _cli(*args) == 0
374 capsys.readouterr()
375 assert json.loads((data_dir / "permissions" / "policy.json").read_text())["rules"] == [ALLOW_NOTES]
376
377
378def test_cli_overwrite_refuses_when_the_difference_cannot_be_computed(tmp_path, capsys):
379 backup, objects_dir, data_dir = _cli_backup_with_policy(
380 tmp_path, _policy(ALLOW_NOTES), _policy(ALLOW_NOTES))
381 (data_dir / "permissions" / "policy.json").write_text("{broken")
382
383 code = _cli(backup, "--objects-dir", objects_dir, "--data-dir", data_dir, "--overwrite", "--yes")
384
385 assert code == 1
386 assert "cannot be computed" in capsys.readouterr().out
387 assert (data_dir / "permissions" / "policy.json").read_text() == "{broken"
388
389
390def test_cli_overwrite_without_a_policy_change_asks_nothing(tmp_path, capsys, monkeypatch):
391 same = _policy(ALLOW_NOTES)
392 backup, objects_dir, data_dir = _cli_backup_with_policy(tmp_path, same, same)
393 monkeypatch.setattr("sys.stdin.isatty", lambda: False, raising=False)
394
395 assert _cli(backup, "--objects-dir", objects_dir, "--data-dir", data_dir, "--overwrite") == 0