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_notify_hidden_fields.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_notify_hidden_fields.py · 10.2 KB · 238 lines
1"""Notifications, emails and the activity feed must not tell a user about a
2field they cannot read, through the real app with enforcement on.
3
4A user who may read a ticket but not its `salary_band` (a rule's field list)
5or `subject` (a schema field hidden from the row's owner) used to learn of
6the field anyway:
7
8- a notify rule rendered its template from the whole row, so a notification
9 to that user carried the value;
10- a rule whose `match` names the field fired only when the value matched, so
11 getting it at all was the answer;
12- an update that changed only that field still notified, saying "something
13 changed";
14- the signed-in user's /api/activity entry took its title from the whole
15 snapshot of the row, hidden field included.
16"""
17
18import json
19import shutil
20from pathlib import Path
21
22import pytest
23
24import object_daemon
25import object_identity
26import object_records
27from scripts.try_package import Sandbox
28from test_object_server import request as http_request
29
30REPO = Path(__file__).resolve().parents[1]
31RECORDS = "/collections/tickets/records"
32
33OWN_ROWS = {"effect": "allow", "principal": "registered",
34 "actions": ["create", "read", "update", "delete"], "collection": "tickets",
35 "row_filter": {"owner_id": "$user_id"}, "reason": "own tickets"}
36SUPPORT = {"effect": "allow", "principal": "role:support", "actions": ["read"],
37 "collection": "tickets", "fields": ["id", "title", "owner_id", "status"],
38 "reason": "support sees every ticket, not the salary band"}
39
40
41def _packages(root):
42 for name in ("app-tasks", "app-projects", "app-collab", "app-notify"):
43 shutil.copytree(REPO / "packages" / name, root / name)
44 pkg = root / "tickets"
45 (pkg / "schemas").mkdir(parents=True)
46 (pkg / "permissions").mkdir()
47 (pkg / "dbbasic-package.json").write_text(json.dumps({
48 "id": "tickets", "name": "Tickets", "version": "0.1.0",
49 "schemas": [{"collection": "tickets", "path": "schemas/tickets.json"}],
50 "permissions": [{"path": "permissions/rules.json"}]}))
51 (pkg / "schemas" / "tickets.json").write_text(json.dumps({
52 "name": "tickets", "version": 1,
53 "fields": [{"name": "id"}, {"name": "title", "type": "text"},
54 {"name": "status", "type": "text"},
55 {"name": "salary_band", "type": "text"},
56 {"name": "memo", "type": "text"},
57 {"name": "subject", "type": "text", "permissions": {"owner": "hidden"}},
58 {"name": "owner_id", "type": "text"}]}))
59 (pkg / "permissions" / "rules.json").write_text(json.dumps({"rules": [OWN_ROWS, SUPPORT]}))
60 return root
61
62
63@pytest.fixture(params=[True], ids=["enforcing"])
64def box(tmp_path, request):
65 sandbox = Sandbox(["tickets", "app-notify"], packages_dir=_packages(tmp_path), enforce=request.param)
66 sandbox.__enter__()
67 sandbox.add_user("ann")
68 sandbox.add_user("sam", roles=["support"])
69 yield sandbox
70 sandbox.__exit__(None, None, None)
71
72
73def _rule(box, name, recipients, channels, match=""):
74 object_records.create_collection_record("notify_rules", {
75 "name": name, "enabled": "true", "event_pattern": "tickets.record.updated",
76 "match": match, "recipients": json.dumps(recipients), "suppress_self": "true",
77 "channels": json.dumps(channels)}, base_dir=box.data_dir, actor="admin")
78
79
80def _ticket(box, **fields):
81 row = {"title": "Printer", "status": "open", "salary_band": "A", "owner_id": "ann"}
82 row.update(fields)
83 status, body = box.call("admin", "POST", RECORDS, row)
84 assert status == 201, body
85 return body["record"]["id"]
86
87
88def _notes(box):
89 return object_records.read_collection_records("notifications", base_dir=box.data_dir)
90
91
92def _pass(box):
93 object_daemon.process_notifications(base_dir=box.data_dir) # first call stamps the cursor
94 return object_daemon.process_notifications
95
96
97def test_premise_sam_cannot_read_the_band(box):
98 tid = _ticket(box)
99 status, body = box.call("sam", "GET", f"{RECORDS}/{tid}")
100 assert status == 200 and "salary_band" not in body["record"]
101
102
103def test_notification_body_does_not_carry_a_field_the_recipient_cannot_read(box):
104 tid = _ticket(box)
105 _rule(box, "r", {"mode": "users", "user_ids": ["sam"]},
106 [{"channel": "in_app", "body_template": "{title} ({status}) band={salary_band}"}])
107 run = _pass(box)
108 assert box.call("admin", "PUT", f"{RECORDS}/{tid}", {"status": "closed", "salary_band": "Z"})[0] == 200
109 run(base_dir=box.data_dir)
110 bodies = [n["body"] for n in _notes(box)]
111 assert bodies == ["Printer (closed) band="]
112
113
114def test_update_of_only_a_hidden_field_notifies_nobody(box):
115 tid = _ticket(box)
116 _rule(box, "r", {"mode": "users", "user_ids": ["sam"]},
117 [{"channel": "in_app", "body_template": "{title} changed"}])
118 run = _pass(box)
119 assert box.call("admin", "PUT", f"{RECORDS}/{tid}", {"salary_band": "Z"})[0] == 200
120 run(base_dir=box.data_dir)
121 assert _notes(box) == []
122
123
124def test_match_on_a_hidden_field_does_not_fire_for_a_reader_who_cannot_see_it(box):
125 tid = _ticket(box)
126 _rule(box, "r", {"mode": "users", "user_ids": ["sam"]},
127 [{"channel": "in_app", "body_template": "matched"}],
128 match=json.dumps({"salary_band": "Z"}))
129 run = _pass(box)
130 assert box.call("admin", "PUT", f"{RECORDS}/{tid}", {"salary_band": "Z", "status": "closed"})[0] == 200
131 run(base_dir=box.data_dir)
132 assert _notes(box) == []
133
134
135def test_email_does_not_carry_a_hidden_field_or_fire_on_it(box, monkeypatch):
136 import object_notify
137 tid = _ticket(box)
138 _rule(box, "r", {"mode": "users", "user_ids": ["sam"]},
139 [{"channel": "email", "subject_template": "{title} {salary_band}",
140 "body_template": "band {salary_band}"}])
141 rule = next(r for r in object_records.read_collection_records("notify_rules", base_dir=box.data_dir)
142 if r["name"] == "r")
143 after = {"id": tid, "title": "Printer", "status": "closed", "salary_band": "Z", "owner_id": "ann"}
144 change = {"collection": "tickets", "action": "update", "record_id": tid, "actor": "admin",
145 "changed_fields": ["status", "salary_band"], "after": after}
146 intents = object_notify.email_intents_for_change(rule, change, base_dir=box.data_dir)
147 assert [(i["subject"], i["body"]) for i in intents] == [("Printer ", "band ")]
148 change["changed_fields"] = ["salary_band"]
149 assert object_notify.email_intents_for_change(rule, change, base_dir=box.data_dir) == []
150
151
152def test_recipient_who_may_read_the_row_still_gets_it(box):
153 """The owner reads the whole row (the own-rows rule has no field list)."""
154 tid = _ticket(box)
155 _rule(box, "r", {"mode": "owner"}, [{"channel": "in_app", "body_template": "band {salary_band}"}])
156 run = _pass(box)
157 assert box.call("admin", "PUT", f"{RECORDS}/{tid}", {"salary_band": "Z"})[0] == 200
158 run(base_dir=box.data_dir)
159 assert [n["body"] for n in _notes(box)] == ["band Z"]
160
161
162def test_recipient_with_no_read_on_the_row_gets_nothing(box):
163 box.add_user("bob")
164 tid = _ticket(box)
165 _rule(box, "r", {"mode": "users", "user_ids": ["bob", "ghost"]},
166 [{"channel": "in_app", "body_template": "{title}"}])
167 run = _pass(box)
168 assert box.call("admin", "PUT", f"{RECORDS}/{tid}", {"title": "Scanner"})[0] == 200
169 run(base_dir=box.data_dir)
170 assert _notes(box) == []
171
172
173def test_unreadable_policy_delivers_nothing(box):
174 tid = _ticket(box)
175 _rule(box, "r", {"mode": "owner"}, [{"channel": "in_app", "body_template": "{title}"}])
176 run = _pass(box)
177 assert box.call("admin", "PUT", f"{RECORDS}/{tid}", {"title": "Scanner"})[0] == 200
178 (box.data_dir / "permissions").mkdir(exist_ok=True)
179 import object_permission_store
180 object_permission_store.policy_path(box.data_dir).write_text("{not json")
181 run(base_dir=box.data_dir)
182 assert _notes(box) == []
183
184
185def test_activity_title_is_not_taken_from_a_field_the_caller_cannot_read(box):
186 """ann owns the row but `subject` is hidden from the owner; her own edit of
187 another field must not put the subject in her feed."""
188 tid = _ticket(box, title="", subject="layoff list")
189 status, body = box.call("ann", "GET", f"{RECORDS}/{tid}")
190 assert status == 200 and "subject" not in body["record"]
191 assert box.call("ann", "PUT", f"{RECORDS}/{tid}", {"memo": "hello"})[0] == 200
192 token = object_identity.create_session({"user_id": "ann"}, base_dir=box.data_dir)["token"]
193 status, _, body = http_request("/api/activity", headers=[("authorization", f"Bearer {token}")])
194 assert status == 200
195 assert "layoff list" not in json.dumps(body)
196 assert [e["record_id"] for e in body["activity"]] == [tid]
197
198
199# Delivery follows the record API's mode (object_access.enforcement_enabled) ----
200
201@pytest.fixture()
202def open_box(tmp_path):
203 sandbox = Sandbox(["tickets", "app-notify"], packages_dir=_packages(tmp_path), enforce=False)
204 sandbox.__enter__()
205 sandbox.add_user("ann")
206 sandbox.add_user("sam", roles=["support"])
207 yield sandbox
208 sandbox.__exit__(None, None, None)
209
210
211def test_not_enforcing_delivers_as_before(open_box):
212 """With enforcement off the record API serves sam every field, so nothing
213 is withheld: the whole row renders, a hidden-field-only update notifies,
214 and a recipient id with no user row still gets its notification."""
215 box = open_box
216 tid = _ticket(box)
217 _rule(box, "r", {"mode": "users", "user_ids": ["sam", "nobody-by-that-name"]},
218 [{"channel": "in_app", "body_template": "{title} band={salary_band}"}])
219 run = _pass(box)
220 assert box.call("admin", "PUT", f"{RECORDS}/{tid}", {"salary_band": "Z"})[0] == 200
221 run(base_dir=box.data_dir)
222 assert sorted((n["user_id"], n["body"]) for n in _notes(box)) == [
223 ("nobody-by-that-name", "Printer band=Z"), ("sam", "Printer band=Z")]
224
225
226def test_mode_that_cannot_be_determined_delivers_nothing(box, monkeypatch):
227 import object_access
228 tid = _ticket(box)
229 _rule(box, "r", {"mode": "users", "user_ids": ["sam"]},
230 [{"channel": "in_app", "body_template": "{title}"}])
231 run = _pass(box)
232 assert box.call("admin", "PUT", f"{RECORDS}/{tid}", {"title": "Scanner"})[0] == 200
233
234 def broken():
235 raise OSError("settings unreadable")
236 monkeypatch.setattr(object_access, "enforcement_enabled", broken)
237 run(base_dir=box.data_dir)
238 assert _notes(box) == []