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

9 downloads

dbbasic-object-server/deployment_checks.py
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, 7 minutes ago History
deployment_checks.py · 14.3 KB · 403 lines
1"""Deployment checks for the conservative single-VM layout."""
2from __future__ import annotations
3
4import argparse
5import grp
6import json
7import os
8import pwd
9import stat
10from dataclasses import asdict, dataclass
11from datetime import datetime, timedelta, timezone
12from pathlib import Path
13from typing import Literal
14
15import object_record_changes
16
17DEFAULT_CODE_DIR = Path("/opt/dbbasic-object-server")
18DEFAULT_OBJECTS_DIR = Path("/var/lib/dbbasic-object-server/objects")
19DEFAULT_DATA_DIR = Path("/var/lib/dbbasic-object-server/data")
20DEFAULT_ENV_FILE = Path("/etc/dbbasic-object-server.env")
21DEFAULT_SERVICE_FILE = Path("/etc/systemd/system/dbbasic-object-server.service")
22DEFAULT_JOURNALD_DROPIN = Path("/etc/systemd/journald.conf.d/99-dbbasic.conf")
23DEFAULT_SERVICE_USER = "dbbasic"
24DEFAULT_SERVICE_GROUP = "dbbasic"
25UNATTRIBUTED_ACTOR = "unattributed"
26DEFAULT_UNATTRIBUTED_WINDOW_HOURS = 24
27
28Status = Literal["ok", "warning", "error"]
29
30
31@dataclass(frozen=True)
32class CheckResult:
33 name: str
34 path: str
35 status: Status
36 message: str
37
38
39def check_single_vm_layout(
40 *,
41 code_dir: Path | str = DEFAULT_CODE_DIR,
42 objects_dir: Path | str | None = None,
43 data_dir: Path | str | None = None,
44 env_file: Path | str = DEFAULT_ENV_FILE,
45 service_file: Path | str = DEFAULT_SERVICE_FILE,
46 journald_dropin: Path | str = DEFAULT_JOURNALD_DROPIN,
47 service_user: str = DEFAULT_SERVICE_USER,
48 service_group: str = DEFAULT_SERVICE_GROUP,
49 env_owner: str = "root",
50 system_owner: str = "root",
51 system_group: str = "root",
52) -> list[CheckResult]:
53 """Return filesystem placement and permission checks for one VM."""
54 objects_path = Path(
55 objects_dir
56 if objects_dir is not None
57 else os.environ.get("DBBASIC_OBJECTS_DIR", DEFAULT_OBJECTS_DIR)
58 )
59 data_path = Path(
60 data_dir if data_dir is not None else os.environ.get("DBBASIC_DATA_DIR", DEFAULT_DATA_DIR)
61 )
62
63 results: list[CheckResult] = []
64 results.extend(
65 _check_service_directory(
66 "code directory",
67 Path(code_dir),
68 expected_user=service_user,
69 expected_group=service_group,
70 private_runtime=False,
71 )
72 )
73 results.extend(
74 _check_service_directory(
75 "object source directory",
76 objects_path,
77 expected_user=service_user,
78 expected_group=service_group,
79 private_runtime=True,
80 )
81 )
82 results.extend(
83 _check_service_directory(
84 "data directory",
85 data_path,
86 expected_user=service_user,
87 expected_group=service_group,
88 private_runtime=True,
89 )
90 )
91 results.extend(_check_env_file(Path(env_file), expected_owner=env_owner, expected_group=service_group))
92 results.extend(
93 _check_service_file(
94 Path(service_file),
95 expected_owner=system_owner,
96 expected_group=system_group,
97 )
98 )
99 results.extend(
100 _check_journald_dropin(
101 Path(journald_dropin),
102 expected_owner=system_owner,
103 expected_group=system_group,
104 )
105 )
106 return results
107
108
109def has_errors(results: list[CheckResult]) -> bool:
110 return any(result.status == "error" for result in results)
111
112
113def check_unattributed_record_changes(
114 *,
115 data_dir: Path | str | None = None,
116 window_hours: int = DEFAULT_UNATTRIBUTED_WINDOW_HOURS,
117) -> list[CheckResult]:
118 """Count recent record changes with no real actor, and warn (never fail).
119
120 Universal attribution defaults an un-actored write to "unattributed"
121 rather than skipping it (see object_records.create/update/delete_
122 collection_record), so writes never go missing -- but a growing count
123 here means some caller still isn't passing its own actor through.
124 This is visibility, not enforcement: it always reports "warning", so
125 it can be tightened to fail-closed later once callers are cleaned up.
126 """
127 name = "record change attribution"
128 data_path = Path(
129 data_dir if data_dir is not None else os.environ.get("DBBASIC_DATA_DIR", DEFAULT_DATA_DIR)
130 )
131 root = data_path / object_record_changes.RECORD_CHANGES_DIR
132 if not root.is_dir():
133 return [_result(name, root, "ok", "no record change log yet")]
134
135 cutoff = datetime.now(timezone.utc) - timedelta(hours=window_hours)
136 unattributed_by_collection: dict[str, int] = {}
137 total = 0
138
139 for changes_file in sorted(root.glob(f"*/{object_record_changes.CHANGES_FILE}")):
140 collection = changes_file.parent.name
141 for line in changes_file.read_text(encoding="utf-8", errors="replace").splitlines():
142 if not line.strip():
143 continue
144 try:
145 entry = json.loads(line)
146 except json.JSONDecodeError:
147 continue
148 if not isinstance(entry, dict) or entry.get("actor") != UNATTRIBUTED_ACTOR:
149 continue
150 if not _within_window(entry.get("timestamp"), cutoff):
151 continue
152 total += 1
153 unattributed_by_collection[collection] = unattributed_by_collection.get(collection, 0) + 1
154
155 if total == 0:
156 return [_result(name, root, "ok", f"no unattributed record changes in the last {window_hours}h")]
157
158 top = ", ".join(
159 f"{collection}={count}"
160 for collection, count in sorted(unattributed_by_collection.items(), key=lambda item: -item[1])[:5]
161 )
162 return [
163 _result(
164 name,
165 root,
166 "warning",
167 f"{total} unattributed record change(s) in the last {window_hours}h ({top})",
168 )
169 ]
170
171
172def _within_window(timestamp: object, cutoff: datetime) -> bool:
173 if not isinstance(timestamp, str):
174 return False
175 try:
176 # A trailing "Z" parses only from Python 3.11; 3.10 needs "+00:00".
177 parsed = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
178 except ValueError:
179 return False
180 if parsed.tzinfo is None:
181 parsed = parsed.replace(tzinfo=timezone.utc)
182 return parsed >= cutoff
183
184
185def _check_service_directory(
186 name: str,
187 path: Path,
188 *,
189 expected_user: str,
190 expected_group: str,
191 private_runtime: bool,
192) -> list[CheckResult]:
193 if not path.exists():
194 return [_result(name, path, "error", "missing")]
195 if not path.is_dir():
196 return [_result(name, path, "error", "not a directory")]
197
198 results = _check_owner(path, name, expected_user, expected_group)
199 mode = stat.S_IMODE(path.stat().st_mode)
200
201 if not mode & stat.S_IRUSR or not mode & stat.S_IWUSR or not mode & stat.S_IXUSR:
202 results.append(_result(name, path, "error", f"owner needs rwx permissions, mode is {_mode(mode)}"))
203
204 if mode & stat.S_IWGRP or mode & stat.S_IWOTH:
205 results.append(_result(name, path, "error", f"group/world writable, mode is {_mode(mode)}"))
206
207 if private_runtime and mode & (stat.S_IROTH | stat.S_IXOTH):
208 results.append(
209 _result(
210 name,
211 path,
212 "warning",
213 f"runtime path is visible to other local users, mode is {_mode(mode)}",
214 )
215 )
216
217 if not results:
218 results.append(_result(name, path, "ok", f"directory mode {_mode(mode)}"))
219 return results
220
221
222def _check_env_file(path: Path, *, expected_owner: str, expected_group: str) -> list[CheckResult]:
223 name = "environment file"
224 if not path.exists():
225 return [_result(name, path, "error", "missing")]
226 if not path.is_file():
227 return [_result(name, path, "error", "not a file")]
228
229 results: list[CheckResult] = []
230 owner, group = _owner_group(path)
231 mode = stat.S_IMODE(path.stat().st_mode)
232
233 if owner != expected_owner:
234 results.append(_result(name, path, "error", f"expected owner {expected_owner}, found {owner}"))
235 if group not in {"root", expected_group}:
236 results.append(
237 _result(name, path, "warning", f"expected group root or {expected_group}, found {group}")
238 )
239 if mode & stat.S_IWGRP or mode & stat.S_IRWXO:
240 results.append(
241 _result(name, path, "error", f"too permissive for deployment secrets, mode is {_mode(mode)}")
242 )
243 if mode & (stat.S_IXUSR | stat.S_IXGRP):
244 results.append(_result(name, path, "warning", f"environment file is executable, mode is {_mode(mode)}"))
245
246 if not results:
247 results.append(_result(name, path, "ok", f"file mode {_mode(mode)}"))
248 return results
249
250
251def _check_service_file(path: Path, *, expected_owner: str, expected_group: str) -> list[CheckResult]:
252 name = "systemd service file"
253 if not path.exists():
254 return [_result(name, path, "error", "missing")]
255 if not path.is_file():
256 return [_result(name, path, "error", "not a file")]
257
258 results: list[CheckResult] = []
259 owner, group = _owner_group(path)
260 mode = stat.S_IMODE(path.stat().st_mode)
261
262 if owner != expected_owner:
263 results.append(_result(name, path, "error", f"expected owner {expected_owner}, found {owner}"))
264 if group != expected_group:
265 results.append(_result(name, path, "warning", f"expected group {expected_group}, found {group}"))
266 if mode & stat.S_IWGRP or mode & stat.S_IWOTH:
267 results.append(_result(name, path, "error", f"group/world writable, mode is {_mode(mode)}"))
268
269 content = path.read_text(errors="replace")
270 if "ExecStart=" in content and "uvicorn" in content and "--no-access-log" not in content:
271 results.append(
272 _result(
273 name,
274 path,
275 "warning",
276 "uvicorn access logs are enabled; add --no-access-log and rely on object logs plus metrics",
277 )
278 )
279
280 if not results:
281 results.append(_result(name, path, "ok", f"file mode {_mode(mode)}"))
282 return results
283
284
285def _check_journald_dropin(
286 path: Path,
287 *,
288 expected_owner: str,
289 expected_group: str,
290) -> list[CheckResult]:
291 name = "journald retention drop-in"
292 if not path.exists():
293 return [_result(name, path, "warning", "missing; journald may keep unbounded process logs")]
294 if not path.is_file():
295 return [_result(name, path, "error", "not a file")]
296
297 results: list[CheckResult] = []
298 owner, group = _owner_group(path)
299 mode = stat.S_IMODE(path.stat().st_mode)
300 content = path.read_text(errors="replace")
301
302 if owner != expected_owner:
303 results.append(_result(name, path, "error", f"expected owner {expected_owner}, found {owner}"))
304 if group != expected_group:
305 results.append(_result(name, path, "warning", f"expected group {expected_group}, found {group}"))
306 if mode & stat.S_IWGRP or mode & stat.S_IWOTH:
307 results.append(_result(name, path, "error", f"group/world writable, mode is {_mode(mode)}"))
308 if "[Journal]" not in content:
309 results.append(_result(name, path, "warning", "missing [Journal] section"))
310 if "SystemMaxUse=" not in content and "RuntimeMaxUse=" not in content:
311 results.append(_result(name, path, "warning", "missing journal size cap"))
312 if "MaxRetentionSec=" not in content:
313 results.append(_result(name, path, "warning", "missing journal age retention cap"))
314
315 if not results:
316 results.append(_result(name, path, "ok", f"file mode {_mode(mode)}"))
317 return results
318
319
320def _check_owner(path: Path, name: str, expected_user: str, expected_group: str) -> list[CheckResult]:
321 owner, group = _owner_group(path)
322 results: list[CheckResult] = []
323 if owner != expected_user:
324 results.append(_result(name, path, "error", f"expected owner {expected_user}, found {owner}"))
325 if group != expected_group:
326 results.append(_result(name, path, "error", f"expected group {expected_group}, found {group}"))
327 return results
328
329
330def _owner_group(path: Path) -> tuple[str, str]:
331 info = path.stat()
332 try:
333 owner = pwd.getpwuid(info.st_uid).pw_name
334 except KeyError:
335 owner = str(info.st_uid)
336 try:
337 group = grp.getgrgid(info.st_gid).gr_name
338 except KeyError:
339 group = str(info.st_gid)
340 return owner, group
341
342
343def _result(name: str, path: Path, status: Status, message: str) -> CheckResult:
344 return CheckResult(name=name, path=str(path), status=status, message=message)
345
346
347def _mode(mode: int) -> str:
348 return format(mode, "04o")
349
350
351def main(argv: list[str] | None = None) -> int:
352 parser = argparse.ArgumentParser(description="Check DBBASIC single-VM filesystem layout.")
353 parser.add_argument("--code-dir", type=Path, default=DEFAULT_CODE_DIR)
354 parser.add_argument("--objects-dir", type=Path)
355 parser.add_argument("--data-dir", type=Path)
356 parser.add_argument("--env-file", type=Path, default=DEFAULT_ENV_FILE)
357 parser.add_argument("--service-file", type=Path, default=DEFAULT_SERVICE_FILE)
358 parser.add_argument("--journald-dropin", type=Path, default=DEFAULT_JOURNALD_DROPIN)
359 parser.add_argument("--service-user", default=DEFAULT_SERVICE_USER)
360 parser.add_argument("--service-group", default=DEFAULT_SERVICE_GROUP)
361 parser.add_argument("--env-owner", default="root")
362 parser.add_argument("--system-owner", default="root")
363 parser.add_argument("--system-group", default="root")
364 parser.add_argument(
365 "--unattributed-window-hours",
366 type=int,
367 default=DEFAULT_UNATTRIBUTED_WINDOW_HOURS,
368 help="lookback window for the unattributed record-change count",
369 )
370 parser.add_argument("--json", action="store_true", help="print machine-readable JSON")
371 args = parser.parse_args(argv)
372
373 results = check_single_vm_layout(
374 code_dir=args.code_dir,
375 objects_dir=args.objects_dir,
376 data_dir=args.data_dir,
377 env_file=args.env_file,
378 service_file=args.service_file,
379 journald_dropin=args.journald_dropin,
380 service_user=args.service_user,
381 service_group=args.service_group,
382 env_owner=args.env_owner,
383 system_owner=args.system_owner,
384 system_group=args.system_group,
385 )
386 results.extend(
387 check_unattributed_record_changes(
388 data_dir=args.data_dir,
389 window_hours=args.unattributed_window_hours,
390 )
391 )
392
393 if args.json:
394 print(json.dumps([asdict(result) for result in results], indent=2))
395 else:
396 for result in results:
397 print(f"{result.status.upper():7} {result.name}: {result.path} - {result.message}")
398
399 return 1 if has_errors(results) else 0
400
401
402if __name__ == "__main__":
403 raise SystemExit(main())