Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 18 minutes ago History
try_package.py · 21.2 KB · 477 lines
1#!/usr/bin/env python3
2"""Try a package: install it into a scratch data directory, make users with
3roles, and call the app as each of them with permission enforcement ON.
4
5 python scripts/try_package.py app-notes \\
6 --user ann --user bob:auditor \\
7 --call 'ann POST /collections/notes/records {"title": "hi", "owner_id": "ann"}' \\
8 --call 'bob GET /collections/notes/records' \\
9 --call 'admin GET /collections/notes/records'
10
11Each `--call` is `USER METHOD PATH [JSON BODY]`. USER is a name given to
12`--user` (`name` or `name:role,role`), `admin` (the admin token) or `anon`
13(no credentials). PATH may carry a query string, and `$last_id` stands for the
14id of the record the previous call returned (so a create can be followed by an
15update of that record). The output is the status and the JSON answer, one
16block per call, so a change to a schema or a rules file can be checked by
17reading what the API says for the people it matters to.
18
19Why this exists. A schema or a rules file is only half-checked by reading it:
20the other half is what the API does for a person with that role, with the
21engine deciding, and every route here is gated differently when enforcement
22is off. This runs the real ASGI app in this process (no port, no server left
23running, no network), against a throwaway data directory, with the same
24settings a production box has. Nothing outside the scratch directory is
25written, and the process environment is put back afterwards.
26
27`--brief` prints one line per call (`USER METHOD PATH -> STATUS`, plus the
28error and its code when the answer has one) instead of the whole JSON: use it
29when you are checking twenty calls, and drop it to read one answer in full.
30
31`--rows 'USER ROUTE'` shows what a seeded page's list blocks would put on
32screen for that person: the row title and subtitle each list block labels its
33rows with. The page itself is drawn in the browser by JavaScript, which this
34script does not run (and must not: no JS engine), so rows are computed here
35by a Python mirror of the rules in packages/app-theme/objects/site/list.py
36(`title_field` / `subtitle_field` / `subtitle_label`, else the first of the
37default title fields). tests/test_try_package.py pins the mirror's default
38field order against that file. It is a check on the data and the labels, not
39a screenshot: layout, filters typed into the search box and a table mode's
40cell formatting are not reproduced (a table-mode collection prints its
41`list_fields` columns instead). Routes with a `{capture}` are matched by
42pattern. Pages are served only with DBBASIC_ENABLE_SITE_ROUTES=true on a real
43server; this does not need it, because it reads the `views` records directly.
44
45What it does NOT do: run the daemon, so no schedules, no attention rollup and
46no event handlers fire (they are off on a stock install too; see AGENTS.md);
47and it does not start a server. `--data-dir DIR` keeps the data where you can
48look at it (and point a real server at it); without it a temporary directory
49is made and removed.
50
51From Python (this is what tests/test_try_package.py does):
52
53 with Sandbox(["app-notes"]) as box:
54 box.add_user("ann")
55 box.add_user("bob", roles=["auditor"])
56 status, body = box.call("ann", "POST", "/collections/notes/records",
57 {"title": "hi", "owner_id": "ann"})
58 # after editing the package's files on disk, install the new version
59 # over the same data (an upgrade): box.reinstall("app-notes")
60
61Standard library and this repository only.
62"""
63
64from __future__ import annotations
65
66import argparse
67import asyncio
68import json
69import os
70import re
71import secrets
72import shutil
73import sys
74import tempfile
75from pathlib import Path
76from typing import Any, Iterable
77
78REPO = Path(__file__).resolve().parent.parent
79if str(REPO) not in sys.path:
80 sys.path.insert(0, str(REPO))
81
82import object_api_keys # noqa: E402
83import object_identity # noqa: E402
84import object_packages # noqa: E402
85import object_server # noqa: E402
86
87# Everything the sandbox sets on the process, restored on exit.
88_ENV = (
89 object_server.DATA_DIR_ENV,
90 object_server.ADMIN_TOKEN_ENV,
91 object_server.PERMISSION_ENFORCEMENT_ENV,
92 object_server.PERMISSION_UNREADY_ENFORCEMENT_ENV,
93 "DBBASIC_OBJECTS_DIR",
94)
95
96
97class SandboxError(Exception):
98 """A setup problem the caller can fix: an unknown package, user or call."""
99
100
101def package_order(package_ids: Iterable[str], root: Path) -> list[str]:
102 """The packages to install, each after the packages it depends on.
103
104 A dependency that is not in `root` is left out (the manifest's
105 `dependencies` is declared, not resolved, by the installer), so a
106 package with an outside dependency still installs.
107 """
108 ordered: list[str] = []
109
110 def visit(package_id: str, trail: tuple[str, ...]) -> None:
111 if package_id in ordered:
112 return
113 manifest = root / package_id / object_packages.MANIFEST_FILE
114 if not manifest.is_file():
115 raise SandboxError(f"no package {package_id!r} under {root}")
116 if package_id in trail:
117 return
118 for dependency in json.loads(manifest.read_text()).get("dependencies", []):
119 dep_id = dependency if isinstance(dependency, str) else dependency.get("id")
120 if dep_id and (root / dep_id / object_packages.MANIFEST_FILE).is_file():
121 visit(dep_id, trail + (package_id,))
122 ordered.append(package_id)
123
124 for package_id in package_ids:
125 visit(package_id, ())
126 return ordered
127
128
129class Sandbox:
130 """A scratch data directory with packages installed, users, and enforcement on."""
131
132 def __init__(
133 self,
134 packages: Iterable[str],
135 *,
136 packages_dir: Path | str | None = None,
137 data_dir: Path | str | None = None,
138 enforce: bool = True,
139 ) -> None:
140 self.packages_dir = Path(packages_dir) if packages_dir else REPO / "packages"
141 self.requested = list(packages)
142 self.enforce = enforce
143 self._given_data_dir = Path(data_dir) if data_dir else None
144 self._tmp: str | None = None
145 self._saved: dict[str, str | None] = {}
146 self.data_dir: Path
147 self.objects_dir: Path
148 self.admin_token = "try-" + secrets.token_urlsafe(18)
149 self.tokens: dict[str, str] = {}
150 self.installed: list[str] = []
151
152 # -- lifecycle ---------------------------------------------------------
153
154 def __enter__(self) -> "Sandbox":
155 self._tmp = tempfile.mkdtemp(prefix="dbbasic-try-")
156 base = self._given_data_dir or Path(self._tmp) / "data"
157 base.mkdir(parents=True, exist_ok=True)
158 self.data_dir = base
159 self.objects_dir = Path(self._tmp) / "objects"
160 self.objects_dir.mkdir()
161 self._saved = {name: os.environ.get(name) for name in _ENV}
162 os.environ[object_server.DATA_DIR_ENV] = str(self.data_dir)
163 os.environ[object_server.ADMIN_TOKEN_ENV] = self.admin_token
164 os.environ["DBBASIC_OBJECTS_DIR"] = str(self.objects_dir)
165 if self.enforce:
166 os.environ[object_server.PERMISSION_ENFORCEMENT_ENV] = "true"
167 os.environ[object_server.PERMISSION_UNREADY_ENFORCEMENT_ENV] = "true"
168 else:
169 os.environ.pop(object_server.PERMISSION_ENFORCEMENT_ENV, None)
170 os.environ.pop(object_server.PERMISSION_UNREADY_ENFORCEMENT_ENV, None)
171 try:
172 for package_id in package_order(self.requested, self.packages_dir):
173 object_packages.install_package(
174 package_id,
175 root=self.packages_dir,
176 base_dir=self.data_dir,
177 object_roots=[self.objects_dir],
178 )
179 self.installed.append(package_id)
180 except BaseException:
181 self.__exit__(None, None, None)
182 raise
183 return self
184
185 def __exit__(self, *exc: object) -> None:
186 for name, value in self._saved.items():
187 if value is None:
188 os.environ.pop(name, None)
189 else:
190 os.environ[name] = value
191 if self._tmp:
192 shutil.rmtree(self._tmp, ignore_errors=True)
193 self._tmp = None
194
195 def reinstall(self, package_id: str) -> dict[str, Any]:
196 """Install `package_id` again over the data already here, as an upgrade
197 (`allow_replace`): edit the package's files first, then call this, then
198 look at what the old records and the new schema now say."""
199 return object_packages.install_package(
200 package_id,
201 root=self.packages_dir,
202 base_dir=self.data_dir,
203 object_roots=[self.objects_dir],
204 allow_replace=True,
205 )
206
207 # -- people ------------------------------------------------------------
208
209 def add_user(self, user_id: str, roles: Iterable[str] = ()) -> str:
210 """Create a user with these roles and an API key; return the key.
211
212 Roles are what a rule's `principal: "role:<name>"` matches. They live
213 on the user record (`data/identity/users.tsv`); a policy's
214 `user_roles` map is the other place to assign them.
215 """
216 object_identity.create_user(
217 {"user_id": user_id, "roles": list(roles)}, base_dir=self.data_dir
218 )
219 _, token = object_api_keys.create_api_key(user_id, "try", base_dir=self.data_dir)
220 self.tokens[user_id] = token
221 return token
222
223 # -- calling -----------------------------------------------------------
224
225 def headers(self, user: str | None) -> list[tuple[str, str]]:
226 headers = [("content-type", "application/json")]
227 if user in (None, "anon"):
228 return headers
229 if user == "admin":
230 return headers + [("authorization", f"Token {self.admin_token}")]
231 if user not in self.tokens:
232 known = ", ".join(sorted(self.tokens) + ["admin", "anon"])
233 raise SandboxError(f"unknown user {user!r} (known: {known})")
234 return headers + [("authorization", f"Bearer {self.tokens[user]}")]
235
236 def call(
237 self,
238 user: str | None,
239 method: str,
240 path: str,
241 body: Any = None,
242 ) -> tuple[int, Any]:
243 """Call the app as `user`. Returns (status, parsed JSON or text)."""
244 route, _, query = path.partition("?")
245 raw = b"" if body is None else json.dumps(body).encode("utf-8")
246 status, payload = asyncio.run(
247 _asgi(route, method.upper(), query, raw, self.headers(user))
248 )
249 try:
250 return status, json.loads(payload.decode("utf-8"))
251 except (UnicodeDecodeError, ValueError):
252 return status, payload.decode("utf-8", errors="replace")
253
254
255async def _asgi(
256 path: str, method: str, query: str, body: bytes, headers: list[tuple[str, str]]
257) -> tuple[int, bytes]:
258 messages: list[dict[str, Any]] = []
259 sent = False
260
261 async def receive() -> dict[str, Any]:
262 nonlocal sent
263 if not sent:
264 sent = True
265 return {"type": "http.request", "body": body, "more_body": False}
266 return {"type": "http.disconnect"}
267
268 async def send(message: dict[str, Any]) -> None:
269 messages.append(message)
270
271 scope = {
272 "type": "http",
273 "method": method,
274 "path": path,
275 "query_string": query.encode("utf-8"),
276 "headers": [(b"accept", b"application/json")]
277 + [(name.encode("latin-1"), value.encode("latin-1")) for name, value in headers],
278 "client": ("127.0.0.1", 12345),
279 }
280 await object_server.app(scope, receive, send)
281 start = next(m for m in messages if m["type"] == "http.response.start")
282 return start["status"], b"".join(
283 m.get("body", b"") for m in messages if m["type"] == "http.response.body"
284 )
285
286
287# The label a list row gets when its block names no `title_field`: the first of
288# these that is non-empty, then the id. A mirror of `cardTitle` in
289# packages/app-theme/objects/site/list.py (a test compares the two).
290AUTO_TITLE_FIELDS = ("title", "name", "label", "subject", "body", "text",
291 "content", "message", "description", "email", "id")
292DEFAULT_ROW_CAP = 50
293
294
295def row_title(block: dict[str, Any], record: dict[str, Any]) -> str:
296 field = block.get("title_field")
297 if field:
298 value = record.get(field)
299 return "(none)" if value in (None, "") else str(value)
300 for name in AUTO_TITLE_FIELDS:
301 if record.get(name):
302 return str(record[name])
303 return "(untitled)"
304
305
306def row_subtitle(block: dict[str, Any], record: dict[str, Any],
307 types: dict[str, str] | None = None) -> str:
308 """A mirror of the subtitle in packages/app-views/objects/site/view_render.py:
309 a blank value draws no line, and a boolean field (per the schema) reads Yes/No."""
310 field = block.get("subtitle_field")
311 if not field:
312 return ""
313 value = record.get(field)
314 if value is None or str(value).strip() == "":
315 return ""
316 if (types or {}).get(field) == "boolean":
317 value = "Yes" if str(value) == "true" else "No"
318 label = f"{block['subtitle_label']}: " if block.get("subtitle_label") else ""
319 return f"{label}{value}"
320
321
322def _route_matches(route: str, path: str) -> bool:
323 pattern = "^" + re.sub(r"\\\{\w+(?::\w+)?\\\}", "[^/]+", re.escape(route)) + "$"
324 return re.match(pattern, path) is not None
325
326
327def view_rows(box: "Sandbox", user: str, route: str) -> list[str]:
328 """Lines describing what each `list` block of the page at `route` would
329 draw for `user` (see the docstring at the top of this file)."""
330 _, views = box.call("admin", "GET", "/collections/views/records?limit=500")
331 records = views.get("records", []) if isinstance(views, dict) else []
332 matches = [v for v in records if v.get("route") and _route_matches(v["route"], route)]
333 if not matches:
334 return [f"no view has the route {route} (is app-views installed, and the view seeded?)"]
335 view = sorted(matches, key=lambda v: ("{" in v["route"], v["route"]))[0]
336 try:
337 blocks = json.loads(view.get("blocks") or "[]")
338 except ValueError as exc:
339 return [f"view {view.get('id')}: its blocks are not valid JSON: {exc}"]
340 lines = [f"view {view.get('id')} ({view['route']}): {view.get('title', '')}"]
341 for block in blocks:
342 if not isinstance(block, dict) or block.get("kind") != "list":
343 lines.append(f" [{block.get('kind') if isinstance(block, dict) else '?'} block: not previewed]")
344 continue
345 collection = block.get("collection", "")
346 query = "limit=500" + "".join(
347 f"&{k}={v}" for k, v in (block.get("where") or {}).items())
348 status, body = box.call(user, "GET", f"/collections/{collection}/records?{query}")
349 if status != 200 or not isinstance(body, dict):
350 lines.append(f" [list {collection}: {user} gets {status}; the page would say \"Not available\"]")
351 continue
352 rows = list(body.get("records", []))
353 _, schema = box.call(user, "GET", f"/api/schema/{collection}")
354 schema_body = schema.get("schema") if isinstance(schema, dict) else None
355 schema_body = schema_body if isinstance(schema_body, dict) else {}
356 views_cfg = schema_body.get("views") or {}
357 field_types = {f.get("name"): str(f.get("type") or "").lower()
358 for f in schema_body.get("fields", []) if isinstance(f, dict)}
359 mode = views_cfg.get("list_mode", "")
360 sort_field = block.get("sort_by") or "created_at"
361 reverse = not (block.get("sort_by") and block.get("sort_dir") == "asc") and block.get("sort") not in ("oldest", "asc")
362 rows.sort(key=lambda r: str(r.get(sort_field) or ""), reverse=reverse)
363 cap = block.get("row_limit") if block.get("row_limit") is not None else DEFAULT_ROW_CAP
364 lines.append(f" list {collection} as {user}: {len(rows)} row(s), mode {mode or 'cards'}")
365 if mode in ("board", "tree", "calendar"):
366 lines.append(f" (the {mode} mode draws these rows another way; not previewed)")
367 continue
368 if mode == "table":
369 columns = views_cfg.get("list_fields") or [f["name"] for f in schema_body.get("fields", [])]
370 lines.append(" columns: " + " | ".join(columns) + " (a table ignores title_field/subtitle_field)")
371 for record in rows[:cap]:
372 lines.append(" " + " | ".join(str(record.get(c, "")) for c in columns))
373 else:
374 for record in rows[:cap]:
375 subtitle = row_subtitle(block, record, field_types)
376 lines.append(f" {row_title(block, record)}" + (f" / {subtitle}" if subtitle else ""))
377 if len(rows) > cap:
378 lines.append(f" ... {len(rows) - cap} more behind 'Show all'")
379 return lines
380
381
382def brief_line(user: str, method: str, path: str, status: int, payload: Any) -> str:
383 """`USER METHOD PATH -> STATUS`, plus the error and its code when there is one."""
384 line = f"{user} {method.upper()} {path} -> {status}"
385 if isinstance(payload, dict):
386 error = payload.get("error")
387 if isinstance(error, dict):
388 code, message = error.get("code"), error.get("message")
389 else:
390 code, message = payload.get("code"), error
391 detail = " ".join(str(part) for part in (code, message) if part)
392 if detail:
393 line += f" {detail}"
394 return line
395
396
397def parse_call(text: str) -> tuple[str, str, str, Any]:
398 """`USER METHOD PATH [JSON]` -> (user, method, path, body or None)."""
399 parts = text.strip().split(None, 3)
400 if len(parts) < 3:
401 raise SandboxError(f"a call is 'USER METHOD PATH [JSON]', got {text!r}")
402 user, method, path = parts[:3]
403 body = None
404 if len(parts) == 4:
405 try:
406 body = json.loads(parts[3])
407 except ValueError as exc:
408 raise SandboxError(f"the body of {text!r} is not JSON: {exc}") from exc
409 return user, method, path, body
410
411
412def parse_user(text: str) -> tuple[str, list[str]]:
413 user_id, _, roles = text.partition(":")
414 return user_id, [role for role in roles.split(",") if role]
415
416
417def main(argv: list[str] | None = None) -> int:
418 parser = argparse.ArgumentParser(
419 description="Install packages into a scratch data directory and call them as users, "
420 "with permission enforcement on. See the top of this file."
421 )
422 parser.add_argument("packages", nargs="+", help="package ids under the packages directory")
423 parser.add_argument("--user", action="append", default=[], metavar="NAME[:ROLE,ROLE]",
424 help="create a user (repeatable); roles are what rules call role:<name>")
425 parser.add_argument("--call", action="append", default=[], metavar="'USER METHOD PATH [JSON]'",
426 help="a request to make (repeatable); USER is a --user name, admin or anon")
427 parser.add_argument("--packages-dir", type=Path, default=None,
428 help="where the packages are (default: packages/ in this repository)")
429 parser.add_argument("--data-dir", type=Path, default=None,
430 help="keep the data here instead of in a temporary directory")
431 parser.add_argument("--brief", action="store_true",
432 help="one line per call: 'USER METHOD PATH -> STATUS' and the error, if any")
433 parser.add_argument("--rows", action="append", default=[], metavar="'USER ROUTE'",
434 help="print the row titles/subtitles the page at ROUTE would list for USER (repeatable)")
435 parser.add_argument("--no-enforce", action="store_true",
436 help="leave permission enforcement off (only the admin token gets in)")
437 args = parser.parse_args(argv)
438
439 try:
440 with Sandbox(args.packages, packages_dir=args.packages_dir,
441 data_dir=args.data_dir, enforce=not args.no_enforce) as box:
442 print(f"installed: {', '.join(box.installed)}")
443 print(f"data dir: {box.data_dir}")
444 for text in args.user:
445 user_id, roles = parse_user(text)
446 box.add_user(user_id, roles)
447 print(f"user {user_id}: roles {roles or '-'}")
448 exit_code = 0
449 last_id = ""
450 for text in args.call:
451 user, method, path, body = parse_call(text)
452 path = path.replace("$last_id", last_id)
453 status, payload = box.call(user, method, path, body)
454 if isinstance(payload, dict) and isinstance(payload.get("record"), dict):
455 last_id = str(payload["record"].get("id") or last_id)
456 if args.brief:
457 print(brief_line(user, method, path, status, payload))
458 else:
459 print(f"\n{user} {method.upper()} {path}" + (f" {json.dumps(body)}" if body is not None else ""))
460 print(f"-> {status}")
461 print(payload if isinstance(payload, str) else json.dumps(payload, indent=2, sort_keys=True))
462 if status >= 500:
463 exit_code = 1
464 for text in args.rows:
465 parts = text.split()
466 if len(parts) != 2:
467 raise SandboxError(f"--rows is 'USER ROUTE', got {text!r}")
468 print()
469 print("\n".join(view_rows(box, parts[0], parts[1])))
470 return exit_code
471 except (SandboxError, object_packages.PackageInstallError) as exc:
472 print(f"error: {exc}", file=sys.stderr)
473 return 2
474
475
476if __name__ == "__main__":
477 sys.exit(main())