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_comment_moderation.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_comment_moderation.py · 26.6 KB · 527 lines
1"""Comment moderation over the API, by role:moderator, on both comment
2collections: app-thread's thread_comments and app-worker's profile_comments.
3
4Both schemas named `role:moderator` as the editor of `status`, but no rule
5let a moderator update somebody else's comment, so that field permission
6could never be reached and nobody could move a comment's status over the
7API. The packages now grant role:moderator update (and, on profile_comments,
8read of every comment), and the schemas' field permissions make every other
9client-writable field the author's and the admins' alone, so the update can
10change status and nothing else.
11
12Everything here goes through the real HTTP app with enforcement on
13(scripts/try_package.Sandbox). Every Sandbox caller but `admin` is a user
14calling with their own API key, so "the AI moderator" is simply a user who
15holds the moderator role and has an API key and nothing else (never a
16password, never a session): `bot` below.
17
18What each caller can do, before and after (the rows the tests pin):
19
20| caller | before | after |
21|---|---|---|
22| author | reads own comment and its status; cannot set status | unchanged |
23| moderator, someone else's comment | thread: reads it, cannot update; profile: approved rows only | reads every comment and its status, moves status, nothing else |
24| moderator, own comment | edits text, cannot set status | unchanged |
25| other signed-in user / anonymous | published (approved) rows only, no status | unchanged |
26| admin token | reads and writes rows, status hidden | unchanged |
27"""
28
29from __future__ import annotations
30
31import json
32from pathlib import Path
33
34import pytest
35
36import object_access
37import object_attention
38import object_packages
39import object_permission_store
40import object_permissions
41import object_records
42from scripts.try_package import Sandbox, view_rows
43
44PACKAGES = Path(object_packages.__file__).parent / "packages"
45THREAD = "/collections/thread_comments/records"
46
47
48def _seed(box, collection, **row):
49 """A row as an in-process writer leaves it. Over the API nobody can
50 create a comment in any state but the schema default (the author's
51 status is read-only, the admin token's hidden), so a pending
52 thread_comment only comes from a writer like this."""
53 return object_records.create_collection_record(collection, row, base_dir=box.data_dir)
54
55
56def _stored(box, collection, record_id):
57 return object_records.get_collection_record(collection, record_id, base_dir=box.data_dir)
58
59
60def _attention(package_id, attention_id, box, identity):
61 manifest = json.loads((PACKAGES / package_id / "dbbasic-package.json").read_text())
62 [entry] = [e for e in object_packages._normalize_attention(
63 manifest["attention"], package_id=package_id) if e["id"] == attention_id]
64 access = object_access.Access(identity, base_dir=box.data_dir)
65 return object_attention.count(object_attention.declaration_from_source(entry),
66 access, base_dir=box.data_dir)["count"]
67
68
69def _without_moderator_writes(policy, collection):
70 """The policy as it was before this change: no moderator update (and,
71 for profile_comments, no moderator read) rule on `collection`."""
72 return object_permissions.PermissionPolicy(
73 access_mode=policy.access_mode,
74 rules=tuple(r for r in policy.rules
75 if not (r.principal == "role:moderator" and r.collection == collection
76 and ("update" in r.actions or collection == "profile_comments"))),
77 roles=policy.roles, user_roles=policy.user_roles, admin_roles=policy.admin_roles)
78
79
80def _decisions(policy, subject, collection, rows):
81 return [(row["id"], action, object_permissions.check_permission(
82 subject, action, policy=policy, collection=collection, record=row).allowed)
83 for row in rows for action in ("read", "update", "delete")]
84
85
86# =============================================================================
87# thread_comments (app-thread)
88# =============================================================================
89
90@pytest.fixture()
91def thread():
92 with Sandbox(["app-thread"]) as box:
93 box.add_user("ann") # the author
94 box.add_user("bob") # signed in, no role
95 box.add_user("mo", roles=["moderator"]) # a person who moderates
96 box.add_user("bot", roles=["moderator"]) # an AI agent: a key and the role
97 common = {"parent_collection": "notes", "parent_id": "n1"}
98 _seed(box, "thread_comments", id="c-pub", body="hello", owner_id="ann",
99 status="published", **common)
100 _seed(box, "thread_comments", id="c-wait", body="please approve", owner_id="ann",
101 status="pending", **common)
102 _seed(box, "thread_comments", id="c-wait2", body="me too", owner_id="ann",
103 status="pending", **common)
104 _seed(box, "thread_comments", id="c-mine", body="mo's own", owner_id="mo",
105 status="pending", **common)
106 yield box
107
108
109def test_a_moderator_lists_the_pending_queue_with_status(thread):
110 status, body = thread.call("mo", "GET", f"{THREAD}?status=pending")
111 assert status == 200, body
112 rows = {r["id"]: r for r in body["records"]}
113 assert set(rows) == {"c-wait", "c-wait2", "c-mine"}
114 assert {r["status"] for r in rows.values()} == {"pending"}
115 assert rows["c-wait"]["body"] == "please approve"
116
117
118def test_a_moderator_approves_and_rejects_someone_elses_comment(thread):
119 status, body = thread.call("mo", "PUT", f"{THREAD}/c-wait", {"status": "published"})
120 assert status == 200, body
121 assert body["record"]["status"] == "published"
122 status, body = thread.call("mo", "PUT", f"{THREAD}/c-wait2", {"status": "removed"})
123 assert status == 200, body
124 # Others now see the approved one and not the rejected one.
125 status, body = thread.call("bob", "GET", THREAD)
126 assert sorted(r["id"] for r in body["records"]) == ["c-pub", "c-wait"]
127 # The author still sees their rejected comment, and that it was removed.
128 status, body = thread.call("ann", "GET", f"{THREAD}/c-wait2")
129 assert (status, body["record"]["status"]) == (200, "removed")
130
131
132def test_the_moves_a_moderator_may_make_are_the_declared_ones(thread):
133 # un-approving is declared: published -> flagged -> published, -> removed
134 assert thread.call("mo", "PUT", f"{THREAD}/c-pub", {"status": "flagged"})[0] == 200
135 assert thread.call("mo", "PUT", f"{THREAD}/c-pub", {"status": "published"})[0] == 200
136 assert thread.call("mo", "PUT", f"{THREAD}/c-pub", {"status": "removed"})[0] == 200
137 # removed is terminal, and nothing goes back to pending
138 status, body = thread.call("mo", "PUT", f"{THREAD}/c-pub", {"status": "published"})
139 assert status == 400, body
140 status, body = thread.call("mo", "PUT", f"{THREAD}/c-wait", {"status": "flagged"})
141 assert status == 200
142 status, body = thread.call("mo", "PUT", f"{THREAD}/c-wait", {"status": "pending"})
143 assert status == 400, body
144 assert _stored(thread, "thread_comments", "c-wait")["status"] == "flagged"
145
146
147@pytest.mark.parametrize("change", [
148 {"body": "rewritten by a moderator"},
149 {"author_name": "Someone Else"},
150 {"parent_collection": "tasks"},
151 {"parent_id": "n2"},
152 {"reply_to_id": "c-pub"},
153 {"owner_id": "mo"},
154 {"status": "published", "body": "approved, and also rewritten"},
155])
156def test_a_moderator_cannot_change_anything_but_status(thread, change):
157 before = _stored(thread, "thread_comments", "c-wait")
158 status, body = thread.call("mo", "PUT", f"{THREAD}/c-wait", change)
159 assert status == 403, body
160 assert _stored(thread, "thread_comments", "c-wait") == before
161
162
163def test_a_moderator_cannot_delete_someone_elses_comment(thread):
164 status, _ = thread.call("mo", "DELETE", f"{THREAD}/c-wait")
165 assert status in (403, 404)
166 assert _stored(thread, "thread_comments", "c-wait")["status"] == "pending"
167
168
169def test_a_moderator_cannot_approve_their_own_comment(thread):
170 status, body = thread.call("mo", "PUT", f"{THREAD}/c-mine", {"status": "published"})
171 assert status == 403 and body["denied_fields"] == ["status"]
172 assert _stored(thread, "thread_comments", "c-mine")["status"] == "pending"
173 # ... and still writes and edits their own comments like anyone else.
174 status, body = thread.call("mo", "PUT", f"{THREAD}/c-mine", {"body": "mo's own, edited"})
175 assert status == 200, body
176 status, body = thread.call("mo", "POST", THREAD,
177 {"parent_collection": "notes", "parent_id": "n1", "body": "new"})
178 assert status == 201, body
179
180
181def test_an_ai_agent_with_only_an_api_key_and_the_role_moderates(thread):
182 status, body = thread.call("bot", "GET", f"{THREAD}?status=pending")
183 assert status == 200
184 assert sorted(r["id"] for r in body["records"]) == ["c-mine", "c-wait", "c-wait2"]
185 assert thread.call("bot", "PUT", f"{THREAD}/c-wait", {"status": "published"})[0] == 200
186 assert thread.call("bot", "PUT", f"{THREAD}/c-wait2", {"status": "removed"})[0] == 200
187 # c-mine is mo's, not bot's: another moderator may decide it.
188 assert thread.call("bot", "PUT", f"{THREAD}/c-mine", {"status": "published"})[0] == 200
189 status, body = thread.call("bot", "PUT", f"{THREAD}/c-pub", {"body": "spam link"})
190 assert status == 403 and body["denied_fields"] == ["body"]
191
192
193def test_the_author_another_user_and_a_visitor_cannot_set_status(thread):
194 status, body = thread.call("ann", "PUT", f"{THREAD}/c-wait", {"status": "published"})
195 assert status == 403 and body["denied_fields"] == ["status"]
196 assert thread.call("ann", "PUT", f"{THREAD}/c-wait", {"body": "fixed typo"})[0] == 200
197 # 403 on a row bob cannot read is what it was before (the update path does
198 # not answer an unreadable row as missing); only the status refusal matters.
199 assert thread.call("bob", "PUT", f"{THREAD}/c-wait", {"status": "published"})[0] == 403
200 assert thread.call("bob", "PUT", f"{THREAD}/c-pub", {"status": "removed"})[0] == 403
201 assert thread.call(None, "PUT", f"{THREAD}/c-pub", {"status": "removed"})[0] in (401, 403)
202 assert _stored(thread, "thread_comments", "c-wait")["status"] == "pending"
203 assert _stored(thread, "thread_comments", "c-pub")["status"] == "published"
204
205
206def test_what_the_author_another_user_and_a_visitor_read_is_unchanged(thread):
207 status, body = thread.call("ann", "GET", THREAD)
208 assert sorted((r["id"], r["status"]) for r in body["records"]) == [
209 ("c-pub", "published"), ("c-wait", "pending"), ("c-wait2", "pending")]
210 status, body = thread.call("bob", "GET", THREAD)
211 assert [r["id"] for r in body["records"]] == ["c-pub"]
212 assert "status" not in body["records"][0] and "owner_id" not in body["records"][0]
213 assert thread.call(None, "GET", THREAD)[0] in (401, 403)
214
215
216def test_the_admin_token_is_unchanged(thread):
217 """It reads every row with status hidden (status names the author and
218 moderators only), cannot set status, and still edits the text."""
219 status, body = thread.call("admin", "GET", f"{THREAD}/c-wait")
220 assert status == 200 and "status" not in body["record"]
221 status, body = thread.call("admin", "PUT", f"{THREAD}/c-wait", {"status": "published"})
222 assert status == 403 and body["denied_fields"] == ["status"]
223 status, body = thread.call("admin", "PUT", f"{THREAD}/c-wait", {"body": "edited by staff"})
224 assert status == 200, body
225
226
227def test_a_user_without_the_role_gains_nothing_from_the_new_rules(thread):
228 policy = object_permission_store.load_policy(thread.data_dir)
229 before = _without_moderator_writes(policy, "thread_comments")
230 assert len(before.rules) == len(policy.rules) - 1
231 rows = object_records.read_collection_records("thread_comments", base_dir=thread.data_dir)
232 for user_id in ("ann", "bob"):
233 subject = object_permissions.PermissionSubject(user_id=user_id)
234 assert _decisions(policy, subject, "thread_comments", rows) == \
235 _decisions(before, subject, "thread_comments", rows)
236 anonymous = object_permissions.PermissionSubject()
237 assert _decisions(policy, anonymous, "thread_comments", rows) == \
238 _decisions(before, anonymous, "thread_comments", rows)
239
240
241def test_moderators_have_an_attention_count_of_other_peoples_pending_comments(thread):
242 count = lambda identity: _attention("app-thread", "thread_comments_to_moderate",
243 thread, identity)
244 assert count({"user_id": "mo", "roles": ["moderator"]}) == 2 # not c-mine
245 assert count({"user_id": "bot", "roles": ["moderator"]}) == 3 # c-mine is mo's
246 assert count({"user_id": "ann"}) == 0 # her own are not a queue
247 assert count({"user_id": "bob"}) == 0
248 thread.call("mo", "PUT", f"{THREAD}/c-wait", {"status": "published"})
249 assert count({"user_id": "mo", "roles": ["moderator"]}) == 1
250
251
252
253def test_the_count_opens_a_page_listing_the_pending_queue(thread):
254 manifest = json.loads((PACKAGES / "app-thread" / "dbbasic-package.json").read_text())
255 [entry] = manifest["attention"]
256 assert entry["path"] == "/comments/pending"
257 lines = view_rows(thread, "mo", entry["path"])
258 assert lines[1].startswith(" list thread_comments as mo: 3 row(s)"), lines
259 assert sorted(line.strip() for line in lines[2:]) == ["me too", "mo's own", "please approve"]
260 # Without the role the page shows nothing: status is not a field the
261 # author, another user or a visitor may filter on, so the list is refused
262 # (the page says "Not available"). The admin token sees the list, as it
263 # reads every comment over the API.
264 for who in ("ann", "bob", "anon"):
265 assert "Not available" in view_rows(thread, who, entry["path"])[1], who
266 assert view_rows(thread, "admin", entry["path"])[1].startswith(
267 " list thread_comments as admin: 3 row(s)")
268
269# =============================================================================
270# profile_comments (app-worker)
271# =============================================================================
272
273GUESTBOOK = "/collections/profile_comments/records"
274
275
276@pytest.fixture()
277def guestbook():
278 with Sandbox(["app-worker"]) as box:
279 box.add_user("ann")
280 box.add_user("bob")
281 box.add_user("mo", roles=["moderator"])
282 box.add_user("bot", roles=["moderator"])
283 status, body = box.call("admin", "POST", "/collections/profiles/records",
284 {"owner_id": "pat", "display_name": "Pat", "slug": "pat"})
285 assert status == 201, body
286 box.profile_id = body["record"]["id"]
287 box.ids = {}
288 # Every comment lands pending, over the API, as its author wrote it.
289 for name, author, text in (("wait", "ann", "please approve"),
290 ("wait2", "ann", "me too"),
291 ("mine", "mo", "mo's own")):
292 status, body = box.call(author, "POST", GUESTBOOK,
293 {"profile_id": box.profile_id, "content": text})
294 assert status == 201 and body["record"]["status"] == "pending", body
295 box.ids[name] = body["record"]["id"]
296 yield box
297
298
299def _path(box, name):
300 return f"{GUESTBOOK}/{box.ids[name]}"
301
302
303def _row(box, name):
304 return _stored(box, "profile_comments", box.ids[name])
305
306
307def test_a_moderator_lists_the_pending_guestbook_queue(guestbook):
308 status, body = guestbook.call("mo", "GET", f"{GUESTBOOK}?status=pending")
309 assert status == 200, body
310 rows = {r["id"]: r for r in body["records"]}
311 assert set(rows) == set(guestbook.ids.values())
312 assert {r["status"] for r in rows.values()} == {"pending"}
313
314
315def test_a_moderator_approves_and_rejects_someone_elses_guestbook_comment(guestbook):
316 status, body = guestbook.call("mo", "PUT", _path(guestbook, "wait"), {"status": "approved"})
317 assert status == 200, body
318 assert body["record"]["status"] == "approved"
319 status, body = guestbook.call("mo", "PUT", _path(guestbook, "wait2"), {"status": "rejected"})
320 assert status == 200, body
321 for who in ("bob", None):
322 status, body = guestbook.call(who, "GET", GUESTBOOK)
323 assert [r["id"] for r in body["records"]] == [guestbook.ids["wait"]]
324 status, body = guestbook.call("ann", "GET", _path(guestbook, "wait2"))
325 assert (status, body["record"]["status"]) == (200, "rejected")
326
327
328def test_the_guestbook_moves_a_moderator_may_make_are_the_declared_ones(guestbook):
329 path = _path(guestbook, "wait")
330 assert guestbook.call("mo", "PUT", path, {"status": "approved"})[0] == 200
331 # un-approving is declared, to rejected; rejected is final; nothing returns to pending
332 assert guestbook.call("mo", "PUT", path, {"status": "pending"})[0] == 400
333 assert guestbook.call("mo", "PUT", path, {"status": "rejected"})[0] == 200
334 assert guestbook.call("mo", "PUT", path, {"status": "approved"})[0] == 400
335 assert _row(guestbook, "wait")["status"] == "rejected"
336
337
338@pytest.mark.parametrize("change", [
339 {"content": "rewritten by a moderator"},
340 {"author_name": "Someone Else"},
341 {"author_url": "https://example.test/spam"},
342 {"author_email": "x@example.test"},
343 {"profile_id": "another-profile"},
344 {"owner_id": "mo"},
345 {"owner_id": "bob"},
346 {"status": "approved", "content": "approved, and also rewritten"},
347])
348def test_a_moderator_cannot_change_anything_but_status_on_the_guestbook(guestbook, change):
349 before = _row(guestbook, "wait")
350 status, body = guestbook.call("mo", "PUT", _path(guestbook, "wait"), change)
351 assert status == 403, body
352 assert _row(guestbook, "wait") == before
353
354
355def test_a_moderator_cannot_delete_someone_elses_guestbook_comment(guestbook):
356 assert guestbook.call("mo", "DELETE", _path(guestbook, "wait"))[0] in (403, 404)
357 assert _row(guestbook, "wait")["status"] == "pending"
358
359
360def test_a_moderator_cannot_approve_their_own_guestbook_comment(guestbook):
361 for target in ("approved", "rejected"):
362 status, body = guestbook.call("mo", "PUT", _path(guestbook, "mine"), {"status": target})
363 assert status == 403 and body["denied_fields"] == ["status"]
364 assert _row(guestbook, "mine")["status"] == "pending"
365 status, body = guestbook.call("mo", "PUT", _path(guestbook, "mine"), {"content": "edited"})
366 assert status == 200, body
367
368
369def test_an_ai_agent_with_only_an_api_key_and_the_role_moderates_the_guestbook(guestbook):
370 status, body = guestbook.call("bot", "GET", f"{GUESTBOOK}?status=pending")
371 assert status == 200 and len(body["records"]) == 3
372 assert guestbook.call("bot", "PUT", _path(guestbook, "wait"), {"status": "approved"})[0] == 200
373 assert guestbook.call("bot", "PUT", _path(guestbook, "wait2"), {"status": "rejected"})[0] == 200
374 assert guestbook.call("bot", "PUT", _path(guestbook, "mine"), {"status": "approved"})[0] == 200
375 status, body = guestbook.call("bot", "PUT", _path(guestbook, "wait"), {"content": "spam"})
376 assert status == 403 and body["denied_fields"] == ["content"]
377
378
379def test_the_author_another_user_and_a_visitor_cannot_set_guestbook_status(guestbook):
380 path = _path(guestbook, "wait")
381 status, body = guestbook.call("ann", "PUT", path, {"status": "approved"})
382 assert status == 403 and body["denied_fields"] == ["status"]
383 assert guestbook.call("ann", "PUT", path, {"content": "fixed typo"})[0] == 200
384 assert guestbook.call("bob", "PUT", path, {"status": "approved"})[0] == 403
385 assert guestbook.call(None, "PUT", path, {"status": "approved"})[0] in (401, 403)
386 assert _row(guestbook, "wait")["status"] == "pending"
387
388
389def test_what_the_author_another_user_and_a_visitor_read_on_the_guestbook_is_unchanged(guestbook):
390 status, body = guestbook.call("ann", "GET", GUESTBOOK)
391 assert sorted(r["status"] for r in body["records"]) == ["pending", "pending"]
392 for who in ("bob", None):
393 status, body = guestbook.call(who, "GET", GUESTBOOK)
394 assert (status, body["records"]) == (200, [])
395 assert guestbook.call(who, "GET", _path(guestbook, "wait"))[0] == 404
396
397
398def test_the_admin_token_is_unchanged_on_the_guestbook(guestbook):
399 status, body = guestbook.call("admin", "GET", _path(guestbook, "wait"))
400 assert status == 200 and "status" not in body["record"]
401 status, body = guestbook.call("admin", "PUT", _path(guestbook, "wait"), {"status": "approved"})
402 assert status == 403 and body["denied_fields"] == ["status"]
403 status, body = guestbook.call("admin", "PUT", _path(guestbook, "wait"), {"content": "staff edit"})
404 assert status == 200, body
405
406
407def test_a_user_without_the_role_gains_nothing_from_the_new_guestbook_rules(guestbook):
408 policy = object_permission_store.load_policy(guestbook.data_dir)
409 before = _without_moderator_writes(policy, "profile_comments")
410 assert len(before.rules) == len(policy.rules) - 2
411 rows = object_records.read_collection_records("profile_comments", base_dir=guestbook.data_dir)
412 for subject in (object_permissions.PermissionSubject(user_id="ann"),
413 object_permissions.PermissionSubject(user_id="bob"),
414 object_permissions.PermissionSubject()):
415 assert _decisions(policy, subject, "profile_comments", rows) == \
416 _decisions(before, subject, "profile_comments", rows)
417
418
419def test_moderators_have_an_attention_count_of_other_peoples_pending_guestbook_comments(guestbook):
420 count = lambda identity: _attention("app-worker", "profile_comments_to_moderate",
421 guestbook, identity)
422 assert count({"user_id": "mo", "roles": ["moderator"]}) == 2
423 assert count({"user_id": "bot", "roles": ["moderator"]}) == 3
424 assert count({"user_id": "ann"}) == 0
425 assert count({"user_id": "bob"}) == 0
426 guestbook.call("mo", "PUT", _path(guestbook, "wait"), {"status": "approved"})
427 assert count({"user_id": "mo", "roles": ["moderator"]}) == 1
428
429
430
431def test_the_guestbook_count_opens_a_page_listing_the_pending_queue(guestbook):
432 manifest = json.loads((PACKAGES / "app-worker" / "dbbasic-package.json").read_text())
433 [entry] = manifest["attention"]
434 assert entry["path"] == "/guestbook/pending"
435 lines = view_rows(guestbook, "mo", entry["path"])
436 assert lines[1].startswith(" list profile_comments as mo: 3 row(s)"), lines
437 for who in ("ann", "bob", "anon"):
438 assert "Not available" in view_rows(guestbook, who, entry["path"])[1], who
439
440# =============================================================================
441# Upgrading a box that has the previous version of either package
442# =============================================================================
443
444# The commenters' rule's reason as app-worker 0.1.x shipped it. The installer
445# matches rules on everything but `reason` (object_packages._rule_merge_key),
446# so the rule's new reason is not a different rule: no retraction, no second
447# copy, and an upgraded box keeps this text until someone edits it.
448OLD_WORKER_REASON = (
449 "v1 guestbook posting is signed-in only (see schemas/profile_comments.json and "
450 "dbbasic-package.json for the deferred anonymous path); a commenter manages their own "
451 "comment, including its own pending/approved/rejected moves via the schema's guarded "
452 "transitions -- this is the same cross-user moderation gap app-forum documents: the "
453 "PROFILE owner cannot moderate someone ELSE's comment through this rule, only the "
454 "commenter can move their own")
455
456NEW_RULES = {"app-thread": ("thread_comments", {("role:moderator", ("update",))}),
457 "app-worker": ("profile_comments", {("role:moderator", ("read",)),
458 ("role:moderator", ("update",))})}
459
460
461def _previous_version(package_id, root):
462 """The package as its previous version shipped its rules: copied, with the
463 moderator rules, the attention count and the app-nav dependency taken out
464 and the commenters' old reason put back."""
465 import shutil
466 shutil.copytree(PACKAGES / package_id, root / package_id)
467 collection, added = NEW_RULES[package_id]
468 rules_path = root / package_id / "permissions" / "rules.json"
469 payload = json.loads(rules_path.read_text())
470 payload["rules"] = [r for r in payload["rules"]
471 if (r["principal"], tuple(r["actions"])) not in added
472 or r.get("collection") != collection]
473 for rule in payload["rules"]:
474 if (package_id == "app-worker" and rule["principal"] == "registered"
475 and rule.get("collection") == "profile_comments"):
476 rule["reason"] = OLD_WORKER_REASON
477 rules_path.write_text(json.dumps(payload))
478 manifest_path = root / package_id / "dbbasic-package.json"
479 manifest = json.loads(manifest_path.read_text())
480 manifest.pop("attention")
481 manifest["dependencies"] = []
482 manifest_path.write_text(json.dumps(manifest))
483
484
485def _key(rule):
486 return object_packages._rule_merge_key(rule)
487
488
489@pytest.mark.parametrize("package_id", sorted(NEW_RULES))
490@pytest.mark.parametrize("recorded_baseline", [True, False])
491def test_reinstalling_over_the_previous_version_leaves_each_rule_once(
492 package_id, recorded_baseline, tmp_path):
493 old_root, data, objects = tmp_path / "old", tmp_path / "data", tmp_path / "objects"
494 objects.mkdir()
495 _previous_version(package_id, old_root)
496 object_packages.install_package(package_id, root=old_root, base_dir=data,
497 object_roots=[objects])
498 if not recorded_baseline: # a box from before baselines recorded rules
499 import object_package_baselines
500 path = object_package_baselines.baseline_path(package_id, base_dir=data)
501 baseline = json.loads(path.read_text())
502 baseline.pop("permissions", None)
503 path.write_text(json.dumps(baseline))
504 collection, added = NEW_RULES[package_id]
505 live = object_permission_store.load_policy(data).rules
506 assert not [r for r in live if (r.principal, tuple(sorted(r.actions))) in added
507 and r.collection == collection]
508
509 for _ in range(2): # the upgrade, then a reinstall of the same version
510 result = object_packages.install_package(
511 package_id, root=PACKAGES, base_dir=data, object_roots=[objects],
512 allow_replace=True)
513 assert result["permission_retractions"] == []
514
515 live = object_permission_store.load_policy(data).rules
516 mine = [r for r in live if r.package == package_id]
517 assert len({_key(r) for r in mine}) == len(mine) # no duplicates
518 shipped_rules = json.loads(
519 (PACKAGES / package_id / "permissions" / "rules.json").read_text())["rules"]
520 assert sorted(_key(object_permissions.rule_from_dict(r)) for r in shipped_rules) == \
521 sorted(_key(r) for r in mine) # nothing left over
522 assert {(r.principal, tuple(sorted(r.actions))) for r in mine
523 if r.collection == collection} >= added
524 if package_id == "app-worker":
525 [commenters] = [r for r in mine if r.principal == "registered"
526 and r.collection == "profile_comments"]
527 assert commenters.reason == OLD_WORKER_REASON