askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
test_user_file_surfaces_agree.py · 12.3 KB · 280 lines
| 1 | """/api/files and /dav/files/ give the same answer for the same file. |
| 2 | |
| 3 | Both are ways into the `files` collection, so a policy that refuses an owner |
| 4 | on one must refuse them on the other. They disagreed under a policy with no |
| 5 | rules: the JSON route asked the collection-level question first (no record, |
| 6 | so no owner fallback) and refused the owner, while WebDAV only asked with |
| 7 | the record and let the owner fallback through, so a desktop could list, |
| 8 | read and delete files the policy was meant to close. |
| 9 | |
| 10 | Each case below builds a fresh box, makes the same request on both surfaces |
| 11 | against two identical files, and compares the outcome: "ok" (served or |
| 12 | done), "hidden" (answered like a missing file) or "refused" (401/403). |
| 13 | |
| 14 | What "the same file" means differs by subject. An owner (with or without an |
| 15 | admin role) addresses their file on both surfaces. A non-owner cannot |
| 16 | address someone else's file through WebDAV at all -- the folder holds only |
| 17 | the caller's own files -- so for them WebDAV must never do more than the |
| 18 | JSON route does, and must leave the owner's file alone. |
| 19 | """ |
| 20 | |
| 21 | from __future__ import annotations |
| 22 | |
| 23 | import base64 |
| 24 | import json |
| 25 | import re |
| 26 | |
| 27 | import pytest |
| 28 | from test_object_server import create_identity_session, raw_request, request, save_permission_policy |
| 29 | from test_object_user_files import files_env, multipart_body |
| 30 | |
| 31 | import object_api_keys |
| 32 | import object_records |
| 33 | import object_server |
| 34 | import object_user_files |
| 35 | |
| 36 | OWNER, OTHER, ADMIN = "dan", "eve", "boss" |
| 37 | USER_ROLES = {ADMIN: ["admin"]} |
| 38 | |
| 39 | POLICIES = { |
| 40 | # "deny-all": no rule grants anything, so only the owner fallback could |
| 41 | "no_rules": {"access_mode": "role_based", "rules": [], "user_roles": USER_ROLES}, |
| 42 | "allow_read": { |
| 43 | "access_mode": "role_based", |
| 44 | "user_roles": USER_ROLES, |
| 45 | "rules": [ |
| 46 | { |
| 47 | "effect": "allow", |
| 48 | "principal": "registered", |
| 49 | "actions": ["read"], |
| 50 | "collection": "files", |
| 51 | "row_filter": {"owner_id": "$user_id"}, |
| 52 | "reason": "own files, read only", |
| 53 | } |
| 54 | ], |
| 55 | }, |
| 56 | "allow_all": { |
| 57 | "access_mode": "role_based", |
| 58 | "user_roles": USER_ROLES, |
| 59 | "rules": [ |
| 60 | { |
| 61 | "effect": "allow", |
| 62 | "principal": "registered", |
| 63 | "actions": ["create", "read", "update", "delete"], |
| 64 | "collection": "files", |
| 65 | "reason": "registered users manage files", |
| 66 | } |
| 67 | ], |
| 68 | }, |
| 69 | } |
| 70 | |
| 71 | MODES = ("enforced", "audit", "off") |
| 72 | SUBJECTS = ("owner", "other", "admin") |
| 73 | VERBS = ("list", "propfind_file", "get", "head", "delete", "put_new", "put_existing", "move", "copy") |
| 74 | |
| 75 | |
| 76 | def _set_mode(monkeypatch, mode): |
| 77 | monkeypatch.delenv(object_server.PERMISSION_ENFORCEMENT_ENV, raising=False) |
| 78 | monkeypatch.delenv(object_server.PERMISSION_AUDIT_ENV, raising=False) |
| 79 | if mode == "enforced": |
| 80 | monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true") |
| 81 | monkeypatch.setenv(object_server.PERMISSION_UNREADY_ENFORCEMENT_ENV, "true") |
| 82 | elif mode == "audit": |
| 83 | monkeypatch.setenv(object_server.PERMISSION_AUDIT_ENV, "true") |
| 84 | |
| 85 | |
| 86 | def _box(tmp_path, monkeypatch, mode, policy, file_owner): |
| 87 | data_dir = files_env(tmp_path, monkeypatch) |
| 88 | monkeypatch.setenv(object_server.WEBDAV_ENABLED_ENV, "true") |
| 89 | save_permission_policy(data_dir, POLICIES[policy]) |
| 90 | _set_mode(monkeypatch, mode) |
| 91 | ids = {} |
| 92 | for name in ("a.txt", "b.txt"): |
| 93 | stored = object_records.create_collection_record( |
| 94 | "files", |
| 95 | {"filename": name, "content_type": "text/plain", "size": "5", "is_public": "false", |
| 96 | "owner_id": file_owner}, |
| 97 | base_dir=data_dir, |
| 98 | ) |
| 99 | object_user_files.save_file(file_owner, stored["id"], b"bytes", base_dir=data_dir) |
| 100 | ids[name] = stored["id"] |
| 101 | return data_dir, ids |
| 102 | |
| 103 | |
| 104 | def _key(data_dir, user_id): |
| 105 | _, token = object_api_keys.create_api_key(user_id, "desk", base_dir=data_dir) |
| 106 | return token |
| 107 | |
| 108 | |
| 109 | def _bearer(token): |
| 110 | return [("authorization", f"Bearer {token}")] |
| 111 | |
| 112 | |
| 113 | def _dav(path, token, method, body=b"", headers=()): |
| 114 | raw = base64.b64encode(f"x:{token}".encode()).decode() |
| 115 | return raw_request(path, method=method, body=body, |
| 116 | headers=[("authorization", f"Basic {raw}")] + list(headers)) |
| 117 | |
| 118 | |
| 119 | def _status_outcome(status): |
| 120 | if 200 <= status < 300: |
| 121 | return "ok" |
| 122 | if status == 404: |
| 123 | return "hidden" |
| 124 | assert status in (401, 403), status |
| 125 | return "refused" |
| 126 | |
| 127 | |
| 128 | def _json(verb, token, file_id, caller): |
| 129 | """The JSON route's answer for this verb on the file with this id.""" |
| 130 | auth = _bearer(token) |
| 131 | if verb == "list": |
| 132 | status, _, payload = request("/collections/files/records", headers=auth) |
| 133 | if status != 200: |
| 134 | return _status_outcome(status) |
| 135 | return "ok" if any(r.get("id") == file_id for r in payload["records"]) else "hidden" |
| 136 | if verb in ("get", "head", "propfind_file"): |
| 137 | return _status_outcome(raw_request(f"/api/files/{file_id}", headers=auth)[0]) |
| 138 | if verb == "delete": |
| 139 | return _status_outcome(raw_request(f"/api/files/{file_id}", method="DELETE", headers=auth)[0]) |
| 140 | if verb == "put_new": |
| 141 | # an upload takes a signed-in session, not an API key: same person |
| 142 | session, _ = create_identity_session({"user_id": caller}) |
| 143 | body, content_type = multipart_body("file", "new.txt", b"new") |
| 144 | status, _, _ = raw_request("/api/files", method="POST", body=body, |
| 145 | headers=_bearer(session) + [("content-type", content_type)]) |
| 146 | return _status_outcome(status) |
| 147 | if verb in ("put_existing", "move"): |
| 148 | change = {"size": "3"} if verb == "put_existing" else {"filename": "renamed.txt"} |
| 149 | status, _, _ = raw_request( |
| 150 | f"/collections/files/records/{file_id}", method="PUT", body=json.dumps(change).encode(), |
| 151 | headers=auth + [("content-type", "application/json")], |
| 152 | ) |
| 153 | return _status_outcome(status) |
| 154 | if verb == "copy": # read the file, then store a new one |
| 155 | read = _json("get", token, file_id, caller) |
| 156 | return read if read != "ok" else _json("put_new", token, file_id, caller) |
| 157 | raise AssertionError(verb) |
| 158 | |
| 159 | |
| 160 | def _webdav(verb, token, name): |
| 161 | """WebDAV's answer for this verb on the file with this name.""" |
| 162 | if verb == "list": |
| 163 | status, _, body = _dav("/dav/files/", token, "PROPFIND", headers=[("depth", "1")]) |
| 164 | if status != 207: |
| 165 | return _status_outcome(status) |
| 166 | return "ok" if name in re.findall(r"<D:displayname>([^<]*)</D:displayname>", body.decode()) else "hidden" |
| 167 | if verb == "propfind_file": |
| 168 | return _status_outcome(_dav(f"/dav/files/{name}", token, "PROPFIND", headers=[("depth", "0")])[0]) |
| 169 | if verb == "get": |
| 170 | return _status_outcome(_dav(f"/dav/files/{name}", token, "GET")[0]) |
| 171 | if verb == "head": |
| 172 | return _status_outcome(_dav(f"/dav/files/{name}", token, "HEAD")[0]) |
| 173 | if verb == "delete": |
| 174 | return _status_outcome(_dav(f"/dav/files/{name}", token, "DELETE")[0]) |
| 175 | if verb == "put_new": |
| 176 | return _status_outcome(_dav("/dav/files/new.txt", token, "PUT", body=b"new")[0]) |
| 177 | if verb == "put_existing": |
| 178 | return _status_outcome(_dav(f"/dav/files/{name}", token, "PUT", body=b"new")[0]) |
| 179 | if verb in ("move", "copy"): |
| 180 | return _status_outcome(_dav( |
| 181 | f"/dav/files/{name}", token, verb.upper(), headers=[("destination", "/dav/files/renamed.txt")] |
| 182 | )[0]) |
| 183 | raise AssertionError(verb) |
| 184 | |
| 185 | |
| 186 | def _answers(tmp_path, monkeypatch, mode, policy, subject, verb): |
| 187 | file_owner = ADMIN if subject == "admin" else OWNER |
| 188 | caller = {"owner": OWNER, "other": OTHER, "admin": ADMIN}[subject] |
| 189 | data_dir, ids = _box(tmp_path, monkeypatch, mode, policy, file_owner) |
| 190 | token = _key(data_dir, caller) |
| 191 | json_answer = _json(verb, token, ids["a.txt"], caller) |
| 192 | dav_answer = _webdav(verb, token, "b.txt") |
| 193 | return data_dir, ids, json_answer, dav_answer |
| 194 | |
| 195 | |
| 196 | # What the off and audit modes answer today: the API keys a desktop signs in |
| 197 | # with are not the admin token, so every byte and every write is refused on |
| 198 | # both surfaces. The folder listing is the one place they differ, and did |
| 199 | # before this file existed: WebDAV lists the caller's own file names (no |
| 200 | # bytes) with checks off, while the JSON list asks for the admin token. |
| 201 | UNENFORCED_LISTING_DIFFERS = {"list", "propfind_file"} |
| 202 | |
| 203 | |
| 204 | @pytest.mark.parametrize("verb", VERBS) |
| 205 | @pytest.mark.parametrize("subject", SUBJECTS) |
| 206 | @pytest.mark.parametrize("policy", sorted(POLICIES)) |
| 207 | @pytest.mark.parametrize("mode", MODES) |
| 208 | def test_json_and_webdav_agree(tmp_path, monkeypatch, mode, policy, subject, verb): |
| 209 | data_dir, ids, json_answer, dav_answer = _answers(tmp_path, monkeypatch, mode, policy, subject, verb) |
| 210 | |
| 211 | if subject == "other": |
| 212 | # Someone else's file is not in your folder: WebDAV can never reach |
| 213 | # it, so it must not do more than the JSON route, and the owner's |
| 214 | # file must come through untouched. |
| 215 | if verb == "put_new": |
| 216 | assert dav_answer == json_answer # a new file of their own |
| 217 | elif verb == "put_existing": |
| 218 | pass # a PUT of that name makes a new file of their own: checked below |
| 219 | else: |
| 220 | assert dav_answer in ("hidden", "refused"), (json_answer, dav_answer) |
| 221 | if json_answer == "refused" and mode == "enforced": |
| 222 | assert dav_answer == "refused" # the same collection-level refusal |
| 223 | assert object_user_files.read_file(OWNER, ids["b.txt"], base_dir=data_dir) == b"bytes" |
| 224 | [record] = [r for r in object_records.read_collection_records("files", base_dir=data_dir) |
| 225 | if r["id"] == ids["b.txt"]] |
| 226 | assert record["filename"] == "b.txt" and record["owner_id"] == OWNER |
| 227 | return |
| 228 | |
| 229 | if mode != "enforced" and verb in UNENFORCED_LISTING_DIFFERS: |
| 230 | assert (json_answer, dav_answer) == ("refused", "ok") |
| 231 | return |
| 232 | assert dav_answer == json_answer, f"JSON said {json_answer}, WebDAV said {dav_answer}" |
| 233 | |
| 234 | |
| 235 | def _expected_enforced(policy, subject, verb): |
| 236 | """The answer both surfaces give under enforcement, by the documented rule: |
| 237 | a request is decided at the collection level first, with no record and |
| 238 | so no owner fallback; only a caller who passes that question is decided |
| 239 | on the file itself.""" |
| 240 | if subject == "admin" or policy == "allow_all": |
| 241 | return "ok" |
| 242 | if policy == "no_rules": |
| 243 | return "refused" |
| 244 | # allow_read: reads of your own file only |
| 245 | return "ok" if verb in ("list", "propfind_file", "get", "head") else "refused" |
| 246 | |
| 247 | |
| 248 | @pytest.mark.parametrize("verb", VERBS) |
| 249 | @pytest.mark.parametrize("subject", ("owner", "admin")) |
| 250 | @pytest.mark.parametrize("policy", sorted(POLICIES)) |
| 251 | def test_enforced_answers_follow_the_documented_rule(tmp_path, monkeypatch, policy, subject, verb): |
| 252 | data_dir, ids, json_answer, dav_answer = _answers(tmp_path, monkeypatch, "enforced", policy, subject, verb) |
| 253 | expected = _expected_enforced(policy, subject, verb) |
| 254 | assert (json_answer, dav_answer) == (expected, expected) |
| 255 | if expected != "ok" and verb in ("delete", "move", "put_existing"): |
| 256 | # the refused write changed nothing on either surface |
| 257 | rows = {r["id"]: r for r in object_records.read_collection_records("files", base_dir=data_dir)} |
| 258 | assert rows[ids["a.txt"]]["filename"] == "a.txt" and rows[ids["b.txt"]]["filename"] == "b.txt" |
| 259 | owner = ADMIN if subject == "admin" else OWNER |
| 260 | assert object_user_files.read_file(owner, ids["b.txt"], base_dir=data_dir) == b"bytes" |
| 261 | |
| 262 | |
| 263 | @pytest.mark.parametrize("method", ("MKCOL", "LOCK", "UNLOCK")) |
| 264 | @pytest.mark.parametrize("policy", sorted(POLICIES)) |
| 265 | def test_unsupported_verbs_are_refused_the_same_way_under_any_policy(tmp_path, monkeypatch, policy, method): |
| 266 | data_dir, _ = _box(tmp_path, monkeypatch, "enforced", policy, OWNER) |
| 267 | status, _, _ = _dav("/dav/files/a.txt", _key(data_dir, OWNER), method) |
| 268 | assert status == 405 |
| 269 | |
| 270 | |
| 271 | def test_a_refused_folder_is_a_refusal_not_an_empty_listing(tmp_path, monkeypatch): |
| 272 | """A sync client that is shown an empty folder deletes its local copies; |
| 273 | one that is refused keeps them. The JSON list refuses with 403 too.""" |
| 274 | data_dir, _ = _box(tmp_path, monkeypatch, "enforced", "no_rules", OWNER) |
| 275 | token = _key(data_dir, OWNER) |
| 276 | for path, depth in (("/dav/files/", "1"), ("/dav/", "infinity")): |
| 277 | status, _, _ = _dav(path, token, "PROPFIND", headers=[("depth", depth)]) |
| 278 | assert status == 403 |
| 279 | status, _, _ = request("/collections/files/records", headers=_bearer(token)) |
| 280 | assert status == 403 |