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_object_user_files.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_object_user_files.py · 14.4 KB · 348 lines
1"""Tests for user file storage: bytes module and the /api/files surface."""
2
3import json
4
5import pytest
6
7import object_records
8import object_server
9import object_user_files
10
11from test_object_server import (
12 create_identity_session,
13 enable_admin_token,
14 raw_request,
15 request,
16 save_permission_policy,
17 write_records,
18)
19
20FILES_POLICY = {
21 "access_mode": "role_based",
22 "rules": [
23 {
24 "effect": "allow",
25 "principal": "registered",
26 "actions": ["create", "read", "update", "delete"],
27 "collection": "files",
28 "row_filter": {"owner_id": "$user_id"},
29 "reason": "own files",
30 },
31 {
32 "effect": "allow",
33 "principal": "public",
34 "actions": ["read"],
35 "collection": "files",
36 "row_filter": {"is_public": "true"},
37 "reason": "public files",
38 },
39 ],
40}
41
42
43def multipart_body(field, filename, content, extra=()):
44 boundary = "testboundary42"
45 parts = []
46 for name, value in extra:
47 parts.append(
48 f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode()
49 )
50 parts.append(
51 (
52 f'--{boundary}\r\nContent-Disposition: form-data; name="{field}"; '
53 f'filename="{filename}"\r\nContent-Type: text/plain\r\n\r\n'
54 ).encode()
55 + content
56 + b"\r\n"
57 )
58 parts.append(f"--{boundary}--\r\n".encode())
59 return b"".join(parts), f"multipart/form-data; boundary={boundary}"
60
61
62def files_env(tmp_path, monkeypatch):
63 data_dir = tmp_path / "data"
64 write_records(
65 data_dir,
66 "files",
67 "id\tfilename\tcontent_type\tsize\tdescription\tproject_id\tis_public\towner_id\n",
68 )
69 schema_file = data_dir / "schemas" / "files.json"
70 schema_file.parent.mkdir(parents=True, exist_ok=True)
71 schema_file.write_text(
72 json.dumps(
73 {
74 "fields": [
75 {"name": "id"},
76 {"name": "filename", "required": True},
77 {"name": "content_type"},
78 {"name": "size", "type": "integer"},
79 {"name": "description"},
80 {"name": "is_public", "type": "boolean", "default": "false"},
81 {"name": "owner_id"},
82 ]
83 }
84 )
85 )
86 save_permission_policy(data_dir, FILES_POLICY)
87 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir))
88 monkeypatch.setenv(object_server.USER_FILES_ENABLED_ENV, "true")
89 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
90 enable_admin_token(monkeypatch)
91 return data_dir
92
93
94def test_module_save_read_delete_and_usage(tmp_path):
95 size = object_user_files.save_file("dan", "f1", b"hello", base_dir=tmp_path)
96 assert size == 5
97 assert object_user_files.read_file("dan", "f1", base_dir=tmp_path) == b"hello"
98 object_user_files.save_file("dan", "f2", b"world!", base_dir=tmp_path)
99 assert object_user_files.usage_bytes("dan", base_dir=tmp_path) == 11
100 assert object_user_files.delete_file("dan", "f1", base_dir=tmp_path) is True
101 assert object_user_files.delete_file("dan", "f1", base_dir=tmp_path) is False
102 with pytest.raises(object_user_files.UserFileNotFoundError):
103 object_user_files.read_file("dan", "f1", base_dir=tmp_path)
104 with pytest.raises(object_user_files.InvalidUserFileError):
105 object_user_files.file_path("../etc", "f1", base_dir=tmp_path)
106 with pytest.raises(object_user_files.InvalidUserFileError):
107 object_user_files.file_path("dan", "../../secrets", base_dir=tmp_path)
108
109
110def test_upload_download_share_delete_flow(tmp_path, monkeypatch):
111 data_dir = files_env(tmp_path, monkeypatch)
112 token, _ = create_identity_session({"user_id": "dan"})
113 bearer = [("authorization", f"Bearer {token}")]
114
115 body, content_type = multipart_body("file", "notes.txt", b"file bytes here")
116 status, _, uploaded = request(
117 "/api/files",
118 method="POST",
119 body=body,
120 headers=bearer + [("content-type", content_type)],
121 )
122 assert status == 201, uploaded
123 file_id = uploaded["file"]["id"]
124 assert uploaded["file"]["size"] == "15"
125 assert uploaded["file"]["owner_id"] == "dan"
126
127 status, response_headers, payload = raw_request(f"/api/files/{file_id}", headers=bearer)
128 assert status == 200
129 assert payload == b"file bytes here"
130 assert response_headers[b"content-type"] == b"text/plain"
131
132 # Anonymous cannot download a private file.
133 status, _, _ = request(f"/api/files/{file_id}")
134 assert status == 404 # like a missing file: no oracle for ids
135
136 # Owner shares it; anonymous download works.
137 status, _, _ = request(
138 f"/collections/files/records/{file_id}",
139 method="PUT",
140 body=json.dumps({"is_public": "true"}).encode(),
141 headers=bearer + [("content-type", "application/json")],
142 )
143 assert status == 200
144 status, _, payload = raw_request(f"/api/files/{file_id}")
145 assert status == 200 and payload == b"file bytes here"
146
147 # Another user cannot delete it; the owner can, and bytes go away.
148 other_token, _ = create_identity_session({"user_id": "mallory"})
149 status, _, _ = request(
150 f"/api/files/{file_id}",
151 method="DELETE",
152 headers=[("authorization", f"Bearer {other_token}")],
153 )
154 assert status == 404 # like a missing file: no oracle for ids
155 status, _, deleted = request(f"/api/files/{file_id}", method="DELETE", headers=bearer)
156 assert status == 200 and deleted["deleted"] is True
157 assert object_user_files.usage_bytes("dan", base_dir=data_dir) == 0
158 status, _, _ = request(f"/api/files/{file_id}", headers=bearer)
159 assert status == 404
160
161
162def test_a_cross_origin_cookie_delete_is_refused_by_the_global_check(tmp_path, monkeypatch):
163 """DELETE /api/files/{id} has no cross-origin check of its own (the one
164 it had could never run): app() refuses the request for every route, with
165 this status and body, before the handler is reached."""
166 data_dir = files_env(tmp_path, monkeypatch)
167 token, _ = create_identity_session({"user_id": "dan"})
168 body, content_type = multipart_body("file", "notes.txt", b"file bytes here")
169 status, _, uploaded = request(
170 "/api/files", method="POST", body=body,
171 headers=[("authorization", f"Bearer {token}"), ("content-type", content_type)],
172 )
173 assert status == 201, uploaded
174 file_id = uploaded["file"]["id"]
175 cookie = ("cookie", f"dbbasic_session={token}")
176
177 reached = []
178 real_handler = object_server._handle_user_file
179
180 async def spy(*args, **kwargs):
181 reached.append(args)
182 return await real_handler(*args, **kwargs)
183
184 monkeypatch.setattr(object_server, "_handle_user_file", spy)
185
186 for origin in ([("origin", "https://evil.example.com")], [("referer", "https://evil.example.com/page")]):
187 status, _, payload = request(
188 f"/api/files/{file_id}", method="DELETE",
189 headers=[cookie, ("host", "files.example.com")] + origin,
190 )
191 assert status == 403
192 assert payload == {"status": "error", "error": "Cross-origin cookie request rejected"}
193 assert reached == []
194 assert object_user_files.read_file("dan", file_id, base_dir=data_dir) == b"file bytes here"
195 assert [r["id"] for r in object_records.read_collection_records("files", base_dir=data_dir)] == [file_id]
196
197 # The same cookie from the box's own origin is the owner deleting a file.
198 status, _, payload = request(
199 f"/api/files/{file_id}", method="DELETE",
200 headers=[cookie, ("host", "files.example.com"), ("origin", "https://files.example.com")],
201 )
202 assert (status, payload) == (200, {"status": "ok", "deleted": True, "file_id": file_id})
203 assert len(reached) == 1
204
205
206def test_upload_respects_quota_and_session(tmp_path, monkeypatch):
207 files_env(tmp_path, monkeypatch)
208 monkeypatch.setenv(object_server.USER_FILES_QUOTA_ENV, "10")
209 token, _ = create_identity_session({"user_id": "dan"})
210 bearer = [("authorization", f"Bearer {token}")]
211
212 body, content_type = multipart_body("file", "big.txt", b"x" * 11)
213 status, _, over = request(
214 "/api/files", method="POST", body=body,
215 headers=bearer + [("content-type", content_type)],
216 )
217 assert status == 413 and over["code"] == "quota_exceeded"
218
219 status, _, _ = request(
220 "/api/files", method="POST", body=body, headers=[("content-type", content_type)]
221 )
222 assert status == 401
223
224
225def test_a_file_whose_record_changes_after_its_gates_is_not_deleted(tmp_path, monkeypatch):
226 """The delete is authorized on the record read before the write lock. A
227 writer that gives the file to someone else in between (here, from the
228 pre-delete hook step, so the interleaving is exact) turns the delete
229 into a retryable 409 conflict: neither the record nor the bytes go
230 (docs/dron-write-semantics.md S52)."""
231 data_dir = files_env(tmp_path, monkeypatch)
232 token, _ = create_identity_session({"user_id": "dan"})
233 bearer = [("authorization", f"Bearer {token}")]
234 body, content_type = multipart_body("file", "notes.txt", b"file bytes here")
235 status, _, uploaded = request(
236 "/api/files", method="POST", body=body, headers=bearer + [("content-type", content_type)],
237 )
238 assert status == 201, uploaded
239 file_id = uploaded["file"]["id"]
240
241 allowed_by_hook = object_server._delete_allowed_by_hook
242
243 async def give_away_first(send, headers, *, collection, existing):
244 object_records.update_collection_record(
245 "files", existing["id"], {"owner_id": "mallory"}, base_dir=data_dir, actor="racer")
246 return await allowed_by_hook(send, headers, collection=collection, existing=existing)
247
248 monkeypatch.setattr(object_server, "_delete_allowed_by_hook", give_away_first)
249 status, _, refused = request(f"/api/files/{file_id}", method="DELETE", headers=bearer)
250 assert (status, refused.get("code")) == (409, "conflict"), refused
251 assert object_records.get_collection_record("files", file_id, base_dir=data_dir)["owner_id"] == "mallory"
252 assert object_user_files.read_file("dan", file_id, base_dir=data_dir) == b"file bytes here"
253
254
255# --- a file's create is a record create (the write path) --------------------
256#
257# The upload and WebDAV PUT/COPY create the file's record through the same
258# gated function as POST /collections/files/records (object_server
259# _gated_create). Before they shared it, a file create skipped the field
260# permission and relation.requires steps that a record create, and a file's
261# own WebDAV overwrite, ask, and the upload answered with the stored row
262# without the read decision every other write answer goes through.
263
264
265def _files_schema(data_dir, **extra_fields):
266 path = data_dir / "schemas" / "files.json"
267 schema = json.loads(path.read_text())
268 for field in schema["fields"]:
269 if field["name"] in extra_fields:
270 field.update(extra_fields.pop(field["name"]))
271 schema["fields"].extend({"name": name, **spec} for name, spec in extra_fields.items())
272 path.write_text(json.dumps(schema))
273
274
275def _upload(token, extra=()):
276 body, content_type = multipart_body("file", "notes.txt", b"file bytes", extra=extra)
277 return request(
278 "/api/files", method="POST", body=body,
279 headers=[("authorization", f"Bearer {token}"), ("content-type", content_type)],
280 )
281
282
283def _stored_files(data_dir):
284 return object_records.read_collection_records("files", base_dir=data_dir)
285
286
287def test_an_upload_asks_field_permissions_like_any_create(tmp_path, monkeypatch):
288 data_dir = files_env(tmp_path, monkeypatch)
289 _files_schema(data_dir, project_id={"permissions": {"registered": "read"}})
290 token, _ = create_identity_session({"user_id": "dan"})
291
292 status, _, refused = _upload(token, extra=[("project_id", "p1")])
293 assert (status, refused.get("code"), refused.get("denied_fields")) == (403, "forbidden", ["project_id"])
294 assert _stored_files(data_dir) == []
295 assert object_user_files.usage_bytes("dan", base_dir=data_dir) == 0
296
297 status, _, uploaded = _upload(token)
298 assert status == 201, uploaded
299
300
301def test_an_upload_asks_relation_requires_like_any_create(tmp_path, monkeypatch):
302 """S15 on a file's create: a project the uploader may not read is
303 answered like a missing one, and nothing is stored."""
304 data_dir = files_env(tmp_path, monkeypatch)
305 write_records(data_dir, "projects", "id\tname\towner_id\nmine\tMine\tdan\ntheirs\tTheirs\teve\n")
306 (data_dir / "schemas" / "projects.json").write_text(json.dumps(
307 {"fields": [{"name": "id"}, {"name": "name"}, {"name": "owner_id"}]}))
308 _files_schema(data_dir, project_id={"relation": {"collection": "projects", "requires": "read"}})
309 policy = json.loads(json.dumps(FILES_POLICY))
310 policy["rules"].append({
311 "effect": "allow", "principal": "registered", "actions": ["read"],
312 "collection": "projects", "row_filter": {"owner_id": "$user_id"}, "reason": "own projects",
313 })
314 save_permission_policy(data_dir, policy)
315 token, _ = create_identity_session({"user_id": "dan"})
316
317 status, _, refused = _upload(token, extra=[("project_id", "theirs")])
318 assert status == 400, refused
319 assert "references a missing record" in refused["error"]
320 assert _stored_files(data_dir) == []
321
322 status, _, uploaded = _upload(token, extra=[("project_id", "mine")])
323 assert status == 201, uploaded
324
325
326def test_an_upload_answers_with_what_the_uploader_may_read(tmp_path, monkeypatch):
327 """A caller allowed to create a file but not to read it gets its id
328 (and its URL) and nothing else, as a record create answers."""
329 data_dir = files_env(tmp_path, monkeypatch)
330 save_permission_policy(data_dir, {
331 "access_mode": "role_based",
332 "rules": [{
333 "effect": "allow", "principal": "registered", "actions": ["create"],
334 "collection": "files", "reason": "drop box: upload, never read back",
335 }, {
336 # without it the owner fallback lets an owner read their own row
337 "effect": "deny", "principal": "registered", "actions": ["read"],
338 "collection": "files", "reason": "drop box: nobody reads it back",
339 }],
340 })
341 token, _ = create_identity_session({"user_id": "dan"})
342
343 status, _, uploaded = _upload(token)
344 assert status == 201, uploaded
345 file_id = uploaded["file"]["id"]
346 assert uploaded["file"] == {"id": file_id}
347 assert uploaded["url"] == f"/api/files/{file_id}"
348 assert object_records.get_collection_record("files", file_id, base_dir=data_dir)["owner_id"] == "dan"