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_identity_grant_reads.py · 14.4 KB · 317 lines
| 1 | """Identity resolution reads one user's grant rows, fresh, without copying everyone's. |
| 2 | |
| 3 | A signed-in request resolves its subject two to five times, and each time |
| 4 | read all of project_access, projects and record_shares -- copying every row |
| 5 | of every user -- to keep the three or four that belong to this one. It now |
| 6 | asks object_records.read_collection_records_where for just those rows. |
| 7 | |
| 8 | That function is not a cache and not an index: it tests every row of the |
| 9 | current records snapshot on every call. So the claims here are (1) it |
| 10 | returns exactly what filtering the full read returns, and (2) a grant given |
| 11 | or taken away, by any writer, is in force on the very next resolution. |
| 12 | """ |
| 13 | |
| 14 | import json |
| 15 | from pathlib import Path |
| 16 | |
| 17 | import pytest |
| 18 | |
| 19 | import object_collections |
| 20 | import object_permissions |
| 21 | import object_records |
| 22 | import object_server |
| 23 | from test_object_server import request, write_records |
| 24 | |
| 25 | |
| 26 | def full_then_filter(collection, field, value, data_dir): |
| 27 | """The oracle: what callers did before.""" |
| 28 | return [ |
| 29 | record |
| 30 | for record in object_records.read_collection_records(collection, base_dir=data_dir, roots=[]) |
| 31 | if record.get(field) == value |
| 32 | ] |
| 33 | |
| 34 | |
| 35 | def where(collection, field, value, data_dir): |
| 36 | return object_records.read_collection_records_where(collection, field, value, base_dir=data_dir, roots=[]) |
| 37 | |
| 38 | |
| 39 | ACCESS = ( |
| 40 | "id\tproject_id\tuser_id\tpermission\n" |
| 41 | "a1\tp1\tu7\tread\n" |
| 42 | "a2\tp2\tu8\twrite\n" |
| 43 | "a3\tp3\tu7\twrite\n" |
| 44 | "a4\t\tu7\tread\n" |
| 45 | "a5\tp1\tu7\tread\n" |
| 46 | "a6\tp9\t\tread\n" |
| 47 | ) |
| 48 | PROJECTS = "id\tname\towner_id\np1\tOne\tu8\np2\tTwo\tu7\np3\tThree\tu9\n\tNameless\tu7\np5\tFive\tu7\n" |
| 49 | SHARES = ( |
| 50 | "id\tcollection\trecord_id\tuser_id\tpermission\n" |
| 51 | "s1\tnotes\tn1\tu7\tread\n" |
| 52 | "s2\tnotes\tn2\tu7\twrite\n" |
| 53 | "s3\ttasks\tt1\tu8\twrite\n" |
| 54 | "s4\t\tn3\tu7\tread\n" |
| 55 | "s5\tnotes\tn1\tu7\tread\n" |
| 56 | ) |
| 57 | |
| 58 | |
| 59 | @pytest.fixture |
| 60 | def data_dir(tmp_path, monkeypatch): |
| 61 | data_dir = tmp_path / "data" |
| 62 | write_records(data_dir, "project_access", ACCESS) |
| 63 | write_records(data_dir, "projects", PROJECTS) |
| 64 | write_records(data_dir, "record_shares", SHARES) |
| 65 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 66 | monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true") |
| 67 | return data_dir |
| 68 | |
| 69 | |
| 70 | def resolved(user_id: str) -> object_permissions.PermissionSubject: |
| 71 | subject = object_permissions.PermissionSubject(user_id=user_id) |
| 72 | return object_server._with_shared_records(object_server._with_accessible_projects(subject)) |
| 73 | |
| 74 | |
| 75 | def reference(user_id: str, data_dir: Path) -> object_permissions.PermissionSubject: |
| 76 | """The resolution as it was written before, over full reads.""" |
| 77 | subject = object_permissions.PermissionSubject(user_id=user_id) |
| 78 | |
| 79 | def rows(collection): |
| 80 | try: |
| 81 | return object_records.read_collection_records(collection, base_dir=data_dir) |
| 82 | except (LookupError, OSError, ValueError): |
| 83 | return [] |
| 84 | |
| 85 | access = [r for r in rows("project_access") if r.get("user_id") == user_id and r.get("project_id")] |
| 86 | project_ids = [r["project_id"] for r in access] |
| 87 | writable = [r["project_id"] for r in access if r.get("permission") == "write"] |
| 88 | owned = [r["id"] for r in rows("projects") if r.get("owner_id") == user_id and r.get("id")] |
| 89 | if project_ids or owned: |
| 90 | subject = subject.with_projects(dict.fromkeys(project_ids), dict.fromkeys(owned), dict.fromkeys(writable)) |
| 91 | shared: dict[str, list[str]] = {} |
| 92 | writable_shared: dict[str, list[str]] = {} |
| 93 | for row in rows("record_shares"): |
| 94 | if row.get("user_id") != user_id or not row.get("collection") or not row.get("record_id"): |
| 95 | continue |
| 96 | shared.setdefault(row["collection"], []).append(row["record_id"]) |
| 97 | if row.get("permission") == "write": |
| 98 | writable_shared.setdefault(row["collection"], []).append(row["record_id"]) |
| 99 | if shared: |
| 100 | subject = subject.with_shares( |
| 101 | {k: list(dict.fromkeys(v)) for k, v in shared.items()}, |
| 102 | {k: list(dict.fromkeys(v)) for k, v in writable_shared.items()}, |
| 103 | ) |
| 104 | return subject |
| 105 | |
| 106 | |
| 107 | # --- the storage function --------------------------------------------------------------------- |
| 108 | |
| 109 | |
| 110 | @pytest.mark.parametrize("collection,field,value", [ |
| 111 | ("project_access", "user_id", "u7"), |
| 112 | ("project_access", "user_id", "u8"), |
| 113 | ("project_access", "user_id", "nobody"), |
| 114 | ("project_access", "user_id", ""), |
| 115 | ("project_access", "user_id", None), |
| 116 | ("project_access", "permission", "write"), |
| 117 | ("project_access", "no_such_field", "x"), |
| 118 | ("project_access", "no_such_field", None), |
| 119 | ("projects", "owner_id", "u7"), |
| 120 | ("record_shares", "user_id", "u7"), |
| 121 | ]) |
| 122 | def test_where_returns_what_filtering_the_full_read_returns(data_dir, collection, field, value): |
| 123 | assert where(collection, field, value, data_dir) == full_then_filter(collection, field, value, data_dir) |
| 124 | |
| 125 | |
| 126 | def test_where_keeps_file_order_and_hands_out_copies(data_dir): |
| 127 | rows = where("project_access", "user_id", "u7", data_dir) |
| 128 | assert [r["id"] for r in rows] == ["a1", "a3", "a4", "a5"] |
| 129 | rows[0]["user_id"] = "tampered" |
| 130 | rows[0]["project_id"] = "tampered" |
| 131 | assert where("project_access", "user_id", "u7", data_dir) == full_then_filter( |
| 132 | "project_access", "user_id", "u7", data_dir |
| 133 | ) |
| 134 | assert [r["id"] for r in where("project_access", "user_id", "u7", data_dir)] == ["a1", "a3", "a4", "a5"] |
| 135 | |
| 136 | |
| 137 | def test_where_on_a_field_stored_in_the_extra_column_sees_the_surfaced_value(tmp_path): |
| 138 | """A `store: extra` field is not a column: its value is inside the JSON |
| 139 | `extra` cell and only exists on the surfaced copy.""" |
| 140 | data_dir = tmp_path / "data" |
| 141 | (data_dir / "schemas").mkdir(parents=True) |
| 142 | (data_dir / "schemas" / "grants.json").write_text(json.dumps({"fields": [ |
| 143 | {"name": "id"}, {"name": "user_id", "store": "extra"}, {"name": "extra"}, |
| 144 | ]})) |
| 145 | write_records(data_dir, "grants", ( |
| 146 | "id\textra\tuser_id\n" |
| 147 | 'g1\t{"user_id": "u7"}\tstale-column\n' |
| 148 | 'g2\t{"user_id": "u8"}\tu7\n' |
| 149 | "g3\t\tu7\n" |
| 150 | )) |
| 151 | assert [r["id"] for r in where("grants", "user_id", "u7", data_dir)] == ["g1"] |
| 152 | assert where("grants", "user_id", "u7", data_dir) == full_then_filter("grants", "user_id", "u7", data_dir) |
| 153 | assert where("grants", "user_id", "", data_dir) == full_then_filter("grants", "user_id", "", data_dir) |
| 154 | assert where("grants", "id", "g2", data_dir) == full_then_filter("grants", "id", "g2", data_dir) |
| 155 | |
| 156 | |
| 157 | def test_where_raises_what_the_full_read_raises(tmp_path): |
| 158 | data_dir = tmp_path / "data" |
| 159 | with pytest.raises(object_collections.CollectionNotFoundError): |
| 160 | where("nothing_here", "user_id", "u7", data_dir) |
| 161 | with pytest.raises(object_collections.InvalidCollectionNameError): |
| 162 | where("bad!name", "user_id", "u7", data_dir) |
| 163 | (data_dir / "schemas").mkdir(parents=True) |
| 164 | (data_dir / "schemas" / "empty_one.json").write_text(json.dumps({"fields": [{"name": "id"}]})) |
| 165 | assert where("empty_one", "user_id", "u7", data_dir) == full_then_filter("empty_one", "user_id", "u7", data_dir) == [] |
| 166 | (data_dir / "schemas" / "broken.json").write_text("{ not json") |
| 167 | write_records(data_dir, "broken", "id\tuser_id\nb1\tu7\n") |
| 168 | with pytest.raises(ValueError): |
| 169 | full_then_filter("broken", "user_id", "u7", data_dir) |
| 170 | with pytest.raises(ValueError): |
| 171 | where("broken", "user_id", "u7", data_dir) |
| 172 | |
| 173 | |
| 174 | def test_where_answers_from_the_field_index_and_still_matches_the_full_read(data_dir, monkeypatch): |
| 175 | """The common case is answered from the cached entry's field index, not |
| 176 | by testing every row; and the index can only make it cheaper.""" |
| 177 | tested = [] |
| 178 | real = object_records._build_field_buckets |
| 179 | |
| 180 | def counting(records, field): |
| 181 | tested.append(field) |
| 182 | return real(records, field) |
| 183 | |
| 184 | monkeypatch.setattr(object_records, "_build_field_buckets", counting) |
| 185 | for value in ("u7", "u8", "u9", "nobody", ""): |
| 186 | assert where("project_access", "user_id", value, data_dir) == full_then_filter( |
| 187 | "project_access", "user_id", value, data_dir |
| 188 | ) |
| 189 | assert tested == ["user_id"], "built once for this entry, then reused" |
| 190 | path = data_dir / "collections" / "project_access" / "records.tsv" |
| 191 | path.write_text(path.read_text() + "a8\tp7\tu7\tread\n") |
| 192 | assert [r["id"] for r in where("project_access", "user_id", "u7", data_dir)] == ["a1", "a3", "a4", "a5", "a8"] |
| 193 | assert tested == ["user_id", "user_id"], "a changed file is a new entry with a new index" |
| 194 | |
| 195 | |
| 196 | def test_where_without_an_index_tests_every_row(data_dir, monkeypatch): |
| 197 | """Too large to cache, or a value that is not a string: no index, the |
| 198 | same answer.""" |
| 199 | monkeypatch.setenv(object_records.RECORDS_CACHE_MAX_ROWS_ENV, "2") |
| 200 | object_records._RECORDS_CACHE.clear() |
| 201 | assert where("project_access", "user_id", "u7", data_dir) == full_then_filter( |
| 202 | "project_access", "user_id", "u7", data_dir |
| 203 | ) |
| 204 | monkeypatch.delenv(object_records.RECORDS_CACHE_MAX_ROWS_ENV) |
| 205 | assert where("project_access", "user_id", 7, data_dir) == full_then_filter("project_access", "user_id", 7, data_dir) == [] |
| 206 | |
| 207 | |
| 208 | def test_where_on_id_with_duplicate_ids_returns_every_row(tmp_path): |
| 209 | """id_index is first-occurrence-wins; a hand-edited file with a repeated |
| 210 | id must still return both rows.""" |
| 211 | data_dir = tmp_path / "data" |
| 212 | write_records(data_dir, "dupes", "id\tuser_id\nd1\tu7\nd2\tu8\nd1\tu9\n\tu7\n") |
| 213 | assert [r["user_id"] for r in where("dupes", "id", "d1", data_dir)] == ["u7", "u9"] |
| 214 | assert where("dupes", "id", "", data_dir) == full_then_filter("dupes", "id", "", data_dir) |
| 215 | assert where("dupes", "id", "d1", data_dir) == full_then_filter("dupes", "id", "d1", data_dir) |
| 216 | |
| 217 | |
| 218 | # --- the resolved subject ------------------------------------------------------------------------ |
| 219 | |
| 220 | |
| 221 | @pytest.mark.parametrize("user_id", ["u7", "u8", "u9", "nobody", ""]) |
| 222 | def test_the_resolved_subject_is_the_one_full_reads_gave(data_dir, user_id): |
| 223 | assert resolved(user_id) == reference(user_id, data_dir) |
| 224 | |
| 225 | |
| 226 | def test_the_resolved_subject_names_exactly_this_users_grants(data_dir): |
| 227 | subject = resolved("u7") |
| 228 | assert list(subject.project_ids) == ["p1", "p3"] |
| 229 | assert list(subject.writable_project_ids) == ["p3"] |
| 230 | assert list(subject.owned_project_ids) == ["p2", "p5"] |
| 231 | assert dict(subject.shared_records) == {"notes": ("n1", "n2")} |
| 232 | assert dict(subject.writable_shared_records) == {"notes": ("n2",)} |
| 233 | |
| 234 | |
| 235 | def test_a_subject_with_no_grants_and_missing_collections_is_left_alone(tmp_path, monkeypatch): |
| 236 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data")) |
| 237 | subject = object_permissions.PermissionSubject(user_id="u7") |
| 238 | assert object_server._with_shared_records(object_server._with_accessible_projects(subject)) is subject |
| 239 | anonymous = object_permissions.PermissionSubject.anonymous() |
| 240 | assert object_server._with_shared_records(object_server._with_accessible_projects(anonymous)) is anonymous |
| 241 | |
| 242 | |
| 243 | def test_resolution_does_not_copy_the_whole_of_any_grant_collection(data_dir, monkeypatch): |
| 244 | """The cost this replaces. If resolution goes back to the full read, |
| 245 | this fails.""" |
| 246 | def full_read(*args, **kwargs): |
| 247 | raise AssertionError("identity resolution must not copy every row of a collection") |
| 248 | |
| 249 | monkeypatch.setattr(object_records, "read_collection_records", full_read) |
| 250 | assert list(resolved("u7").project_ids) == ["p1", "p3"] |
| 251 | |
| 252 | |
| 253 | def test_a_grant_written_by_another_process_is_in_force_on_the_next_resolution(data_dir): |
| 254 | assert "p4" not in resolved("u7").project_ids |
| 255 | path = data_dir / "collections" / "project_access" / "records.tsv" |
| 256 | with path.open("a") as handle: |
| 257 | handle.write("a7\tp4\tu7\twrite\n") |
| 258 | subject = resolved("u7") |
| 259 | assert "p4" in subject.project_ids and "p4" in subject.writable_project_ids |
| 260 | assert subject == reference("u7", data_dir) |
| 261 | |
| 262 | |
| 263 | def test_a_grant_removed_by_hand_is_gone_on_the_next_resolution(data_dir): |
| 264 | """The direction that matters most: access taken away must be taken |
| 265 | away at once, including by an edit that keeps the file the same size.""" |
| 266 | assert "p3" in resolved("u7").writable_project_ids |
| 267 | path = data_dir / "collections" / "project_access" / "records.tsv" |
| 268 | text = path.read_text() |
| 269 | path.write_text(text.replace("a3\tp3\tu7\twrite\n", "a3\tp3\tu8\twrite\n")) # same size |
| 270 | subject = resolved("u7") |
| 271 | assert "p3" not in subject.project_ids and "p3" not in subject.writable_project_ids |
| 272 | assert "p3" in resolved("u8").project_ids |
| 273 | path.write_text(text.replace("a1\tp1\tu7\tread\n", "")) |
| 274 | assert list(resolved("u7").project_ids) == ["p3", "p1"] # a5 still grants p1 |
| 275 | path.unlink() |
| 276 | assert list(resolved("u7").project_ids) == [] |
| 277 | assert resolved("u7") == reference("u7", data_dir) |
| 278 | |
| 279 | |
| 280 | def test_grants_changed_through_the_record_api_are_in_force_on_the_next_resolution(data_dir): |
| 281 | object_records.create_collection_record( |
| 282 | "project_access", {"id": "a9", "project_id": "p8", "user_id": "u7", "permission": "read"}, base_dir=data_dir |
| 283 | ) |
| 284 | assert "p8" in resolved("u7").project_ids |
| 285 | object_records.update_collection_record("project_access", "a9", {"permission": "write"}, base_dir=data_dir) |
| 286 | assert "p8" in resolved("u7").writable_project_ids |
| 287 | object_records.delete_collection_record("project_access", "a9", base_dir=data_dir) |
| 288 | assert "p8" not in resolved("u7").project_ids |
| 289 | |
| 290 | object_records.create_collection_record("projects", {"id": "p6", "name": "Six", "owner_id": "u7"}, base_dir=data_dir) |
| 291 | assert "p6" in resolved("u7").owned_project_ids |
| 292 | object_records.update_collection_record("projects", "p6", {"owner_id": "u8"}, base_dir=data_dir) |
| 293 | assert "p6" not in resolved("u7").owned_project_ids and "p6" in resolved("u8").owned_project_ids |
| 294 | |
| 295 | object_records.create_collection_record( |
| 296 | "record_shares", {"id": "s9", "collection": "tasks", "record_id": "t9", "user_id": "u7", "permission": "write"}, |
| 297 | base_dir=data_dir, |
| 298 | ) |
| 299 | assert resolved("u7") == reference("u7", data_dir) |
| 300 | assert "t9" in resolved("u7").shared_records["tasks"] |
| 301 | object_records.delete_collection_record("record_shares", "s9", base_dir=data_dir) |
| 302 | assert "tasks" not in resolved("u7").shared_records |
| 303 | |
| 304 | |
| 305 | def test_the_identity_endpoint_follows_a_grant_given_and_taken_away(data_dir): |
| 306 | def project_ids(): |
| 307 | status, _, payload = request("/identity", headers=[("x-dbbasic-user-id", "u7")]) |
| 308 | assert status == 200 |
| 309 | return payload["subject"].get("project_ids", []) |
| 310 | |
| 311 | assert project_ids() == ["p1", "p3"] |
| 312 | path = data_dir / "collections" / "project_access" / "records.tsv" |
| 313 | original = path.read_text() |
| 314 | path.write_text(original + "a7\tp4\tu7\tread\n") |
| 315 | assert project_ids() == ["p1", "p3", "p4"] |
| 316 | path.write_text(original) |
| 317 | assert project_ids() == ["p1", "p3"] |