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_share_revoke_write_path.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_share_revoke_write_path.py · 8.7 KB · 197 lines
1"""Revoking a grant (DELETE /api/share/{id}) is a delete like any other.
2
3The route keeps its own permission rule (the record's owner, the granter, or
4an admin: record_shares has no policy rules by design), and everything after
5it is the write path's (docs/dron-write-semantics.md, S30): the collection's
6delete hook is asked, the row that was judged is the row that is removed, and
7the change is published. It used to call storage directly and skipped all
8three.
9"""
10import json
11
12import object_records
13import object_server
14from test_object_server import create_identity_session, enable_admin_token, request, session_headers, write_records
15
16SHARES_SCHEMA = {
17 "name": "record_shares",
18 "version": 1,
19 "fields": [
20 {"name": "id"},
21 {"name": "collection", "type": "text", "required": True},
22 {"name": "record_id", "type": "text", "required": True},
23 {"name": "user_id", "type": "text", "required": True},
24 {"name": "permission", "type": "enum", "enum": ["read", "write"], "default": "read"},
25 {"name": "granted_by", "type": "text", "read_only": True},
26 {"name": "created_at", "type": "datetime", "read_only": True},
27 ],
28}
29NOTES_SCHEMA = {
30 "name": "notes",
31 "version": 1,
32 "fields": [{"name": "id"}, {"name": "title", "type": "text"}, {"name": "owner_id", "type": "text"}],
33}
34
35
36def share_env(tmp_path, monkeypatch, hook_source=None):
37 data_dir = tmp_path / "data"
38 objects_root = tmp_path / "objects"
39 objects_root.mkdir(parents=True, exist_ok=True)
40 write_records(data_dir, "notes", "id\ttitle\towner_id\nn1\tplan\t7\n")
41 write_records(data_dir, "record_shares", "id\tcollection\trecord_id\tuser_id\tpermission\tgranted_by\tcreated_at\n")
42 schema_dir = data_dir / "schemas"
43 schema_dir.mkdir(parents=True, exist_ok=True)
44 shares = dict(SHARES_SCHEMA)
45 if hook_source is not None:
46 shares["hooks"] = {"before_write": "hook_shares"}
47 (objects_root / "hook").mkdir(parents=True, exist_ok=True)
48 (objects_root / "hook" / "shares.py").write_text(hook_source)
49 (schema_dir / "record_shares.json").write_text(json.dumps(shares))
50 (schema_dir / "notes.json").write_text(json.dumps(NOTES_SCHEMA))
51 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir))
52 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
53 enable_admin_token(monkeypatch)
54 owner, _ = create_identity_session({"user_id": "7"})
55 stranger, _ = create_identity_session({"user_id": "9"})
56 return data_dir, owner, stranger
57
58
59def grant(owner, user_id="8"):
60 status, _, payload = request(
61 "/api/share", method="POST", headers=session_headers(owner),
62 body=json.dumps({"collection": "notes", "record_id": "n1", "user_id": user_id}).encode(),
63 )
64 assert status == 201, payload
65 return payload["share"]["id"]
66
67
68def revoke(token, grant_id):
69 return request(f"/api/share/{grant_id}", method="DELETE", headers=session_headers(token))
70
71
72def grants(data_dir):
73 return object_records.read_collection_records("record_shares", base_dir=data_dir)
74
75
76def test_the_routes_own_answers_are_unchanged(tmp_path, monkeypatch):
77 data_dir, owner, stranger = share_env(tmp_path, monkeypatch)
78 grant_id = grant(owner)
79
80 status, _, payload = request(f"/api/share/{grant_id}", method="DELETE")
81 assert (status, payload) == (401, {"status": "error", "error": "Sharing requires a signed-in session."})
82 status, _, payload = revoke(stranger, grant_id)
83 assert (status, payload) == (403, {"status": "error", "error": "Not allowed to revoke this grant."})
84 assert len(grants(data_dir)) == 1
85 status, _, payload = revoke(owner, "no-such-grant")
86 assert (status, payload) == (404, {"status": "error", "error": "Grant not found."})
87
88 status, _, payload = revoke(owner, grant_id)
89 assert (status, payload) == (200, {"status": "ok"})
90 assert grants(data_dir) == []
91 status, _, payload = revoke(owner, grant_id)
92 assert (status, payload) == (404, {"status": "error", "error": "Grant not found."})
93
94
95def test_a_revoke_asks_the_collections_delete_hook(tmp_path, monkeypatch):
96 data_dir, owner, _ = share_env(
97 tmp_path, monkeypatch,
98 hook_source=(
99 "def BEFORE_WRITE(request):\n"
100 " if request['action'] == 'delete' and request['existing'].get('user_id') == 'kept':\n"
101 " return {'error': 'This grant is kept', 'status': 409}\n"
102 " return None\n"
103 ),
104 )
105 kept = grant(owner, "kept")
106 other = grant(owner, "8")
107
108 status, _, payload = revoke(owner, kept)
109 assert status == 409
110 assert payload["error"] == "This grant is kept" and payload["code"] == "hook_rejected"
111 assert [row["id"] for row in grants(data_dir)] == [kept, other]
112
113 assert revoke(owner, other)[0] == 200
114 assert [row["id"] for row in grants(data_dir)] == [kept]
115
116
117def test_a_revoke_removes_only_the_row_it_judged_and_publishes_the_change(tmp_path, monkeypatch):
118 data_dir, owner, _ = share_env(tmp_path, monkeypatch)
119 grant_id = grant(owner)
120 stored = object_records.get_collection_record("record_shares", grant_id, base_dir=data_dir)
121
122 seen = {}
123 real_delete = object_records.delete_collection_record
124
125 def spy_delete(collection, record_id, **kwargs):
126 seen["judged_rev"] = kwargs.get("judged_rev")
127 return real_delete(collection, record_id, **kwargs)
128
129 published = []
130 monkeypatch.setattr(object_records, "delete_collection_record", spy_delete)
131 monkeypatch.setattr(
132 object_server, "_publish_record_change_event",
133 lambda change, record=None: published.append((change, record)),
134 )
135
136 status, _, payload = revoke(owner, grant_id)
137 assert (status, payload) == (200, {"status": "ok"})
138 assert seen["judged_rev"] == object_records.compute_record_rev(stored)
139 assert len(published) == 1
140 change, record = published[0]
141 assert change["collection"] == "record_shares" and change["action"] == "delete"
142 assert change["record_id"] == grant_id and record["id"] == grant_id
143
144
145def test_a_grant_that_changed_after_it_was_judged_is_not_removed(tmp_path, monkeypatch):
146 """S52: the owner/granter check judged one row; if the row under the
147 lock is another, nothing is removed and the caller retries."""
148 data_dir, owner, _ = share_env(tmp_path, monkeypatch)
149 grant_id = grant(owner)
150 real_delete = object_records.delete_collection_record
151
152 def change_then_delete(collection, record_id, **kwargs):
153 object_records.update_collection_record(
154 collection, record_id, {"permission": "write"}, base_dir=data_dir)
155 return real_delete(collection, record_id, **kwargs)
156
157 monkeypatch.setattr(object_records, "delete_collection_record", change_then_delete)
158 status, _, payload = revoke(owner, grant_id)
159 assert status == 409 and payload["code"] == "conflict"
160 assert [row["id"] for row in grants(data_dir)] == [grant_id]
161
162
163def test_a_cross_origin_cookie_share_or_revoke_is_refused_by_the_global_check(tmp_path, monkeypatch):
164 """Neither handler has a cross-origin check of its own (the ones they
165 had could never run): app() refuses the request for every route, with
166 this status and body, before a handler is reached."""
167 data_dir, owner, _ = share_env(tmp_path, monkeypatch)
168 grant_id = grant(owner)
169 cookie = ("cookie", f"dbbasic_session={owner}")
170 body = json.dumps({"collection": "notes", "record_id": "n1", "user_id": "12"}).encode()
171
172 reached = []
173 for name in ("_handle_share", "_handle_share_revoke"):
174 real = getattr(object_server, name)
175
176 async def spy(*args, _real=real, _name=name, **kwargs):
177 reached.append(_name)
178 return await _real(*args, **kwargs)
179
180 monkeypatch.setattr(object_server, name, spy)
181
182 for origin in (("origin", "https://evil.example.com"), ("referer", "https://evil.example.com/page")):
183 headers = [cookie, ("host", "desk.example.com"), origin]
184 for path, method, sent in (("/api/share", "POST", body), (f"/api/share/{grant_id}", "DELETE", b"")):
185 status, _, payload = request(path, method=method, body=sent, headers=headers)
186 assert status == 403
187 assert payload == {"status": "error", "error": "Cross-origin cookie request rejected"}
188 assert reached == []
189 assert [row["id"] for row in grants(data_dir)] == [grant_id]
190
191 # The same cookie from the box's own origin is the owner at work.
192 same = [cookie, ("host", "desk.example.com"), ("origin", "https://desk.example.com")]
193 status, _, payload = request("/api/share", method="POST", body=body, headers=same)
194 assert status == 201, payload
195 status, _, payload = request(f"/api/share/{grant_id}", method="DELETE", headers=same)
196 assert (status, payload) == (200, {"status": "ok"})
197 assert reached == ["_handle_share", "_handle_share_revoke"]