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_try_package.py · 12.4 KB · 263 lines
| 1 | """scripts/try_package.py: install a package into a scratch directory, make users |
| 2 | with roles, and call the app as them with permission enforcement on. |
| 3 | |
| 4 | It exists so a newcomer can check a schema or a rules change by running one |
| 5 | command instead of assembling an install, an identity registry, API keys and an |
| 6 | ASGI driver by hand (docs/package-authoring.md, "Try Your Change"). The claims |
| 7 | that matter, each tested here: |
| 8 | |
| 9 | - enforcement really is on (an anonymous caller and a caller outside the rule |
| 10 | are refused, an owner and a role with a broader grant are served); |
| 11 | - dependencies install first, and a dependency that is not beside the package |
| 12 | is left out rather than failing the install; |
| 13 | - nothing leaks out: the process environment is put back, the scratch |
| 14 | directory is gone, and the repository's own data directory is untouched; |
| 15 | - the command line prints status and body for each call and reports a bad call |
| 16 | as a usage error, not a traceback. |
| 17 | """ |
| 18 | |
| 19 | import json |
| 20 | import os |
| 21 | |
| 22 | import pytest |
| 23 | |
| 24 | from scripts import try_package |
| 25 | from scripts.try_package import Sandbox, SandboxError, package_order |
| 26 | |
| 27 | SCHEMA = { |
| 28 | "name": "widgets", |
| 29 | "version": 1, |
| 30 | "fields": [ |
| 31 | {"name": "id"}, |
| 32 | {"name": "title", "type": "text", "required": True}, |
| 33 | {"name": "owner_id", "type": "text"}, |
| 34 | ], |
| 35 | } |
| 36 | RULES = { |
| 37 | "rules": [ |
| 38 | {"effect": "allow", "principal": "registered", |
| 39 | "actions": ["create", "read", "update", "delete"], |
| 40 | "collection": "widgets", "row_filter": {"owner_id": "$user_id"}, |
| 41 | "reason": "own rows"}, |
| 42 | {"effect": "allow", "principal": "role:auditor", "actions": ["read"], |
| 43 | "collection": "widgets", "reason": "auditors read all"}, |
| 44 | ] |
| 45 | } |
| 46 | |
| 47 | |
| 48 | def write_package(root, package_id, dependencies=(), schema=SCHEMA, rules=RULES): |
| 49 | folder = root / package_id |
| 50 | (folder / "schemas").mkdir(parents=True) |
| 51 | (folder / "permissions").mkdir() |
| 52 | (folder / "dbbasic-package.json").write_text(json.dumps({ |
| 53 | "id": package_id, "name": package_id, "version": "0.1.0", |
| 54 | "compatibility": {"dbbasic_object_server": ">=0.1.0"}, |
| 55 | "dependencies": list(dependencies), "objects": [], |
| 56 | "schemas": [{"collection": "widgets", "path": "schemas/widgets.json"}] if schema else [], |
| 57 | "permissions": [{"path": "permissions/rules.json"}] if rules else [], |
| 58 | "seed": [], "migrations": [], |
| 59 | })) |
| 60 | if schema: |
| 61 | (folder / "schemas" / "widgets.json").write_text(json.dumps(schema)) |
| 62 | if rules: |
| 63 | (folder / "permissions" / "rules.json").write_text(json.dumps(rules)) |
| 64 | return folder |
| 65 | |
| 66 | |
| 67 | @pytest.fixture |
| 68 | def packages(tmp_path): |
| 69 | root = tmp_path / "packages" |
| 70 | write_package(root, "widgets") |
| 71 | return root |
| 72 | |
| 73 | |
| 74 | def test_enforcement_is_on_and_roles_decide(packages): |
| 75 | with Sandbox(["widgets"], packages_dir=packages) as box: |
| 76 | box.add_user("ann") |
| 77 | box.add_user("bob") |
| 78 | box.add_user("carol", roles=["auditor"]) |
| 79 | |
| 80 | status, body = box.call("ann", "POST", "/collections/widgets/records", |
| 81 | {"title": "one", "owner_id": "ann"}) |
| 82 | assert status == 201 |
| 83 | record_id = body["record"]["id"] |
| 84 | |
| 85 | # A create naming someone else is refused: the record does not match the |
| 86 | # caller's own grant. (One that omits owner_id is the caller's: the |
| 87 | # server stamps it before the rule is asked; tests/test_create_owner_id.py.) |
| 88 | status, body = box.call("ann", "POST", "/collections/widgets/records", |
| 89 | {"title": "x", "owner_id": "bob"}) |
| 90 | assert (status, body["code"], body["error"]) == (403, "forbidden", "no matching role rule") |
| 91 | |
| 92 | listing = {who: box.call(who, "GET", "/collections/widgets/records") |
| 93 | for who in ("ann", "bob", "carol", "admin", "anon")} |
| 94 | assert listing["ann"][1]["total"] == 1 |
| 95 | assert listing["bob"][1]["total"] == 0 |
| 96 | assert listing["carol"][1]["total"] == 1 # a grant with no row_filter reads every row |
| 97 | assert listing["admin"][1]["total"] == 1 |
| 98 | assert listing["anon"][0] == 403 |
| 99 | |
| 100 | assert box.call("carol", "PUT", f"/collections/widgets/records/{record_id}", {"title": "no"})[0] == 403 |
| 101 | assert box.call("ann", "PUT", f"/collections/widgets/records/{record_id}", {"title": "yes"})[0] == 200 |
| 102 | |
| 103 | |
| 104 | def test_without_enforcement_only_the_admin_token_gets_in(packages): |
| 105 | with Sandbox(["widgets"], packages_dir=packages, enforce=False) as box: |
| 106 | box.add_user("ann") |
| 107 | assert box.call("ann", "GET", "/collections/widgets/records")[0] in (401, 403) |
| 108 | assert box.call("admin", "GET", "/collections/widgets/records")[0] == 200 |
| 109 | |
| 110 | |
| 111 | def test_an_unknown_user_is_a_setup_error_not_a_silent_anonymous_call(packages): |
| 112 | with Sandbox(["widgets"], packages_dir=packages) as box: |
| 113 | with pytest.raises(SandboxError, match="unknown user 'dave'"): |
| 114 | box.call("dave", "GET", "/collections/widgets/records") |
| 115 | |
| 116 | |
| 117 | def test_dependencies_install_first_and_missing_ones_are_left_out(tmp_path): |
| 118 | root = tmp_path / "packages" |
| 119 | write_package(root, "base", schema=None, rules=None) |
| 120 | write_package(root, "middle", dependencies=["base"], schema=None, rules=None) |
| 121 | write_package(root, "top", dependencies=["middle", {"id": "not-here", "version": ">=1"}], |
| 122 | schema=None, rules=None) |
| 123 | assert package_order(["top"], root) == ["base", "middle", "top"] |
| 124 | assert package_order(["top", "base"], root) == ["base", "middle", "top"] |
| 125 | with pytest.raises(SandboxError, match="no package 'nope'"): |
| 126 | package_order(["nope"], root) |
| 127 | |
| 128 | |
| 129 | def test_the_environment_and_the_scratch_directory_do_not_outlive_the_sandbox(packages): |
| 130 | names = [try_package.object_server.DATA_DIR_ENV, try_package.object_server.ADMIN_TOKEN_ENV, |
| 131 | try_package.object_server.PERMISSION_ENFORCEMENT_ENV, "DBBASIC_OBJECTS_DIR"] |
| 132 | before = {name: os.environ.get(name) for name in names} |
| 133 | with Sandbox(["widgets"], packages_dir=packages) as box: |
| 134 | data_dir = box.data_dir |
| 135 | assert os.environ[names[0]] == str(data_dir) |
| 136 | assert data_dir.is_dir() |
| 137 | assert {name: os.environ.get(name) for name in names} == before |
| 138 | assert not data_dir.exists() |
| 139 | |
| 140 | |
| 141 | def test_a_kept_data_dir_survives(packages, tmp_path): |
| 142 | keep = tmp_path / "keep" |
| 143 | with Sandbox(["widgets"], packages_dir=packages, data_dir=keep) as box: |
| 144 | box.add_user("ann") |
| 145 | assert (keep / "schemas" / "widgets.json").is_file() |
| 146 | assert (keep / "identity" / "users.tsv").is_file() |
| 147 | |
| 148 | |
| 149 | def test_a_failed_install_cleans_up_after_itself(tmp_path): |
| 150 | root = tmp_path / "packages" |
| 151 | write_package(root, "widgets", schema={"name": "widgets", "fields": "not a list"}) |
| 152 | before = os.environ.get(try_package.object_server.DATA_DIR_ENV) |
| 153 | with pytest.raises(Exception): |
| 154 | with Sandbox(["widgets"], packages_dir=root): |
| 155 | pass |
| 156 | assert os.environ.get(try_package.object_server.DATA_DIR_ENV) == before |
| 157 | |
| 158 | |
| 159 | def test_the_command_line_prints_each_call_and_chains_last_id(packages, capsys): |
| 160 | code = try_package.main([ |
| 161 | "widgets", "--packages-dir", str(packages), |
| 162 | "--user", "ann", "--user", "carol:auditor", |
| 163 | "--call", 'ann POST /collections/widgets/records {"title": "one", "owner_id": "ann"}', |
| 164 | "--call", 'ann PUT /collections/widgets/records/$last_id {"title": "two"}', |
| 165 | "--call", "carol GET /collections/widgets/records?limit=1", |
| 166 | "--call", "anon GET /collections/widgets/records", |
| 167 | ]) |
| 168 | out = capsys.readouterr().out |
| 169 | assert code == 0 |
| 170 | assert "user carol: roles ['auditor']" in out |
| 171 | assert out.count("-> 201") == 1 |
| 172 | assert out.count("-> 200") == 2 # the PUT and carol's list |
| 173 | assert out.count("-> 403") == 1 # anonymous |
| 174 | assert '"title": "two"' in out # the update reached the record the create made |
| 175 | |
| 176 | |
| 177 | @pytest.mark.parametrize("argv, message", [ |
| 178 | (["nope"], "no package 'nope'"), |
| 179 | (["widgets", "--call", "ann GET"], "a call is 'USER METHOD PATH"), |
| 180 | (["widgets", "--call", "dave GET /collections/widgets/records"], "unknown user 'dave'"), |
| 181 | (["widgets", "--user", "ann", "--call", "ann POST /collections/widgets/records {not json"], "not JSON"), |
| 182 | ]) |
| 183 | def test_a_bad_call_is_a_usage_error_not_a_traceback(packages, capsys, argv, message): |
| 184 | code = try_package.main(argv[:1] + ["--packages-dir", str(packages)] + argv[1:]) |
| 185 | assert code == 2 |
| 186 | assert message in capsys.readouterr().err |
| 187 | |
| 188 | |
| 189 | def test_brief_prints_one_line_per_call_with_the_error_and_its_code(packages, capsys): |
| 190 | code = try_package.main([ |
| 191 | "widgets", "--packages-dir", str(packages), "--brief", "--user", "ann", |
| 192 | "--call", 'ann POST /collections/widgets/records {"owner_id": "ann"}', |
| 193 | "--call", "anon GET /collections/widgets/records", |
| 194 | ]) |
| 195 | lines = [line for line in capsys.readouterr().out.splitlines() |
| 196 | if line.startswith(("ann ", "anon "))] |
| 197 | assert code == 0 |
| 198 | assert lines[0] == "ann POST /collections/widgets/records -> 400 Record field 'title' is required" |
| 199 | assert lines[1].startswith("anon GET /collections/widgets/records -> 403 forbidden ") |
| 200 | |
| 201 | |
| 202 | def test_the_default_row_title_order_is_the_one_the_browser_uses(): |
| 203 | """`--rows` is a Python mirror of the list renderer's `cardTitle`. If the |
| 204 | JavaScript's default order changes and the mirror does not, `--rows` |
| 205 | tells a developer their rows are labelled one way while the page labels |
| 206 | them another, which is worse than not having `--rows`.""" |
| 207 | import re |
| 208 | from pathlib import Path |
| 209 | source = (Path(__file__).resolve().parents[1] |
| 210 | / "packages" / "app-theme" / "objects" / "site" / "list.py").read_text() |
| 211 | chain = re.search(r"const auto = (r\.\w+(?:\s*\|\|\s*r\.\w+)+);", source).group(1) |
| 212 | assert tuple(re.findall(r"r\.(\w+)", chain)) == try_package.AUTO_TITLE_FIELDS |
| 213 | |
| 214 | |
| 215 | def test_row_labels_follow_the_blocks_title_and_subtitle_fields(): |
| 216 | record = {"id": "n1", "content": "hello", "owner_id": "ann", "title": ""} |
| 217 | assert try_package.row_title({}, record) == "hello" # '' is skipped, as in JS || |
| 218 | assert try_package.row_title({"title_field": "owner_id"}, record) == "ann" |
| 219 | assert try_package.row_title({"title_field": "missing"}, record) == "(none)" |
| 220 | assert try_package.row_title({}, {}) == "(untitled)" |
| 221 | assert try_package.row_subtitle({}, record) == "" |
| 222 | assert try_package.row_subtitle({"subtitle_field": "owner_id"}, record) == "ann" |
| 223 | assert try_package.row_subtitle( |
| 224 | {"subtitle_field": "owner_id", "subtitle_label": "By"}, record) == "By: ann" |
| 225 | |
| 226 | |
| 227 | def test_rows_shows_what_each_person_would_see_in_a_seeded_list(capsys): |
| 228 | code = try_package.main([ |
| 229 | "app-views", "app-notes", "--user", "ann", "--user", "bob", "--brief", |
| 230 | "--call", 'ann POST /collections/notes/records {"content": "first note", "owner_id": "ann"}', |
| 231 | "--rows", "ann /notes", "--rows", "bob /notes", "--rows", "ann /nowhere", |
| 232 | ]) |
| 233 | out = capsys.readouterr().out |
| 234 | assert code == 0 |
| 235 | assert "list notes as ann: 1 row(s)" in out and " first note" in out |
| 236 | assert "list notes as bob: 0 row(s)" in out |
| 237 | assert "no view has the route /nowhere" in out |
| 238 | |
| 239 | |
| 240 | def test_a_blank_subtitle_draws_no_line_and_a_boolean_reads_yes_or_no(): |
| 241 | block = {"subtitle_field": "pinned", "subtitle_label": "Pinned"} |
| 242 | assert try_package.row_subtitle(block, {"pinned": ""}) == "" |
| 243 | assert try_package.row_subtitle(block, {"pinned": " "}) == "" |
| 244 | assert try_package.row_subtitle(block, {}) == "" |
| 245 | assert try_package.row_subtitle(block, {"pinned": "true"}) == "Pinned: true" # no schema: as stored |
| 246 | types = {"pinned": "boolean"} |
| 247 | assert try_package.row_subtitle(block, {"pinned": "true"}, types) == "Pinned: Yes" |
| 248 | assert try_package.row_subtitle(block, {"pinned": "false"}, types) == "Pinned: No" |
| 249 | assert try_package.row_subtitle(block, {"pinned": ""}, types) == "" |
| 250 | |
| 251 | |
| 252 | def test_the_browser_subtitle_does_what_the_mirror_does(): |
| 253 | """No JS engine here, so pin the pieces of the real code the mirror copies: |
| 254 | view_render skips a blank value and formats a boolean from cfg.fieldTypes, |
| 255 | and the list generator is what fills cfg.fieldTypes from the schema.""" |
| 256 | from pathlib import Path |
| 257 | packages = Path(__file__).resolve().parents[1] / "packages" |
| 258 | render = (packages / "app-views" / "objects" / "site" / "view_render.py").read_text() |
| 259 | assert 'if (v == null || String(v).trim() === "") return "";' in render |
| 260 | assert 'cfg.fieldTypes[sf] === "boolean"' in render |
| 261 | assert '(String(v) === "true" ? "Yes" : "No")' in render |
| 262 | listing = (packages / "app-theme" / "objects" / "site" / "list.py").read_text() |
| 263 | assert "cfg.fieldTypes[f.name] = String(f.type" in listing |