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_field_visibility_leaks.py · 13.6 KB · 323 lines
| 1 | """Field visibility, through the HTTP app with enforcement on. |
| 2 | |
| 3 | A caller must not learn, by any answer, the value of a field that a GET of |
| 4 | the same row by the same caller hides. Each test here reproduced a way to do |
| 5 | it before the fix: |
| 6 | |
| 7 | - a list filter on a field that is filterable for the collection as a whole |
| 8 | but redacted on some rows (an own-rows rule with no field list beside a |
| 9 | role rule with one) answered "this row's hidden value is X" by whether the |
| 10 | row came back; |
| 11 | - a create, update or delete answered with the stored row, so a field the |
| 12 | caller's own GET hides (a rule's `denied_fields`, a role rule's field |
| 13 | list, a schema-hidden field) came back in the write's answer, and a caller |
| 14 | who may write a row but not read it got the whole row; |
| 15 | - a list decided which rows to return at one reading of the clock and how |
| 16 | to redact them at another, so a rule whose window closed in between let |
| 17 | the row through and then redacted nothing; |
| 18 | - app-worker's profile_comments.status was `public: hidden`, hidden from |
| 19 | every caller (the author and the admin token too). |
| 20 | """ |
| 21 | |
| 22 | import json |
| 23 | from datetime import datetime, timedelta, timezone |
| 24 | |
| 25 | import pytest |
| 26 | |
| 27 | import object_permissions |
| 28 | import object_server |
| 29 | from scripts.try_package import Sandbox |
| 30 | |
| 31 | RECORDS = "/collections/tickets/records" |
| 32 | |
| 33 | OWN_ROWS = {"effect": "allow", "principal": "registered", |
| 34 | "actions": ["create", "read", "update", "delete"], "collection": "tickets", |
| 35 | "row_filter": {"owner_id": "$user_id"}, |
| 36 | "reason": "people manage their own tickets"} |
| 37 | SUPPORT = {"effect": "allow", "principal": "role:support", "actions": ["read"], |
| 38 | "collection": "tickets", "fields": ["id", "title", "owner_id"], |
| 39 | "reason": "support sees every ticket, not the salary band"} |
| 40 | |
| 41 | |
| 42 | def _package(root, rules): |
| 43 | pkg = root / "tickets" |
| 44 | (pkg / "schemas").mkdir(parents=True) |
| 45 | (pkg / "permissions").mkdir() |
| 46 | (pkg / "dbbasic-package.json").write_text(json.dumps({ |
| 47 | "id": "tickets", "name": "Tickets", "version": "0.1.0", |
| 48 | "schemas": [{"collection": "tickets", "path": "schemas/tickets.json"}], |
| 49 | "permissions": [{"path": "permissions/rules.json"}]})) |
| 50 | (pkg / "schemas" / "tickets.json").write_text(json.dumps({ |
| 51 | "name": "tickets", "version": 1, |
| 52 | "fields": [{"name": "id"}, {"name": "title", "type": "text"}, |
| 53 | {"name": "salary_band", "type": "text"}, |
| 54 | {"name": "grade", "type": "integer"}, |
| 55 | {"name": "memo", "type": "text"}, |
| 56 | # Hidden from the row's owner only: shown on others' rows. |
| 57 | {"name": "flag", "type": "text", "permissions": {"owner": "hidden"}}, |
| 58 | {"name": "owner_id", "type": "text"}]})) |
| 59 | (pkg / "permissions" / "rules.json").write_text(json.dumps({"rules": rules})) |
| 60 | return root |
| 61 | |
| 62 | |
| 63 | @pytest.fixture() |
| 64 | def box_with(tmp_path): |
| 65 | boxes = [] |
| 66 | |
| 67 | def make(*rules): |
| 68 | assert not boxes, "one box per test: a Sandbox sets process environment" |
| 69 | box = Sandbox(["tickets"], packages_dir=_package(tmp_path, list(rules))) |
| 70 | box.__enter__() |
| 71 | boxes.append(box) |
| 72 | box.add_user("ann") |
| 73 | box.add_user("sam", roles=["support"]) |
| 74 | return box |
| 75 | |
| 76 | yield make |
| 77 | for box in boxes: |
| 78 | box.__exit__(None, None, None) |
| 79 | |
| 80 | |
| 81 | def _titles(body): |
| 82 | return sorted(r["title"] for r in body["records"]) |
| 83 | |
| 84 | |
| 85 | # 1. a list filter is not a value oracle -------------------------------------- |
| 86 | |
| 87 | def _seed_bands(box): |
| 88 | assert box.call("ann", "POST", RECORDS, {"title": "ann's", "salary_band": "A", "grade": 7})[0] == 201 |
| 89 | assert box.call("sam", "POST", RECORDS, {"title": "sam's", "salary_band": "C", "grade": 2})[0] == 201 |
| 90 | |
| 91 | |
| 92 | def test_list_hides_the_field_the_filter_would_probe(box_with): |
| 93 | box = box_with(OWN_ROWS, SUPPORT) |
| 94 | _seed_bands(box) |
| 95 | status, body = box.call("sam", "GET", RECORDS) |
| 96 | assert status == 200 |
| 97 | rows = {r["title"]: r for r in body["records"]} |
| 98 | assert "salary_band" not in rows["ann's"] |
| 99 | assert rows["sam's"]["salary_band"] == "C" |
| 100 | |
| 101 | |
| 102 | @pytest.mark.parametrize("query", [ |
| 103 | "salary_band=A", "salary_band=B", "salary_band.ne=B", "salary_band.in=A,B", |
| 104 | "grade.gte=5", "grade.lt=5", |
| 105 | ]) |
| 106 | def test_filter_never_matches_a_row_where_the_field_is_hidden(box_with, query): |
| 107 | box = box_with(OWN_ROWS, SUPPORT) |
| 108 | _seed_bands(box) |
| 109 | status, body = box.call("sam", "GET", f"{RECORDS}?{query}") |
| 110 | assert status == 200, body |
| 111 | assert "ann's" not in _titles(body) |
| 112 | |
| 113 | |
| 114 | def test_filter_still_matches_where_the_field_is_readable(box_with): |
| 115 | box = box_with(OWN_ROWS, SUPPORT) |
| 116 | _seed_bands(box) |
| 117 | status, body = box.call("sam", "GET", f"{RECORDS}?salary_band=C") |
| 118 | assert (status, _titles(body)) == (200, ["sam's"]) |
| 119 | # A field readable on every row filters every row, as before. |
| 120 | status, body = box.call("sam", "GET", f"{RECORDS}?title=ann's") |
| 121 | assert (status, _titles(body)) == (200, ["ann's"]) |
| 122 | assert body["total"] == 1 |
| 123 | |
| 124 | |
| 125 | def test_admin_token_filter_unchanged(box_with): |
| 126 | box = box_with(OWN_ROWS, SUPPORT) |
| 127 | _seed_bands(box) |
| 128 | status, body = box.call("admin", "GET", f"{RECORDS}?salary_band=A") |
| 129 | assert (status, _titles(body)) == (200, ["ann's"]) |
| 130 | |
| 131 | |
| 132 | READ_ALL = {"effect": "allow", "principal": "registered", "actions": ["read"], |
| 133 | "collection": "tickets", "reason": "everyone signed in reads every ticket"} |
| 134 | |
| 135 | |
| 136 | def test_filter_on_a_schema_field_hidden_from_the_owner(box_with): |
| 137 | """The schema hides `flag` from a row's owner and from nobody else, so |
| 138 | the collection-level check finds it filterable; on the caller's own |
| 139 | row it is hidden, and the filter must not answer for it there.""" |
| 140 | box = box_with(OWN_ROWS, READ_ALL) |
| 141 | status, body = box.call("admin", "POST", RECORDS, {"title": "ann's", "owner_id": "ann", "flag": "watch"}) |
| 142 | assert status == 201, body |
| 143 | status, body = box.call("ann", "GET", RECORDS) |
| 144 | assert "flag" not in body["records"][0] |
| 145 | for query in ("flag=watch", "flag.ne=calm"): |
| 146 | status, body = box.call("ann", "GET", f"{RECORDS}?{query}") |
| 147 | assert (status, body["records"]) == (200, []), query |
| 148 | # sam is not the owner: the field is his to read, and to filter on. |
| 149 | status, body = box.call("sam", "GET", f"{RECORDS}?flag=watch") |
| 150 | assert (status, _titles(body)) == (200, ["ann's"]) |
| 151 | |
| 152 | |
| 153 | # 2. a write answers with what the writer's own GET shows --------------------- |
| 154 | |
| 155 | OWN_NO_MEMO = dict(OWN_ROWS, denied_fields=["memo"]) |
| 156 | |
| 157 | |
| 158 | def test_write_answers_leave_out_a_field_the_writers_get_hides(box_with): |
| 159 | box = box_with(OWN_NO_MEMO) |
| 160 | status, body = box.call("ann", "POST", RECORDS, {"title": "a", "memo": "mine to write"}) |
| 161 | assert status == 201, body |
| 162 | assert "memo" not in body["record"] |
| 163 | assert body["record"]["title"] == "a" |
| 164 | path = f"{RECORDS}/{body['record']['id']}" |
| 165 | assert box.call("admin", "PUT", path, {"memo": "staff only: refund refused"})[0] == 200 |
| 166 | |
| 167 | status, got = box.call("ann", "GET", path) |
| 168 | assert status == 200 and "memo" not in got["record"] |
| 169 | |
| 170 | status, body = box.call("ann", "PUT", path, {"title": "b"}) |
| 171 | assert status == 200, body |
| 172 | assert body["record"] == {**got["record"], "title": "b"} |
| 173 | # The rev is still the one a GET gives, over the full stored row. |
| 174 | assert body["_rev"] == box.call("ann", "GET", path)[1]["_rev"] |
| 175 | |
| 176 | status, body = box.call("ann", "DELETE", path) |
| 177 | assert status == 200, body |
| 178 | assert body["deleted"] is True |
| 179 | assert "memo" not in body["record"] |
| 180 | assert body["record"]["title"] == "b" |
| 181 | |
| 182 | |
| 183 | def test_write_answers_keep_every_field_for_the_admin_token(box_with): |
| 184 | box = box_with(OWN_NO_MEMO) |
| 185 | status, body = box.call("admin", "POST", RECORDS, {"title": "a", "owner_id": "ann", "memo": "m"}) |
| 186 | assert status == 201 and body["record"]["memo"] == "m" |
| 187 | |
| 188 | |
| 189 | SUPPORT_EDITS = {"effect": "allow", "principal": "role:support", "actions": ["read", "update"], |
| 190 | "collection": "tickets", "fields": ["id", "title", "owner_id"], |
| 191 | "reason": "support retitles any ticket, without seeing the salary band"} |
| 192 | |
| 193 | |
| 194 | def test_update_answer_follows_a_role_rules_field_list(box_with): |
| 195 | box = box_with(OWN_ROWS, SUPPORT_EDITS) |
| 196 | status, body = box.call("ann", "POST", RECORDS, {"title": "a", "salary_band": "A"}) |
| 197 | path = f"{RECORDS}/{body['record']['id']}" |
| 198 | status, body = box.call("sam", "PUT", path, {"title": "retitled"}) |
| 199 | assert status == 200, body |
| 200 | assert body["record"] == {"id": body["record"]["id"], "title": "retitled", "owner_id": "ann"} |
| 201 | |
| 202 | |
| 203 | WRITE_ONLY = {"effect": "allow", "principal": "role:clerk", "actions": ["create", "update", "delete"], |
| 204 | "collection": "tickets", "on_behalf": True, |
| 205 | "reason": "a clerk files and fixes tickets for others, and cannot read them back"} |
| 206 | |
| 207 | |
| 208 | def test_write_without_read_answers_with_the_id_only(box_with): |
| 209 | """The owner fallback lets a row's owner read it, so the clerk writes |
| 210 | rows owned by someone else: allowed to write them, not to read them.""" |
| 211 | box = box_with(WRITE_ONLY) |
| 212 | box.add_user("cleo", roles=["clerk"]) |
| 213 | status, body = box.call("cleo", "POST", RECORDS, {"title": "a", "owner_id": "ann", "salary_band": "A"}) |
| 214 | assert status == 201, body |
| 215 | record_id = body["record"]["id"] |
| 216 | assert body["record"] == {"id": record_id} |
| 217 | path = f"{RECORDS}/{record_id}" |
| 218 | assert box.call("cleo", "GET", path)[0] in (403, 404) |
| 219 | |
| 220 | status, body = box.call("cleo", "PUT", path, {"title": "b"}) |
| 221 | assert status == 200, body |
| 222 | assert body["record"] == {"id": record_id} |
| 223 | assert "_rev" not in body |
| 224 | |
| 225 | status, body = box.call("cleo", "DELETE", path) |
| 226 | assert status == 200, body |
| 227 | assert body["record"] == {"id": record_id} and body["deleted"] is True |
| 228 | |
| 229 | |
| 230 | def test_update_answer_leaves_out_a_schema_field_hidden_from_the_owner(box_with): |
| 231 | box = box_with(OWN_ROWS) |
| 232 | status, body = box.call("admin", "POST", RECORDS, {"title": "a", "owner_id": "ann", "flag": "watch"}) |
| 233 | path = f"{RECORDS}/{body['record']['id']}" |
| 234 | status, body = box.call("ann", "PUT", path, {"title": "b"}) |
| 235 | assert status == 200, body |
| 236 | assert "flag" not in body["record"] |
| 237 | |
| 238 | |
| 239 | # 3. one clock reading per request -------------------------------------------- |
| 240 | |
| 241 | WINDOW_CLOSES = datetime(2026, 12, 3, 12, 0, tzinfo=timezone.utc) |
| 242 | SUPPORT_UNTIL_NOON = dict(SUPPORT, expires_at="2026-12-03T12:00:00Z", |
| 243 | reason="support covers the morning shift, not the salary band") |
| 244 | |
| 245 | |
| 246 | class _Clock: |
| 247 | """A wall clock that reads one second before the window closes until |
| 248 | `late` is set, and one second after from then on.""" |
| 249 | late = False |
| 250 | |
| 251 | @classmethod |
| 252 | def read(cls): |
| 253 | return WINDOW_CLOSES + timedelta(seconds=1 if cls.late else -1) |
| 254 | |
| 255 | |
| 256 | def _fake_datetime(clock): |
| 257 | class FakeDatetime(datetime): |
| 258 | @classmethod |
| 259 | def now(cls, tz=None): |
| 260 | return clock.read() |
| 261 | return FakeDatetime |
| 262 | |
| 263 | |
| 264 | def test_a_list_reads_the_clock_once(box_with, monkeypatch): |
| 265 | """The window of the only rule that lets sam read ann's ticket closes |
| 266 | while the list runs: between deciding which rows to return and |
| 267 | redacting them. Read the clock twice and the row was let through by the |
| 268 | rule, then redacted by a decision that found no rule -- and so removed |
| 269 | no field. One reading: the row is returned as the rule shows it.""" |
| 270 | box = box_with(OWN_ROWS, SUPPORT_UNTIL_NOON) |
| 271 | _seed_bands(box) |
| 272 | clock = type("Clock", (_Clock,), {"late": False}) |
| 273 | fake = _fake_datetime(clock) |
| 274 | monkeypatch.setattr(object_permissions, "datetime", fake) |
| 275 | monkeypatch.setattr(object_server, "datetime", fake) |
| 276 | redact = object_server._redact_records_for_permission |
| 277 | |
| 278 | def redact_after_the_window(*args, **kwargs): |
| 279 | clock.late = True |
| 280 | return redact(*args, **kwargs) |
| 281 | |
| 282 | monkeypatch.setattr(object_server, "_redact_records_for_permission", redact_after_the_window) |
| 283 | status, body = box.call("sam", "GET", RECORDS) |
| 284 | assert status == 200, body |
| 285 | rows = {r["title"]: r for r in body["records"]} |
| 286 | assert "salary_band" not in rows["ann's"] |
| 287 | assert rows["sam's"]["salary_band"] == "C" |
| 288 | |
| 289 | |
| 290 | # 4. app-worker profile_comments.status: the thread_comments grant ------------ |
| 291 | |
| 292 | COMMENTS = "/collections/profile_comments/records" |
| 293 | |
| 294 | |
| 295 | def test_profile_comment_status_follows_the_thread_comments_grant(): |
| 296 | with Sandbox(["app-worker"]) as box: |
| 297 | box.add_user("ann") |
| 298 | box.add_user("bob") |
| 299 | box.add_user("mo", roles=["moderator"]) |
| 300 | status, profile = box.call("admin", "POST", "/collections/profiles/records", |
| 301 | {"owner_id": "pat", "display_name": "Pat", "slug": "pat"}) |
| 302 | assert status == 201, profile |
| 303 | status, body = box.call("ann", "POST", COMMENTS, |
| 304 | {"profile_id": profile["record"]["id"], "content": "hi"}) |
| 305 | assert status == 201, body |
| 306 | path = f"{COMMENTS}/{body['record']['id']}" |
| 307 | assert body["record"]["status"] == "pending" # the author's write answer says so |
| 308 | |
| 309 | # The author reads it: their pending comment says it is pending. |
| 310 | status, body = box.call("ann", "GET", path) |
| 311 | assert (status, body["record"]["status"]) == (200, "pending") |
| 312 | status, body = box.call("ann", "GET", COMMENTS) |
| 313 | assert [r.get("status") for r in body["records"]] == ["pending"] |
| 314 | # ... but may not set it: no approving your own comment. |
| 315 | status, body = box.call("ann", "PUT", path, {"status": "approved"}) |
| 316 | assert status == 403 and body["denied_fields"] == ["status"] |
| 317 | # Somebody else signed in, and a visitor, do not see a pending comment. |
| 318 | assert box.call("bob", "GET", path)[0] == 404 |
| 319 | assert box.call(None, "GET", path)[0] == 404 |
| 320 | # The admin token reads the row; status stays hidden from it, as it is |
| 321 | # on thread_comments (only the author and moderators are named). |
| 322 | status, body = box.call("admin", "GET", path) |
| 323 | assert status == 200 and "status" not in body["record"] |