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_ai_attachment_policy.py · 11.7 KB · 269 lines
| 1 | """A chat attachment is read only when GET /api/files/{id} would serve it. |
| 2 | |
| 3 | Attaching a file sends its contents to an AI provider, so it is a read of the |
| 4 | file. The chat route checked only that the caller owned the record, so under |
| 5 | an enforced policy that grants nothing on files the owner fallback alone let |
| 6 | the bytes out, while /api/files and WebDAV refused the same owner the same |
| 7 | file. It now asks the same question as GET /api/files: the collection-level |
| 8 | read first (no record, so no owner fallback), then the file itself. A refusal |
| 9 | is a 400 like any other bad attachment, made before the provider is called. |
| 10 | |
| 11 | With enforcement off or in audit mode nothing changes: an owner attaches |
| 12 | their own file, and nobody attaches anyone else's. In audit mode the same |
| 13 | questions are asked and recorded in the permission audit log, would-be |
| 14 | refusals included. |
| 15 | """ |
| 16 | |
| 17 | from __future__ import annotations |
| 18 | |
| 19 | import json |
| 20 | |
| 21 | import pytest |
| 22 | from ai_fakes import anthropic_message, chat_server, install_fake_transport, text_block |
| 23 | from test_object_server import raw_request, save_permission_policy, write_records |
| 24 | |
| 25 | import object_permission_audit |
| 26 | import object_server |
| 27 | import object_user_files |
| 28 | |
| 29 | OWNER, OTHER, ADMIN = "dan", "eve", "boss" |
| 30 | USER_ROLES = {ADMIN: ["admin"]} |
| 31 | |
| 32 | POLICIES = { |
| 33 | "no_rules": {"access_mode": "role_based", "rules": [], "user_roles": USER_ROLES}, |
| 34 | "allow_read": { |
| 35 | "access_mode": "role_based", |
| 36 | "user_roles": USER_ROLES, |
| 37 | "rules": [ |
| 38 | { |
| 39 | "effect": "allow", |
| 40 | "principal": "registered", |
| 41 | "actions": ["read"], |
| 42 | "collection": "files", |
| 43 | "row_filter": {"owner_id": "$user_id"}, |
| 44 | "reason": "own files, read only", |
| 45 | } |
| 46 | ], |
| 47 | }, |
| 48 | # passes the collection-level question (an allow rule matches there) but |
| 49 | # refuses the owner's private file itself: only public files, and the |
| 50 | # owner fallback switched off for reads |
| 51 | "public_only": { |
| 52 | "access_mode": "role_based", |
| 53 | "user_roles": USER_ROLES, |
| 54 | "rules": [ |
| 55 | { |
| 56 | "effect": "allow", |
| 57 | "principal": "registered", |
| 58 | "actions": ["read"], |
| 59 | "collection": "files", |
| 60 | "row_filter": {"is_public": "true"}, |
| 61 | "reason": "public files only", |
| 62 | }, |
| 63 | { |
| 64 | "effect": "deny", |
| 65 | "principal": "owner_fallback", |
| 66 | "actions": ["read"], |
| 67 | "collection": "files", |
| 68 | "reason": "only what the rules say", |
| 69 | }, |
| 70 | ], |
| 71 | }, |
| 72 | } |
| 73 | MODES = ("enforced", "audit", "off") |
| 74 | # subject -> (the caller, whose file they attach) |
| 75 | SUBJECTS = { |
| 76 | "owner": (OWNER, OWNER), |
| 77 | "other": (OTHER, OWNER), |
| 78 | "admin": (ADMIN, ADMIN), # an admin role attaching their own file |
| 79 | "admin_others": (ADMIN, OWNER), # ...and someone else's: still owner-only |
| 80 | } |
| 81 | |
| 82 | |
| 83 | def _set_mode(monkeypatch, mode): |
| 84 | monkeypatch.delenv(object_server.PERMISSION_ENFORCEMENT_ENV, raising=False) |
| 85 | monkeypatch.delenv(object_server.PERMISSION_AUDIT_ENV, raising=False) |
| 86 | if mode == "enforced": |
| 87 | monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true") |
| 88 | monkeypatch.setenv(object_server.PERMISSION_UNREADY_ENFORCEMENT_ENV, "true") |
| 89 | elif mode == "audit": |
| 90 | monkeypatch.setenv(object_server.PERMISSION_AUDIT_ENV, "true") |
| 91 | |
| 92 | |
| 93 | def _box(tmp_path, monkeypatch, mode, policy, caller, file_owner): |
| 94 | """A box with one text file of file_owner's, and a signed-in caller who |
| 95 | has a stored provider key. The mode is set last, so the setup requests |
| 96 | are not themselves decided by the policy.""" |
| 97 | data_dir, headers = chat_server(tmp_path, monkeypatch, user=caller) |
| 98 | write_records( |
| 99 | data_dir, "files", |
| 100 | f"id\tfilename\tcontent_type\tsize\tis_public\towner_id\n" |
| 101 | f"f1\tnotes.txt\ttext/plain\t6\tfalse\t{file_owner}\n", |
| 102 | ) |
| 103 | object_user_files.save_file(file_owner, "f1", b"secret", base_dir=data_dir) |
| 104 | monkeypatch.setenv(object_server.USER_FILES_ENABLED_ENV, "true") |
| 105 | save_permission_policy(data_dir, POLICIES[policy]) |
| 106 | _set_mode(monkeypatch, mode) |
| 107 | return data_dir, headers |
| 108 | |
| 109 | |
| 110 | def _attach(monkeypatch, headers, attachments, *, stream=False): |
| 111 | calls = [] |
| 112 | install_fake_transport(monkeypatch, [anthropic_message([text_block("read it")])], seen=calls) |
| 113 | body = {"message": "summarize", "attachments": attachments} |
| 114 | if stream: |
| 115 | body["stream"] = True |
| 116 | status, _, payload = raw_request( |
| 117 | "/api/ai/chat", method="POST", body=json.dumps(body).encode(), headers=headers, |
| 118 | ) |
| 119 | return status, payload, calls |
| 120 | |
| 121 | |
| 122 | def _expected(mode, policy, subject): |
| 123 | """ok; hidden (answered like a missing file); or refused at the |
| 124 | collection level (the same answer for every id).""" |
| 125 | caller, file_owner = SUBJECTS[subject] |
| 126 | admin = caller == ADMIN |
| 127 | if mode == "enforced" and policy == "no_rules" and not admin: |
| 128 | return "refused" # no rule grants read on files; the owner fallback does not answer that |
| 129 | if caller != file_owner: |
| 130 | return "hidden" # owner-only, in every mode, admin role or not |
| 131 | if mode != "enforced" or admin or policy == "allow_read": |
| 132 | return "ok" |
| 133 | return "hidden" # public_only: the collection passes, the private file does not |
| 134 | |
| 135 | |
| 136 | @pytest.mark.parametrize("subject", sorted(SUBJECTS)) |
| 137 | @pytest.mark.parametrize("policy", sorted(POLICIES)) |
| 138 | @pytest.mark.parametrize("mode", MODES) |
| 139 | def test_an_attachment_is_read_only_when_the_policy_allows_it(tmp_path, monkeypatch, mode, policy, subject): |
| 140 | caller, file_owner = SUBJECTS[subject] |
| 141 | _, headers = _box(tmp_path, monkeypatch, mode, policy, caller, file_owner) |
| 142 | |
| 143 | status, raw, calls = _attach(monkeypatch, headers, ["f1"]) |
| 144 | payload = json.loads(raw) |
| 145 | |
| 146 | if _expected(mode, policy, subject) == "ok": |
| 147 | assert status == 200, payload |
| 148 | assert len(calls) == 1 |
| 149 | assert "secret" in json.dumps(calls[0]["body"]) |
| 150 | return |
| 151 | assert status == 400, payload |
| 152 | assert calls == [], "the provider was called for a refused attachment" |
| 153 | assert "notes.txt" not in raw.decode() |
| 154 | assert "secret" not in raw.decode() |
| 155 | [problem] = payload["problems"] |
| 156 | if _expected(mode, policy, subject) == "hidden": |
| 157 | assert problem.startswith("f1: no such file among yours") |
| 158 | else: |
| 159 | assert "f1" not in problem and "permission policy does not let you read files" in problem |
| 160 | |
| 161 | |
| 162 | @pytest.mark.parametrize("subject", sorted(SUBJECTS)) |
| 163 | @pytest.mark.parametrize("policy", sorted(POLICIES)) |
| 164 | def test_chat_and_the_file_route_agree_under_enforcement(tmp_path, monkeypatch, policy, subject): |
| 165 | caller, file_owner = SUBJECTS[subject] |
| 166 | _, headers = _box(tmp_path, monkeypatch, "enforced", policy, caller, file_owner) |
| 167 | |
| 168 | file_status = raw_request("/api/files/f1", headers=headers[:1])[0] |
| 169 | chat_status, raw, calls = _attach(monkeypatch, headers, ["f1"]) |
| 170 | |
| 171 | assert (chat_status == 200) == bool(calls) |
| 172 | if subject == "admin_others": |
| 173 | # the file route serves an admin role anyone's file; chat attachments |
| 174 | # stay owner-only, so chat never does more than the file route |
| 175 | assert (file_status, chat_status) == (200, 400), raw |
| 176 | return |
| 177 | assert (file_status == 200) == (chat_status == 200), (file_status, raw) |
| 178 | |
| 179 | |
| 180 | def test_a_refused_file_is_indistinguishable_from_a_missing_one(tmp_path, monkeypatch): |
| 181 | """A file refused on the record gives the same problem text as an id |
| 182 | that does not exist.""" |
| 183 | _, headers = _box(tmp_path, monkeypatch, "enforced", "public_only", OWNER, OWNER) |
| 184 | status, raw, calls = _attach(monkeypatch, headers, ["f1", "nosuch"]) |
| 185 | payload = json.loads(raw) |
| 186 | assert status == 400 and calls == [] |
| 187 | refused, missing = payload["problems"] |
| 188 | assert refused.replace("f1", "ID") == missing.replace("nosuch", "ID") |
| 189 | |
| 190 | |
| 191 | def test_a_collection_refusal_is_one_problem_whatever_the_ids(tmp_path, monkeypatch): |
| 192 | """Refused at the collection level, the answer does not depend on which |
| 193 | ids were sent, so it says nothing about which exist.""" |
| 194 | _, headers = _box(tmp_path, monkeypatch, "enforced", "no_rules", OWNER, OWNER) |
| 195 | answers = [] |
| 196 | for ids in (["f1"], ["nosuch"], ["f1", "nosuch"]): |
| 197 | status, raw, calls = _attach(monkeypatch, headers, ids) |
| 198 | assert status == 400 and calls == [] |
| 199 | answers.append(json.loads(raw)) |
| 200 | assert answers[0] == answers[1] == answers[2] |
| 201 | |
| 202 | |
| 203 | def test_one_refused_attachment_sends_none_of_them(tmp_path, monkeypatch): |
| 204 | """No partial send: an allowed file next to a refused one is not sent.""" |
| 205 | data_dir, headers = _box(tmp_path, monkeypatch, "enforced", "allow_read", OWNER, OWNER) |
| 206 | write_records( |
| 207 | data_dir, "files", |
| 208 | "id\tfilename\tcontent_type\tsize\tis_public\towner_id\n" |
| 209 | "f1\tnotes.txt\ttext/plain\t6\tfalse\tdan\n" |
| 210 | "f2\ttheirs.txt\ttext/plain\t6\tfalse\teve\n", |
| 211 | ) |
| 212 | object_user_files.save_file(OTHER, "f2", b"theirs", base_dir=data_dir) |
| 213 | status, raw, calls = _attach(monkeypatch, headers, ["f1", "f2"]) |
| 214 | assert status == 400 and calls == [], raw |
| 215 | |
| 216 | |
| 217 | def test_a_refused_attachment_on_a_streamed_turn_is_refused_before_the_stream(tmp_path, monkeypatch): |
| 218 | _, headers = _box(tmp_path, monkeypatch, "enforced", "no_rules", OWNER, OWNER) |
| 219 | status, raw, calls = _attach(monkeypatch, headers, ["f1"], stream=True) |
| 220 | assert status == 400 and calls == [], raw |
| 221 | |
| 222 | |
| 223 | def test_without_attachments_chat_is_unchanged_under_a_policy_with_no_files_rules(tmp_path, monkeypatch): |
| 224 | """The files question is asked only when something is attached.""" |
| 225 | _, headers = _box(tmp_path, monkeypatch, "enforced", "no_rules", OWNER, OWNER) |
| 226 | status, raw, calls = _attach(monkeypatch, headers, []) |
| 227 | assert status == 200 and len(calls) == 1, raw |
| 228 | |
| 229 | |
| 230 | def test_an_unreadable_policy_is_a_503_not_a_missing_file(tmp_path, monkeypatch): |
| 231 | """Under enforcement an unreadable policy decides nothing: the chat says |
| 232 | so as the file route does (503), sends nothing, and does not blame the |
| 233 | attachment.""" |
| 234 | import object_permission_store |
| 235 | |
| 236 | data_dir, headers = _box(tmp_path, monkeypatch, "enforced", "allow_read", OWNER, OWNER) |
| 237 | object_permission_store.policy_path(data_dir).write_text("{not json") |
| 238 | file_status = raw_request("/api/files/f1", headers=headers[:1])[0] |
| 239 | status, raw, calls = _attach(monkeypatch, headers, ["f1"]) |
| 240 | assert (status, file_status) == (503, 503), raw |
| 241 | assert calls == [] |
| 242 | assert json.loads(raw)["code"] == object_server.PERMISSION_POLICY_UNAVAILABLE_CODE |
| 243 | |
| 244 | |
| 245 | @pytest.mark.parametrize("policy", sorted(POLICIES)) |
| 246 | def test_audit_mode_records_the_attachment_decisions(tmp_path, monkeypatch, policy): |
| 247 | """Audit mode serves the attachment as off does, but records what |
| 248 | enforcement would have decided, a would-be refusal included: the |
| 249 | attachment path returned before asking, so it left no audit entry.""" |
| 250 | data_dir, headers = _box(tmp_path, monkeypatch, "audit", policy, OWNER, OWNER) |
| 251 | before = object_permission_audit.get_permission_audit(data_dir, collection="files") |
| 252 | |
| 253 | status, raw, calls = _attach(monkeypatch, headers, ["f1"]) |
| 254 | assert status == 200 and len(calls) == 1, raw |
| 255 | |
| 256 | entries = object_permission_audit.get_permission_audit(data_dir, collection="files") |
| 257 | entries = entries[len(before):] |
| 258 | assert [(e["action"], e["enforced"], e["subject"]["user_id"]) for e in entries] == [ |
| 259 | ("read", False, OWNER), ("read", False, OWNER)] # the collection, then the file |
| 260 | would_be = "refused" if _expected("enforced", policy, "owner") != "ok" else "ok" |
| 261 | allowed = [e["decision"]["allowed"] for e in entries] |
| 262 | assert all(allowed) == (would_be == "ok"), entries |
| 263 | |
| 264 | |
| 265 | def test_off_mode_records_nothing(tmp_path, monkeypatch): |
| 266 | data_dir, headers = _box(tmp_path, monkeypatch, "off", "no_rules", OWNER, OWNER) |
| 267 | status, raw, _ = _attach(monkeypatch, headers, ["f1"]) |
| 268 | assert status == 200, raw |
| 269 | assert object_permission_audit.get_permission_audit(data_dir, collection="files") == [] |