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_create_owner_id.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_create_owner_id.py · 11.8 KB · 287 lines
1"""Who owns a record you create, through HTTP with enforcement on.
2
3Found by a simulated nonprofit: a treasurer (role grant to create
4donations, no row filter) created a donation with `owner_id` naming the
5donor and got 201 -- with the server having silently rewritten owner_id to
6the treasurer. Other runs saw the opposite surprise: a plain member's
7create WITHOUT owner_id was refused "no matching role rule", because the
8rule (`owner_id: $user_id`) was asked about a row with no owner and the
9stamp came after the check.
10
11The rule now (docs/permissions-model.md, "Who owns a record you create"):
12
13- omitted or blank: the caller owns it, stamped before the check;
14- the caller's own id: as sent;
15- someone else's id: kept exactly as sent, and refused unless a rule with
16 `"on_behalf": true` (or an admin role) lets the caller enter records for
17 others. Never silently rewritten.
18- the admin token is not a person: whatever it sends is kept.
19"""
20
21import json
22
23import pytest
24
25import object_permissions
26from scripts.try_package import Sandbox
27
28RECORDS = "/collections/donations/records"
29
30OWN_ROWS = {"effect": "allow", "principal": "registered",
31 "actions": ["create", "read"], "collection": "donations",
32 "row_filter": {"owner_id": "$user_id"},
33 "reason": "members record and read their own pledges"}
34TREASURER = {"effect": "allow", "principal": "role:treasurer",
35 "actions": ["create", "read"], "collection": "donations",
36 "reason": "the treasurer enters donations"}
37
38
39def _package(root, rules):
40 pkg = root / "donations"
41 (pkg / "schemas").mkdir(parents=True)
42 (pkg / "permissions").mkdir()
43 (pkg / "dbbasic-package.json").write_text(json.dumps({
44 "id": "donations", "name": "Donations", "version": "0.1.0",
45 "schemas": [{"collection": "donations", "path": "schemas/donations.json"}],
46 "permissions": [{"path": "permissions/rules.json"}]}))
47 (pkg / "schemas" / "donations.json").write_text(json.dumps({
48 "name": "donations", "version": 1,
49 "fields": [{"name": "id"}, {"name": "amount_cents", "type": "integer"},
50 {"name": "fund", "type": "text"},
51 {"name": "owner_id", "type": "text"}]}))
52 (pkg / "permissions" / "rules.json").write_text(json.dumps({"rules": rules}))
53 return root
54
55
56@pytest.fixture()
57def box_with(tmp_path):
58 boxes = []
59
60 def make(*rules):
61 assert not boxes, "one box per test: a Sandbox sets process environment"
62 box = Sandbox(["donations"], packages_dir=_package(tmp_path, list(rules)))
63 box.__enter__()
64 boxes.append(box)
65 box.add_user("ann")
66 box.add_user("bob")
67 box.add_user("tess", roles=["treasurer"])
68 box.add_user("olive", roles=["admin"])
69 return box
70
71 yield make
72 for box in boxes:
73 box.__exit__(None, None, None)
74
75
76def _rows(box):
77 status, body = box.call("admin", "GET", RECORDS)
78 assert status == 200
79 return body["records"]
80
81
82# -- a plain registered user -------------------------------------------------
83
84def test_a_create_without_owner_id_is_owned_by_the_caller(box_with):
85 """The confusing 403: the member's own-rows rule was asked about a row
86 with no owner. The stamp now happens before the check."""
87 box = box_with(OWN_ROWS)
88 status, body = box.call("ann", "POST", RECORDS, {"amount_cents": 500})
89 assert status == 201, body
90 assert body["record"]["owner_id"] == "ann"
91 status, body = box.call("ann", "POST", RECORDS, {"amount_cents": 500, "owner_id": ""})
92 assert status == 201, body
93 assert body["record"]["owner_id"] == "ann"
94
95
96def test_a_create_naming_the_caller_is_kept(box_with):
97 box = box_with(OWN_ROWS)
98 status, body = box.call("ann", "POST", RECORDS, {"amount_cents": 500, "owner_id": "ann"})
99 assert status == 201, body
100 assert body["record"]["owner_id"] == "ann"
101
102
103UNFILTERED = {"effect": "allow", "principal": "registered",
104 "actions": ["create"], "collection": "donations",
105 "reason": "anyone signed in may pledge"}
106
107
108@pytest.mark.parametrize("rule", [OWN_ROWS, UNFILTERED], ids=["own-rows", "unfiltered"])
109def test_a_registered_user_cannot_create_a_row_owned_by_someone_else(box_with, rule):
110 """Even with a create grant that has no row filter at all: a row owned
111 by bob is bob's to read, change and delete (the owner fallback), so
112 planting one is not a create the member was granted."""
113 box = box_with(rule)
114 status, body = box.call("ann", "POST", RECORDS, {"amount_cents": 1, "owner_id": "bob"})
115 assert status == 403, body
116 assert _rows(box) == []
117
118
119# -- staff entering records for others ---------------------------------------
120
121def test_a_role_without_on_behalf_is_refused_not_rewritten(box_with):
122 """The reported bug: 201 with owner_id quietly changed to the
123 treasurer's own. Now the treasurer is told, and nothing is written."""
124 box = box_with(OWN_ROWS, TREASURER)
125 status, body = box.call("tess", "POST", RECORDS, {"amount_cents": 2500, "owner_id": "bob"})
126 assert status == 403, body
127 assert body["code"] == "forbidden"
128 assert body["field"] == "owner_id"
129 assert "on_behalf" in body["error"]
130 assert _rows(box) == []
131
132
133def test_a_role_granted_on_behalf_creates_the_row_for_its_owner(box_with):
134 box = box_with(OWN_ROWS, {**TREASURER, "on_behalf": True})
135 status, body = box.call("tess", "POST", RECORDS, {"amount_cents": 2500, "owner_id": "bob"})
136 assert status == 201, body
137 assert body["record"]["owner_id"] == "bob"
138 # It is bob's now: his own-rows rule shows it to him, and not to ann.
139 _, mine = box.call("bob", "GET", RECORDS)
140 assert [row["owner_id"] for row in mine["records"]] == ["bob"]
141 _, hers = box.call("ann", "GET", RECORDS)
142 assert hers["records"] == []
143 # Omitting owner_id still means "mine".
144 status, body = box.call("tess", "POST", RECORDS, {"amount_cents": 1})
145 assert status == 201 and body["record"]["owner_id"] == "tess"
146
147
148def test_an_on_behalf_grant_is_bounded_by_its_row_filter(box_with):
149 box = box_with({**TREASURER, "on_behalf": True, "row_filter": {"fund": "general"}})
150 status, _ = box.call("tess", "POST", RECORDS,
151 {"amount_cents": 1, "fund": "general", "owner_id": "bob"})
152 assert status == 201
153 status, _ = box.call("tess", "POST", RECORDS,
154 {"amount_cents": 1, "fund": "building", "owner_id": "bob"})
155 assert status == 403
156
157
158def test_an_explicit_deny_beats_an_on_behalf_grant(box_with):
159 deny = {"effect": "deny", "principal": "role:treasurer", "actions": ["create"],
160 "collection": "donations", "row_filter": {"fund": "restricted"},
161 "reason": "restricted funds are entered by the board"}
162 box = box_with({**TREASURER, "on_behalf": True}, deny)
163 status, _ = box.call("tess", "POST", RECORDS,
164 {"amount_cents": 1, "fund": "restricted", "owner_id": "bob"})
165 assert status == 403
166 assert _rows(box) == []
167
168
169def test_an_admin_may_create_for_anyone(box_with):
170 box = box_with(OWN_ROWS)
171 status, body = box.call("olive", "POST", RECORDS, {"amount_cents": 1, "owner_id": "bob"})
172 assert status == 201, body
173 assert body["record"]["owner_id"] == "bob"
174 status, body = box.call("admin", "POST", RECORDS, {"amount_cents": 1, "owner_id": "bob"})
175 assert status == 201, body
176 assert body["record"]["owner_id"] == "bob"
177
178
179# -- the grant is narrow, and a wrong one is an invalid policy ---------------
180
181@pytest.mark.parametrize("change", [
182 {"principal": "registered"},
183 {"principal": "public"},
184 {"principal": "owner"},
185 {"principal": "subscription:pro"},
186 {"effect": "deny"},
187 {"actions": ["read"]},
188 {"collection": None},
189 {"on_behalf": "yes"},
190 {"on_behalf": 1},
191])
192def test_an_on_behalf_rule_outside_staff_entry_is_refused(change):
193 """Fail closed: a rule that would let a population (everyone signed
194 in, every subscriber) create rows owned by anyone is not a narrower
195 grant that happens to match nothing; it is a policy error."""
196 rule = {**TREASURER, "on_behalf": True, **change}
197 rule = {key: value for key, value in rule.items() if value is not None}
198 with pytest.raises(ValueError):
199 object_permissions.rule_from_dict(rule)
200
201
202def test_on_behalf_round_trips_and_leaves_older_rules_unchanged():
203 rule = object_permissions.rule_from_dict({**TREASURER, "on_behalf": True})
204 assert rule.on_behalf is True
205 assert object_permissions.rule_to_dict(rule)["on_behalf"] is True
206 plain = object_permissions.rule_from_dict(TREASURER)
207 assert "on_behalf" not in object_permissions.rule_to_dict(plain)
208
209
210# -- changing who owns a record on update ------------------------------------
211#
212# Measured before: a role with an unconditional update grant (a billing
213# manager on invoices, a manager on expenses and time logs, an assignee on a
214# task) could PUT owner_id and hand the row to any user, 200. Changing
215# owner_id now needs what creating the row with that owner_id needs.
216
217CLERK = {"effect": "allow", "principal": "role:treasurer",
218 "actions": ["create", "read", "update"], "collection": "donations",
219 "reason": "the treasurer enters and corrects donations"}
220
221
222def _donation(box, owner="bob", fund="general"):
223 status, body = box.call("admin", "POST", RECORDS,
224 {"amount_cents": 100, "fund": fund, "owner_id": owner})
225 assert status == 201, body
226 return body["record"]
227
228
229def _put(box, user, record_id, changes):
230 return box.call(user, "PUT", f"{RECORDS}/{record_id}", changes)
231
232
233def _owner(box, record_id):
234 status, body = box.call("admin", "GET", f"{RECORDS}/{record_id}")
235 assert status == 200, body
236 return body["record"]["owner_id"]
237
238
239@pytest.mark.parametrize("new_owner", ["ann", "tess", ""], ids=["to-another", "to-self", "to-nobody"])
240def test_an_unconditional_update_grant_cannot_change_the_owner(box_with, new_owner):
241 box = box_with(OWN_ROWS, CLERK)
242 row = _donation(box)
243 status, body = _put(box, "tess", row["id"], {"owner_id": new_owner, "fund": "building"})
244 assert status == 403, body
245 assert (body["code"], body["field"]) == ("forbidden", "owner_id")
246 assert _owner(box, row["id"]) == "bob"
247 status, body = box.call("admin", "GET", f"{RECORDS}/{row['id']}")
248 assert body["record"]["fund"] == "general" # nothing of the PUT was written
249
250
251def test_the_same_grant_still_edits_and_may_send_the_owner_back_unchanged(box_with):
252 """An honest client PUTs the whole record it read."""
253 box = box_with(OWN_ROWS, CLERK)
254 row = _donation(box)
255 status, body = _put(box, "tess", row["id"], {**row, "fund": "building"})
256 assert status == 200, body
257 assert (body["record"]["owner_id"], body["record"]["fund"]) == ("bob", "building")
258
259
260def test_an_on_behalf_grant_may_change_the_owner_within_its_row_filter(box_with):
261 box = box_with(OWN_ROWS, {**CLERK, "on_behalf": True, "row_filter": {"fund": "general"}})
262 row = _donation(box)
263 status, body = _put(box, "tess", row["id"], {"owner_id": "ann"})
264 assert status == 200, body
265 assert _owner(box, row["id"]) == "ann"
266 other = _donation(box, fund="building")
267 status, _ = _put(box, "tess", other["id"], {"owner_id": "ann"})
268 assert status == 403
269 assert _owner(box, other["id"]) == "bob"
270
271
272def test_an_admin_may_change_the_owner(box_with):
273 box = box_with(OWN_ROWS, CLERK)
274 row = _donation(box)
275 status, body = _put(box, "olive", row["id"], {"owner_id": "ann"})
276 assert status == 200, body
277 status, body = _put(box, "admin", row["id"], {"owner_id": "tess"})
278 assert status == 200, body
279 assert _owner(box, row["id"]) == "tess"
280
281
282def test_an_owner_still_cannot_give_a_row_away(box_with):
283 box = box_with({**OWN_ROWS, "actions": ["create", "read", "update"]})
284 row = _donation(box, owner="ann")
285 status, _ = _put(box, "ann", row["id"], {"owner_id": "bob"})
286 assert status == 403
287 assert _owner(box, row["id"]) == "ann"