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_collection_scope.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_collection_scope.py · 7.7 KB · 188 lines
1"""A user object is in no system collection's permission scope.
2
3An object is checked under the collection its name starts with, and a user
4object `u_<id>_<name>` used to be checked under the collection `<name>`
5starts with: `u_1_tools_cli` as a member of `tools`. A grant written for
6the system collection then granted on a private object whose owner merely
7picked that name. The owner rule on /objects/{id} hid this from other
8users there; a site route pointing at the object did not.
9
10Allow rules that name a collection no longer apply to a user object. Deny
11rules are untouched: this change only ever refuses more.
12"""
13
14import asyncio
15import json
16
17import pytest
18
19import object_permission_store
20import object_permissions
21import object_server
22
23
24def policy(*rules, access_mode="role_based"):
25 return object_permissions.policy_from_dict({"access_mode": access_mode, "rules": list(rules)})
26
27
28def decide(subject, action, object_id, *rules, access_mode="role_based"):
29 return object_server._object_permission_decision(
30 subject, action, policy(*rules, access_mode=access_mode), object_id)
31
32
33ANONYMOUS = object_permissions.PermissionSubject.anonymous()
34OWNER = object_permissions.PermissionSubject(user_id="1")
35OTHER = object_permissions.PermissionSubject(user_id="2", roles=("member",))
36
37TOOLS_PUBLIC = {"effect": "allow", "principal": "public", "actions": ["execute", "read"],
38 "collection": "tools"}
39TOOLS_MEMBER = {"effect": "allow", "principal": "role:member", "actions": ["*"],
40 "collection": "tools"}
41
42
43@pytest.mark.parametrize("object_id", ["u_1_tools_cli", "u_1_tools", "u_1_deals"])
44@pytest.mark.parametrize("action", ["read", "execute", "update", "delete", "source", "state",
45 "logs", "files", "versions"])
46def test_system_collection_grant_does_not_reach_a_user_object(object_id, action):
47 rules = [
48 TOOLS_PUBLIC,
49 TOOLS_MEMBER,
50 {**TOOLS_PUBLIC, "collection": "deals"},
51 {**TOOLS_MEMBER, "collection": "deals"},
52 ]
53
54 assert not decide(ANONYMOUS, action, object_id, *rules).allowed
55 assert not decide(OTHER, action, object_id, *rules).allowed
56
57
58def test_system_collection_grant_still_covers_the_system_object():
59 assert decide(ANONYMOUS, "execute", "tools_cli", TOOLS_PUBLIC).allowed
60 assert decide(OTHER, "update", "tools_cli", TOOLS_MEMBER).allowed
61 assert not decide(ANONYMOUS, "update", "tools_cli", TOOLS_PUBLIC).allowed
62
63
64def test_owner_keeps_the_owner_fallback_on_their_object():
65 decision = decide(OWNER, "execute", "u_1_tools_cli", TOOLS_PUBLIC)
66
67 assert decision.allowed
68 assert decision.reason == "object owner"
69
70
71def test_rule_naming_the_user_object_still_shares_it():
72 share = {"effect": "allow", "principal": "user:2", "actions": ["read"],
73 "object_id": "u_1_tools_cli"}
74
75 assert decide(OTHER, "read", "u_1_tools_cli", share).allowed
76 assert not decide(OTHER, "update", "u_1_tools_cli", share).allowed
77
78
79def test_rule_naming_collection_and_user_object_does_not_grant():
80 # Refused rather than guessed at: the collection half can no longer match.
81 both = {"effect": "allow", "principal": "user:2", "actions": ["read"],
82 "collection": "tools", "object_id": "u_1_tools_cli"}
83
84 assert not decide(OTHER, "read", "u_1_tools_cli", both).allowed
85
86
87def test_collection_deny_still_refuses_the_user_object():
88 deny = {"effect": "deny", "principal": "registered", "actions": ["execute"],
89 "collection": "tools"}
90 opt_out = {"effect": "deny", "principal": "owner_fallback", "actions": ["delete"],
91 "collection": "tools"}
92
93 assert not decide(OWNER, "execute", "u_1_tools_cli", deny).allowed
94 assert not decide(OWNER, "delete", "u_1_tools_cli", opt_out).allowed
95 assert decide(OWNER, "read", "u_1_tools_cli", deny, opt_out).allowed
96
97
98def call(path, headers=None):
99 sent = {}
100
101 async def run():
102 scope = {
103 "type": "http", "method": "GET", "path": path, "query_string": b"",
104 "headers": [(k.lower().encode(), v.encode()) for k, v in (headers or {}).items()],
105 }
106
107 async def receive():
108 return {"type": "http.request", "body": b"", "more_body": False}
109
110 async def send(message):
111 if message["type"] == "http.response.start":
112 sent["status"] = message["status"]
113 elif message["type"] == "http.response.body":
114 sent["body"] = sent.get("body", b"") + message.get("body", b"")
115
116 await object_server.app(scope, receive, send)
117
118 asyncio.run(run())
119 return sent
120
121
122def test_site_route_to_a_user_object_is_not_opened_by_a_system_collection_rule(
123 tmp_path, monkeypatch):
124 objects_dir = tmp_path / "objects"
125 data_dir = tmp_path / "data"
126 (objects_dir / "users" / "1").mkdir(parents=True)
127 (objects_dir / "tools").mkdir(parents=True)
128 source = "def GET(request):\n return {'ran': True}\n"
129 (objects_dir / "users" / "1" / "tools_cli.py").write_text(source)
130 (objects_dir / "tools" / "cli.py").write_text(source)
131 routes = data_dir / "collections" / "site_routes" / "records.tsv"
132 routes.parent.mkdir(parents=True)
133 routes.write_text(
134 "id\tpattern\tobject_id\n"
135 "r1\t/private-tool\tu_1_tools_cli\n"
136 "r2\t/public-tool\ttools_cli\n"
137 )
138 object_permission_store.replace_policy(
139 {"access_mode": "role_based", "rules": [TOOLS_PUBLIC]}, data_dir)
140 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_dir))
141 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
142 monkeypatch.setenv("DBBASIC_ENABLE_SITE_ROUTES", "true")
143 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
144
145 private = call("/private-tool")
146 public = call("/public-tool")
147
148 assert private["status"] == 403
149 assert json.loads(private["body"])["error"] == "no matching role rule"
150 assert public["status"] == 200
151 assert json.loads(public["body"])["ran"] is True
152
153
154def test_collections_listing_groups_user_objects_under_their_owner(tmp_path, monkeypatch):
155 objects_dir = tmp_path / "objects"
156 data_dir = tmp_path / "data"
157 source = "def GET(request):\n return {}\n"
158 for relative in ("tools/export.py", "users/1/tools_cli.py", "users/1/deals.py"):
159 path = objects_dir / relative
160 path.parent.mkdir(parents=True, exist_ok=True)
161 path.write_text(source)
162 object_permission_store.replace_policy(
163 {"access_mode": "role_based", "rules": [TOOLS_PUBLIC]}, data_dir)
164 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_dir))
165 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
166 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", "unit-test-only-admin-token")
167 admin = {"authorization": "Token unit-test-only-admin-token"}
168
169 for path in ("/admin/collections", "/collections"):
170 sent = call(path, headers=admin)
171 payload = json.loads(sent["body"])
172
173 assert sent["status"] == 200
174 by_name = {item["name"]: item for item in payload["collections"]}
175 assert sorted(by_name) == ["deals", "tools"]
176 assert payload["count"] == 2
177 assert by_name["tools"]["object_count"] == 1
178 assert by_name["tools"]["owners"] == ["system"]
179 assert by_name["deals"]["object_count"] == 0
180 assert by_name["deals"]["owners"] == []
181 assert [group["owner"] for group in payload["user_objects"]] == ["1"]
182 assert [item["object_id"] for item in payload["user_objects"][0]["objects"]] == [
183 "u_1_deals", "u_1_tools_cli"]
184
185 deals = json.loads(call("/admin/collections/deals", headers=admin)["body"])
186 assert deals["collection"]["objects"] == []
187 detail = json.loads(call("/admin/collections/tools", headers=admin)["body"])
188 assert [item["object_id"] for item in detail["collection"]["objects"]] == ["tools_export"]