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/object_permission_audit.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, 8 minutes ago History
object_permission_audit.py · 14.1 KB · 389 lines
1"""Permission decision audit log.
2
3One JSON line per permission check, appended to
4``data/permissions/audit.jsonl``. The file is bounded the way object logs
5are (object_logs.py, docs/runtime-contract.md "Log maintenance settings"):
6when the active file reaches DBBASIC_PERMISSION_AUDIT_MAX_BYTES it is cut
7into a numbered segment next to it, segments are gzip-compressed, and only
8the newest DBBASIC_PERMISSION_AUDIT_KEEP_ROTATED are kept.
9
10How a cut works, and why it loses nothing:
11
12- Appends never wait for a cut. Each line is one O_APPEND write, made
13 holding a SHARED flock on the open file itself (no second file to open;
14 appenders never wait for one another).
15- A cut is a rename of the active file, under an flock, by whichever
16 writer first sees the file over the limit (re-checked under the lock, so
17 several workers seeing it at once still cut once). A writer that opened
18 the active file just before the rename writes into the renamed segment,
19 which is the same inode. Nothing is copied at cut time.
20- That is why the newest segment stays plain and is only compressed at the
21 NEXT cut, a whole active file of appends later. Compression writes a
22 temp file, renames it into place, then removes the plain segment; a
23 crash in between leaves both forms, which readers count once (the plain
24 one, which is the source) and the next cut cleans up.
25- "A whole active file later" is usually long enough for a writer that
26 opened the file before its rename, and it is not a guarantee: a worker
27 descheduled between its open and its write (a busy box, more workers
28 than cores, a slower free-threaded interpreter) can wake after the next
29 cut copied the segment, and its line went into a file about to be
30 unlinked, or already unlinked, and was lost. CI lost lines this way on
31 3.14t. So the compressor holds an EXCLUSIVE flock on the segment from
32 before its copy until after its unlink, and an appender, once it holds
33 its shared lock, checks the file still has a link; if not, it reopens
34 the active file and appends there.
35- Segment names carry a sequence number before the timestamp, so they sort
36 in the order they were cut even if the clock is set back.
37- A cut that fails (disk full, permissions) is abandoned and the entry is
38 still appended; the next append tries again.
39
40Readers (GET /permissions/audit) read the active file and then segments,
41newest first, until they have `limit` matching entries.
42"""
43
44from __future__ import annotations
45
46import gzip
47import json
48import os
49import re
50import shutil
51from collections import deque
52from contextlib import contextmanager
53from datetime import datetime, timezone
54from pathlib import Path
55from typing import Any, Iterator
56
57from object_versions import DEFAULT_DATA_DIR
58
59PERMISSIONS_DIR = "permissions"
60AUDIT_FILE = "audit.jsonl"
61
62AUDIT_MAX_BYTES_ENV = "DBBASIC_PERMISSION_AUDIT_MAX_BYTES"
63AUDIT_KEEP_ROTATED_ENV = "DBBASIC_PERMISSION_AUDIT_KEEP_ROTATED"
64DEFAULT_AUDIT_MAX_BYTES = 10 * 1024 * 1024
65DEFAULT_AUDIT_KEEP_ROTATED = 32
66
67_SEGMENT_RE = re.compile(r"^audit-(\d{10})-\d{8}T\d{12}Z\.jsonl(\.gz)?$")
68
69
70def audit_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
71 """Return the permission audit file path."""
72 root = Path(base_dir) / PERMISSIONS_DIR
73 path = root / AUDIT_FILE
74 resolved_root = root.resolve(strict=False)
75 resolved_path = path.resolve(strict=False)
76
77 try:
78 resolved_path.relative_to(resolved_root)
79 except ValueError as exc:
80 raise ValueError("Permission audit path escapes permissions directory") from exc
81
82 return path
83
84
85def append_permission_audit(
86 entry: dict[str, Any],
87 base_dir: Path | str = DEFAULT_DATA_DIR,
88) -> Path:
89 """Append one JSON-line permission audit entry, cutting the active file
90 into a segment first when it has reached the size limit."""
91 path = audit_path(base_dir)
92 path.parent.mkdir(parents=True, exist_ok=True)
93
94 max_bytes = _max_bytes()
95 if max_bytes is not None and _size(path) >= max_bytes:
96 try:
97 _rotate(path, max_bytes=max_bytes, keep=_keep_rotated())
98 except OSError:
99 pass # the entry below matters more than the cut; the next append retries
100
101 line = json.dumps(entry, sort_keys=True, separators=(",", ":")) + "\n"
102 for attempt in range(_APPEND_ATTEMPTS):
103 with path.open("a", encoding="utf-8") as handle:
104 # Shared lock on the file itself (no extra open), held until the
105 # close below has flushed the line. A compressor holds it
106 # exclusively from its copy to its unlink, so after taking it a
107 # handle on a segment that has since been compressed sees no
108 # links and starts again on the active file.
109 _lock(handle, shared=True)
110 if _unlinked(handle) and attempt + 1 < _APPEND_ATTEMPTS:
111 continue
112 handle.write(line)
113 handle.flush()
114 break
115
116 return path
117
118
119# A handle needs a second attempt only when its file was cut AND the next
120# cut compressed it while this writer was between open and lock; a third
121# needs that twice more over. The bound is only so a filesystem that
122# reports no links for a live file can never spin an append forever.
123_APPEND_ATTEMPTS = 8
124
125
126def _lock(handle: Any, *, shared: bool) -> None:
127 try:
128 import fcntl
129 except ImportError: # pragma: no cover - not a POSIX host
130 return
131 try:
132 fcntl.flock(handle.fileno(), fcntl.LOCK_SH if shared else fcntl.LOCK_EX)
133 except OSError:
134 # Where flock is emulated with fcntl locks (NFS), a shared lock on a
135 # write-only handle is EBADF. Losing this lock only reopens the old,
136 # rare race; failing would lose the entry, or the request, outright.
137 pass
138
139
140def _unlinked(handle: Any) -> bool:
141 try:
142 return os.fstat(handle.fileno()).st_nlink == 0
143 except OSError:
144 return False
145
146
147def get_permission_audit(
148 base_dir: Path | str = DEFAULT_DATA_DIR,
149 *,
150 limit: int = 100,
151 action: str | None = None,
152 object_id: str | None = None,
153 collection: str | None = None,
154 allowed: bool | None = None,
155 enforced: bool | None = None,
156) -> list[dict[str, Any]]:
157 """Read recent permission audit entries (oldest first, at most `limit`),
158 from the active file and, when that holds too few, the segments before
159 it."""
160 if limit < 1:
161 raise ValueError("Permission audit limit must be at least 1")
162
163 path = audit_path(base_dir)
164 filters = {
165 "action": action,
166 "object_id": object_id,
167 "collection": collection,
168 "allowed": allowed,
169 "enforced": enforced,
170 }
171
172 # The active file is opened BEFORE the segments are listed. A cut in
173 # between turns the file this handle reads into the newest segment, so
174 # that segment is recognised by inode and skipped: read once, not twice.
175 # (Listing first would miss it instead.)
176 active_inode = None
177 try:
178 handle = path.open(encoding="utf-8")
179 except FileNotFoundError:
180 newest: list[dict[str, Any]] = []
181 else:
182 with handle:
183 active_inode = os.fstat(handle.fileno()).st_ino
184 newest = _matching(handle, limit, filters)
185
186 collected: deque[list[dict[str, Any]]] = deque([newest])
187 count = len(newest)
188 for segment in reversed(list_rotated_audit_files(base_dir)):
189 if count >= limit:
190 break
191 entries = _read_segment(segment, limit, filters, skip_inode=active_inode)
192 collected.appendleft(entries)
193 count += len(entries)
194
195 merged = [entry for entries in collected for entry in entries]
196 return merged[-limit:]
197
198
199def list_rotated_audit_files(base_dir: Path | str = DEFAULT_DATA_DIR) -> list[Path]:
200 """The audit segments, oldest first, one path per segment.
201
202 A segment present in both forms (a crash between writing the compressed
203 copy and removing the plain one) is listed once, as the plain file: it
204 is the source the compressed copy was made from.
205 """
206 root = audit_path(base_dir).parent
207 try:
208 names = os.listdir(root)
209 except (FileNotFoundError, NotADirectoryError):
210 return []
211 chosen: dict[str, str] = {}
212 for name in names:
213 match = _SEGMENT_RE.match(name)
214 if match is None or not (root / name).is_file():
215 continue
216 stem = name[: -len(".gz")] if match.group(2) else name
217 if stem not in chosen or not match.group(2):
218 chosen[stem] = name
219 return [root / chosen[stem] for stem in sorted(chosen)]
220
221
222def _max_bytes() -> int | None:
223 """The active file's size limit; None means never cut."""
224 value = _env_int(AUDIT_MAX_BYTES_ENV, DEFAULT_AUDIT_MAX_BYTES)
225 return value if value > 0 else None
226
227
228def _keep_rotated() -> int | None:
229 """How many segments to keep; None means keep them all."""
230 value = _env_int(AUDIT_KEEP_ROTATED_ENV, DEFAULT_AUDIT_KEEP_ROTATED)
231 return value if value > 0 else None
232
233
234def _env_int(name: str, default: int) -> int:
235 raw = os.environ.get(name)
236 if raw is None:
237 return default
238 try:
239 return int(raw)
240 except ValueError:
241 return default
242
243
244def _size(path: Path) -> int:
245 try:
246 return os.stat(path).st_size
247 except OSError:
248 return 0
249
250
251def _rotate(path: Path, *, max_bytes: int, keep: int | None) -> None:
252 with _rotation_lock(path):
253 # Another worker may have cut it between our stat and the lock.
254 if _size(path) < max_bytes:
255 return
256 root = path.parent
257 segments = list_rotated_audit_files(root.parent)
258 sequence = 1 + max((_sequence(segment) for segment in segments), default=0)
259 stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")
260 cut = root / f"audit-{sequence:010d}-{stamp}.jsonl"
261 os.replace(path, cut)
262
263 # Every older plain segment is compressed now (the one just cut
264 # waits for the next rotation; see the module docstring).
265 for segment in segments:
266 if not segment.name.endswith(".gz"):
267 _compress(segment)
268
269 if keep is not None:
270 for stale in list_rotated_audit_files(root.parent)[:-keep]:
271 for form in (stale, _gz_name(stale), _plain_name(stale)):
272 form.unlink(missing_ok=True)
273
274
275def _compress(segment: Path) -> None:
276 """Replace a plain segment with its gzip copy. The exclusive lock on the
277 segment is held from before the copy until after the unlink: a writer
278 still holding a handle on this inode either finishes its line before
279 the copy starts, or finds the file unlinked once it gets the lock and
280 appends to the active file instead (append_permission_audit)."""
281 target = _gz_name(segment)
282 temp = segment.with_name(f".{target.name}.tmp")
283 with segment.open("rb") as source:
284 _lock(source, shared=False)
285 try:
286 with gzip.open(temp, "wb", compresslevel=6) as sink:
287 shutil.copyfileobj(source, sink)
288 os.replace(temp, target)
289 except BaseException:
290 temp.unlink(missing_ok=True)
291 raise
292 segment.unlink(missing_ok=True)
293
294
295def _gz_name(segment: Path) -> Path:
296 return segment if segment.name.endswith(".gz") else segment.with_name(segment.name + ".gz")
297
298
299def _plain_name(segment: Path) -> Path:
300 return segment.with_name(segment.name[: -len(".gz")]) if segment.name.endswith(".gz") else segment
301
302
303def _sequence(segment: Path) -> int:
304 match = _SEGMENT_RE.match(segment.name)
305 return int(match.group(1)) if match else 0
306
307
308@contextmanager
309def _rotation_lock(path: Path) -> Iterator[None]:
310 """An advisory flock around a cut, as object_logs takes around its own
311 rotation. Only cuts take it; appends never wait for it."""
312 lock_path = path.with_name(f".{path.name}.lock")
313 with lock_path.open("a") as lock_file:
314 try:
315 import fcntl
316 except ImportError: # pragma: no cover - not a POSIX host
317 fcntl = None
318 if fcntl is not None:
319 fcntl.flock(lock_file, fcntl.LOCK_EX)
320 try:
321 yield
322 finally:
323 if fcntl is not None:
324 fcntl.flock(lock_file, fcntl.LOCK_UN)
325
326
327def _read_segment(
328 segment: Path,
329 limit: int,
330 filters: dict[str, Any],
331 *,
332 skip_inode: int | None,
333) -> list[dict[str, Any]]:
334 """The newest `limit` matching entries of one segment. A plain segment
335 compressed (and removed) since it was listed is read from its
336 compressed copy; an unreadable segment contributes nothing."""
337 for candidate in (segment, _gz_name(segment)):
338 try:
339 if candidate.name.endswith(".gz"):
340 with gzip.open(candidate, "rt", encoding="utf-8") as handle:
341 return _matching(handle, limit, filters)
342 with candidate.open(encoding="utf-8") as handle:
343 if skip_inode is not None and os.fstat(handle.fileno()).st_ino == skip_inode:
344 return []
345 return _matching(handle, limit, filters)
346 except FileNotFoundError:
347 continue
348 except (OSError, EOFError, UnicodeDecodeError):
349 return []
350 return []
351
352
353def _matching(lines: Any, limit: int, filters: dict[str, Any]) -> list[dict[str, Any]]:
354 entries: deque[dict[str, Any]] = deque(maxlen=limit)
355 for line in lines:
356 if not line.strip():
357 continue
358 try:
359 entry = json.loads(line)
360 except json.JSONDecodeError:
361 continue
362 if _matches_filters(entry, **filters):
363 entries.append(entry)
364 return list(entries)
365
366
367def _matches_filters(
368 entry: dict[str, Any],
369 *,
370 action: str | None,
371 object_id: str | None,
372 collection: str | None,
373 allowed: bool | None,
374 enforced: bool | None,
375) -> bool:
376 if action is not None and entry.get("action") != action:
377 return False
378 if object_id is not None and entry.get("object_id") != object_id:
379 return False
380 if collection is not None and entry.get("collection") != collection:
381 return False
382 if enforced is not None and entry.get("enforced") is not enforced:
383 return False
384 if allowed is not None:
385 decision = entry.get("decision")
386 if not isinstance(decision, dict) or decision.get("allowed") is not allowed:
387 return False
388
389 return True