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_user_object_access_modes.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_user_object_access_modes.py · 16.0 KB · 403 lines
1"""The access mode alone never opens a user object to anyone but its owner.
2
3`public`, `registered` and `subscription` allow read and execute without a
4rule, on whatever object the gate is asked about. A user object
5`u_<id>_<name>` is private to user <id> (docs/http-api-contract.md "User
6objects"); /objects/{id} answers a non-owner 404 before the gate is asked,
7but a site route pointing at the object asked the gate, and the mode said
8yes: the object ran for an anonymous caller.
9
10For a user object the mode now grants to the owner only. Everyone else
11needs what they need in `role_based`: an admin role, or a rule naming the
12`object_id`. Nothing refused before is allowed now.
13"""
14
15import asyncio
16import json
17
18import pytest
19
20import object_permission_store
21import object_permissions
22import object_server
23
24
25def policy(*rules, access_mode):
26 return object_permissions.policy_from_dict({"access_mode": access_mode, "rules": list(rules)})
27
28
29def decide(subject, action, object_id, *rules, access_mode):
30 return object_server._object_permission_decision(
31 subject, action, policy(*rules, access_mode=access_mode), object_id)
32
33
34ANONYMOUS = object_permissions.PermissionSubject.anonymous()
35OWNER = object_permissions.PermissionSubject(user_id="1", subscriptions=("pro",))
36OTHER = object_permissions.PermissionSubject(
37 user_id="2", roles=("member",), subscriptions=("pro",))
38ADMIN = object_permissions.PermissionSubject(user_id="3", roles=("admin",))
39
40OPEN_MODES = ["public", "registered", "subscription"]
41EVERY_MODE = OPEN_MODES + ["password", "role_based", "private"]
42NOT_SHARED = "user object is not shared with this caller"
43
44
45@pytest.mark.parametrize("mode", OPEN_MODES)
46@pytest.mark.parametrize("action", ["read", "execute"])
47def test_open_mode_does_not_grant_a_user_object_to_another_user(mode, action):
48 decision = decide(OTHER, action, "u_1_x", access_mode=mode)
49
50 assert not decision.allowed
51 assert decision.reason == NOT_SHARED
52 assert decision.http_status == 403
53
54
55def test_public_mode_does_not_grant_a_user_object_to_an_anonymous_caller():
56 decision = decide(ANONYMOUS, "execute", "u_1_x", access_mode="public")
57
58 assert not decision.allowed
59 assert decision.reason == NOT_SHARED
60
61
62@pytest.mark.parametrize("mode,status", [("registered", 401), ("subscription", 402)])
63def test_refusals_the_mode_already_gave_are_unchanged(mode, status):
64 # An anonymous caller was refused by the mode itself; that answer stays.
65 assert decide(ANONYMOUS, "execute", "u_1_x", access_mode=mode).http_status == status
66 assert decide(OTHER, "update", "u_1_x", access_mode="public").reason == (
67 "public access is read-only")
68
69
70@pytest.mark.parametrize("mode", OPEN_MODES)
71def test_open_mode_still_grants_system_objects(mode):
72 assert decide(OTHER, "execute", "tools_cli", access_mode=mode).allowed
73 assert decide(OTHER, "read", "x", access_mode=mode).allowed
74
75
76def test_public_mode_still_grants_system_objects_to_anonymous():
77 assert decide(ANONYMOUS, "execute", "tools_cli", access_mode="public").allowed
78
79
80@pytest.mark.parametrize("mode", OPEN_MODES)
81@pytest.mark.parametrize("action", ["read", "execute", "update", "delete"])
82def test_owner_keeps_their_object_in_every_open_mode(mode, action):
83 assert decide(OWNER, action, "u_1_x", access_mode=mode).allowed
84
85
86@pytest.mark.parametrize("mode", EVERY_MODE)
87def test_admin_role_is_still_decided_first(mode):
88 decision = decide(ADMIN, "execute", "u_1_x", access_mode=mode)
89
90 assert decision.allowed
91 assert decision.reason == "admin role"
92
93
94@pytest.mark.parametrize("mode", OPEN_MODES)
95def test_rule_naming_the_object_still_shares_it(mode):
96 share = {"effect": "allow", "principal": "user:2", "actions": ["read"],
97 "object_id": "u_1_x", "reason": "shared by owner"}
98
99 decision = decide(OTHER, "read", "u_1_x", share, access_mode=mode)
100
101 assert decision.allowed
102 assert decision.reason == "shared by owner"
103 assert not decide(OTHER, "execute", "u_1_x", share, access_mode=mode).allowed
104 assert not decide(OTHER, "read", "u_1_y", share, access_mode=mode).allowed
105
106
107def test_public_rule_naming_the_object_shares_it_with_anonymous():
108 share = {"effect": "allow", "principal": "public", "actions": ["execute"],
109 "object_id": "u_1_x"}
110
111 assert decide(ANONYMOUS, "execute", "u_1_x", share, access_mode="public").allowed
112 assert decide(ANONYMOUS, "execute", "u_1_x", share, access_mode="role_based").allowed
113
114
115@pytest.mark.parametrize("mode", OPEN_MODES)
116def test_deny_rules_still_refuse_first(mode):
117 deny = {"effect": "deny", "principal": "registered", "actions": ["execute"],
118 "object_id": "u_1_x", "reason": "switched off"}
119 share = {"effect": "allow", "principal": "user:2", "actions": ["execute"],
120 "object_id": "u_1_x"}
121
122 assert decide(OTHER, "execute", "u_1_x", deny, share, access_mode=mode).reason == (
123 "switched off")
124 assert decide(OWNER, "execute", "u_1_x", deny, access_mode=mode).reason == "switched off"
125
126
127@pytest.mark.parametrize("mode", EVERY_MODE)
128@pytest.mark.parametrize("subject", [ANONYMOUS, OTHER, OWNER, ADMIN])
129@pytest.mark.parametrize("action", ["read", "execute", "update", "delete", "source", "share"])
130@pytest.mark.parametrize("object_id", ["u_1_x", "u_1_tools_cli", "tools_cli"])
131def test_nothing_refused_by_the_policy_engine_is_allowed_now(mode, subject, action, object_id):
132 rules = [
133 {"effect": "allow", "principal": "user:2", "actions": ["read"], "object_id": "u_1_x"},
134 {"effect": "allow", "principal": "role:member", "actions": ["execute"]},
135 ]
136 active = policy(*rules, access_mode=mode)
137
138 before = object_permissions.check_permission(
139 subject, action, policy=active,
140 collection=object_server._object_collection(object_id), object_id=object_id)
141 after = object_server._object_permission_decision(subject, action, active, object_id)
142
143 assert before.allowed or not after.allowed
144 if object_permissions.parse_user_object_id(object_id) is None:
145 assert after == before
146
147
148def call(path, headers=None):
149 sent = {}
150
151 async def run():
152 scope = {
153 "type": "http", "method": "GET", "path": path, "query_string": b"",
154 "headers": [(k.lower().encode(), v.encode()) for k, v in (headers or {}).items()],
155 }
156
157 async def receive():
158 return {"type": "http.request", "body": b"", "more_body": False}
159
160 async def send(message):
161 if message["type"] == "http.response.start":
162 sent["status"] = message["status"]
163 elif message["type"] == "http.response.body":
164 sent["body"] = sent.get("body", b"") + message.get("body", b"")
165
166 await object_server.app(scope, receive, send)
167
168 asyncio.run(run())
169 return sent
170
171
172@pytest.fixture
173def site(tmp_path, monkeypatch):
174 objects_dir = tmp_path / "objects"
175 data_dir = tmp_path / "data"
176 (objects_dir / "users" / "1").mkdir(parents=True)
177 (objects_dir / "tools").mkdir(parents=True)
178 source = "def GET(request):\n return {'ran': True}\n"
179 (objects_dir / "users" / "1" / "x.py").write_text(source)
180 (objects_dir / "tools" / "cli.py").write_text(source)
181 routes = data_dir / "collections" / "site_routes" / "records.tsv"
182 routes.parent.mkdir(parents=True)
183 routes.write_text(
184 "id\tpattern\tobject_id\n"
185 "r1\t/private-tool\tu_1_x\n"
186 "r2\t/public-tool\ttools_cli\n"
187 )
188 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_dir))
189 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
190 monkeypatch.setenv("DBBASIC_ENABLE_SITE_ROUTES", "true")
191 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
192 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
193
194 def set_policy(access_mode, *rules):
195 object_permission_store.replace_policy(
196 {"access_mode": access_mode, "rules": list(rules)}, data_dir)
197
198 return set_policy
199
200
201USER_2 = {"X-DBBasic-User-Id": "2"}
202
203
204def test_public_mode_site_route_to_a_user_object_refuses_an_anonymous_caller(site):
205 site("public")
206
207 private = call("/private-tool")
208 public = call("/public-tool")
209
210 assert private["status"] == 403
211 assert json.loads(private["body"])["error"] == NOT_SHARED
212 assert b"ran" not in private["body"]
213 assert public["status"] == 200
214 assert json.loads(public["body"])["ran"] is True
215
216
217def test_registered_mode_site_route_to_a_user_object_refuses_another_user(site):
218 site("registered")
219
220 private = call("/private-tool", USER_2)
221 public = call("/public-tool", USER_2)
222
223 assert private["status"] == 403
224 assert json.loads(private["body"])["error"] == NOT_SHARED
225 assert public["status"] == 200
226 assert call("/private-tool")["status"] == 401
227
228
229@pytest.mark.parametrize("mode", ["public", "registered"])
230def test_site_route_to_a_user_object_is_not_refused_to_its_owner_by_the_gate(site, mode):
231 site(mode)
232
233 owner = call("/private-tool", {"X-DBBasic-User-Id": "1"})
234
235 assert json.loads(owner["body"]).get("error") != NOT_SHARED
236 assert owner["status"] not in (401, 404)
237
238
239@pytest.mark.parametrize("mode", ["public", "registered"])
240def test_site_route_to_a_user_object_shared_by_a_rule_passes_the_gate(site, mode):
241 site(mode, {"effect": "allow", "principal": "user:2", "actions": ["execute", "read"],
242 "object_id": "u_1_x"})
243
244 shared = call("/private-tool", USER_2)
245 stranger = call("/private-tool", {"X-DBBasic-User-Id": "5"})
246
247 assert json.loads(shared["body"]).get("error") != NOT_SHARED
248 assert json.loads(stranger["body"])["error"] == NOT_SHARED
249 assert stranger["status"] == 403
250
251
252@pytest.mark.parametrize("mode", ["public", "registered", "role_based"])
253def test_objects_route_answers_a_non_owner_the_same_404_in_every_mode(site, mode):
254 site(mode)
255
256 for headers in (None, USER_2):
257 direct = call("/objects/u_1_x", headers)
258 assert direct["status"] == 404
259 assert json.loads(direct["body"])["error"] == "Object not found: u_1_x"
260
261
262@pytest.mark.parametrize("mode", ["public", "registered", "role_based"])
263def test_objects_listing_never_shows_another_users_object(site, mode):
264 site(mode)
265
266 for headers in (None, USER_2):
267 listing = call("/objects", headers)
268 assert b"u_1_x" not in listing.get("body", b"")
269
270
271# POST /permissions/check previews a decision. For an object it must be the
272# decision the route gate makes: both call _object_permission_decision.
273
274ADMIN_TOKEN = "test-admin-token-for-the-check-route"
275SHARE_WITH_2 = {"effect": "allow", "principal": "user:2", "actions": ["execute", "read"],
276 "object_id": "u_1_x"}
277MEMBERS_RUN_TOOLS = {"effect": "allow", "principal": "registered", "actions": ["execute"],
278 "collection": "tools"}
279
280
281def check(payload):
282 sent = {}
283
284 async def run():
285 scope = {
286 "type": "http", "method": "POST", "path": "/permissions/check", "query_string": b"",
287 "headers": [(b"authorization", f"Token {ADMIN_TOKEN}".encode()),
288 (b"content-type", b"application/json")],
289 }
290 body = json.dumps(payload).encode()
291
292 async def receive():
293 return {"type": "http.request", "body": body, "more_body": False}
294
295 async def send(message):
296 if message["type"] == "http.response.start":
297 sent["status"] = message["status"]
298 elif message["type"] == "http.response.body":
299 sent["body"] = sent.get("body", b"") + message.get("body", b"")
300
301 await object_server.app(scope, receive, send)
302
303 asyncio.run(run())
304 assert sent["status"] == 200, sent
305 return json.loads(sent["body"])["decision"]
306
307
308def gate(path, user_id, monkeypatch):
309 """What the route gate decided for a GET on a site route: the decision
310 it handed to the audit log, so an allowed request is seen as allowed
311 whatever the object does afterwards."""
312 seen = []
313 real = object_server._object_permission_decision
314
315 def spy(*args, **kwargs):
316 decision = real(*args, **kwargs)
317 seen.append(decision)
318 return decision
319
320 monkeypatch.setattr(object_server, "_object_permission_decision", spy)
321 response = call(path, {"X-DBBasic-User-Id": user_id} if user_id else None)
322 monkeypatch.setattr(object_server, "_object_permission_decision", real)
323 assert len(seen) == 1, seen
324 if not seen[0].allowed:
325 assert response["status"] == seen[0].http_status
326 assert json.loads(response["body"])["error"] == seen[0].reason
327 return object_permissions.decision_to_dict(seen[0]), response
328
329
330@pytest.mark.parametrize("mode", ["public", "registered", "role_based"])
331@pytest.mark.parametrize("user_id", [None, "1", "2", "5"])
332@pytest.mark.parametrize("path,object_id", [("/private-tool", "u_1_x"),
333 ("/public-tool", "tools_cli")])
334@pytest.mark.parametrize("rules", [(), (SHARE_WITH_2,), (MEMBERS_RUN_TOOLS,)],
335 ids=["no-rules", "shared-with-2", "tools-rule"])
336def test_permissions_check_answers_what_the_gate_answers_for_an_object(
337 site, monkeypatch, mode, user_id, path, object_id, rules):
338 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", ADMIN_TOKEN)
339 site(mode, *rules)
340 subject = {"user_id": user_id} if user_id else None
341
342 gate_decision, response = gate(path, user_id, monkeypatch)
343 stored = check({"subject": subject, "action": "execute", "object_id": object_id})
344 inline = check({"subject": subject, "action": "execute", "object_id": object_id,
345 "policy": {"access_mode": mode, "rules": list(rules)}})
346
347 assert stored == gate_decision
348 assert inline == gate_decision
349 if object_id == "tools_cli":
350 assert (response["status"] == 200) == gate_decision["allowed"]
351
352
353@pytest.mark.parametrize("mode", ["public", "registered"])
354def test_permissions_check_no_longer_says_allowed_for_someone_elses_user_object(
355 site, monkeypatch, mode):
356 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", ADMIN_TOKEN)
357 site(mode)
358
359 decision = check({"subject": {"user_id": "2"}, "action": "execute", "object_id": "u_1_x"})
360
361 assert decision["allowed"] is False
362 assert decision["reason"] == NOT_SHARED
363 assert decision["http_status"] == 403
364
365
366def test_permissions_check_reads_the_collection_out_of_the_object_id(site, monkeypatch):
367 # The gate never takes a collection from the caller; neither does the
368 # preview. Naming `tools` beside a user object does not put it in tools.
369 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", ADMIN_TOKEN)
370 site("role_based", MEMBERS_RUN_TOOLS)
371
372 user_object = check({"subject": {"user_id": "2"}, "action": "execute",
373 "object_id": "u_1_x", "collection": "tools"})
374 misfiled = check({"subject": {"user_id": "2"}, "action": "execute",
375 "object_id": "site_home", "collection": "tools"})
376 system_object = check({"subject": {"user_id": "2"}, "action": "execute",
377 "object_id": "tools_cli"})
378
379 assert user_object["allowed"] is False
380 assert misfiled["allowed"] is False
381 assert system_object["allowed"] is True
382
383
384def test_permissions_check_for_a_collection_is_unchanged(site, monkeypatch):
385 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", ADMIN_TOKEN)
386 site("role_based", MEMBERS_RUN_TOOLS)
387 active = object_permissions.policy_from_dict(
388 {"access_mode": "role_based", "rules": [MEMBERS_RUN_TOOLS]})
389
390 for subject, payload in ((OTHER, {"user_id": "2", "roles": ["member"],
391 "subscriptions": ["pro"]}), (ANONYMOUS, None)):
392 expected = object_permissions.decision_to_dict(object_permissions.check_permission(
393 subject, "execute", policy=active, collection="tools"))
394 assert check({"subject": payload, "action": "execute", "collection": "tools"}) == expected
395
396
397def test_permissions_check_honours_now_for_an_object(site, monkeypatch):
398 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", ADMIN_TOKEN)
399 site("public", {**SHARE_WITH_2, "expires_at": "2030-01-01T00:00:00Z"})
400 ask = {"subject": {"user_id": "2"}, "action": "execute", "object_id": "u_1_x"}
401
402 assert check({**ask, "now": "2029-12-31T00:00:00Z"})["allowed"] is True
403 assert check({**ask, "now": "2030-01-02T00:00:00Z"})["reason"] == NOT_SHARED