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.
object_permission_store.py · 19.0 KB · 424 lines
| 1 | """File-backed permission policy storage.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import json |
| 6 | import os |
| 7 | import threading |
| 8 | import time |
| 9 | from pathlib import Path |
| 10 | from typing import Any |
| 11 | |
| 12 | import object_permissions |
| 13 | from object_versions import DEFAULT_DATA_DIR |
| 14 | |
| 15 | PERMISSIONS_DIR = "permissions" |
| 16 | POLICY_FILE = "policy.json" |
| 17 | DEFAULT_POLICY = object_permissions.PermissionPolicy(access_mode="role_based") |
| 18 | |
| 19 | # Parsed policies: {base_dir as the caller spelled it: (policy file path, |
| 20 | # stat signature, policy)}. See load_policy for what makes an entry usable. |
| 21 | # The last item is the fail-closed setting the entry was built under |
| 22 | # (DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS): an entry built under the other |
| 23 | # value is not used. |
| 24 | _POLICY_CACHE: dict[str, tuple[str, tuple[int, int, int, int, int], object_permissions.PermissionPolicy, bool]] = {} |
| 25 | _POLICY_CACHE_LOCK = threading.Lock() |
| 26 | _POLICY_CACHE_MAX_DIRS = 64 |
| 27 | # A policy file changed more recently than this when it was read is not |
| 28 | # cached: a second write inside the filesystem's timestamp granularity would |
| 29 | # leave the same stat behind. The margin object_identity's session cache |
| 30 | # uses, comfortably above coarse (4-10 ms) granularities. |
| 31 | _POLICY_CACHE_RACY_NS = 50_000_000 |
| 32 | |
| 33 | |
| 34 | def policy_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path: |
| 35 | """Return the permission policy file path.""" |
| 36 | root = Path(base_dir) / PERMISSIONS_DIR |
| 37 | path = root / POLICY_FILE |
| 38 | resolved_root = root.resolve(strict=False) |
| 39 | resolved_path = path.resolve(strict=False) |
| 40 | |
| 41 | try: |
| 42 | resolved_path.relative_to(resolved_root) |
| 43 | except ValueError as exc: |
| 44 | raise ValueError("Permission policy path escapes permissions directory") from exc |
| 45 | |
| 46 | return path |
| 47 | |
| 48 | |
| 49 | def load_policy(base_dir: Path | str = DEFAULT_DATA_DIR) -> object_permissions.PermissionPolicy: |
| 50 | """Load the persisted policy, or return the conservative default. |
| 51 | |
| 52 | Parsing the file and rebuilding its rules cost about 1 ms with 246 |
| 53 | rules, one to three times per request. The parsed policy is now kept |
| 54 | and returned for as long as the file still has the stat it was read |
| 55 | under; a hit is one lstat. |
| 56 | |
| 57 | Every permission decision is made from what this returns, so the rule |
| 58 | is: WHEN IN DOUBT, READ THE FILE. Nothing in this process is told when |
| 59 | the policy changes (another worker's API call, the package installer, |
| 60 | the daemon and an operator's editor all write it), so each call stats |
| 61 | the file and compares (mtime_ns, ctime_ns, size, inode, device): |
| 62 | |
| 63 | - save_policy and the installer replace the file, which is a new inode |
| 64 | even inside one timestamp tick and at the same size; |
| 65 | - an edit in place moves mtime, and ctime, which cannot be set back the |
| 66 | way mtime can (`touch -r`, a restore that preserves times); |
| 67 | - the stat is taken BEFORE the read, so a write landing mid-read leaves |
| 68 | a signature older than the content and the next call reads again. |
| 69 | |
| 70 | Nothing is kept, and the file is read on every call, when a stat cannot |
| 71 | vouch for it: the file changed within _POLICY_CACHE_RACY_NS of being |
| 72 | read (a second in-place write in the same tick would be invisible), it |
| 73 | is a symlink (its target can change without it), it is missing (the |
| 74 | default applies until a file appears), or it does not parse (the error |
| 75 | is raised every time, never remembered and never papered over with an |
| 76 | older policy). |
| 77 | |
| 78 | The policy returned is shared between callers. It is a frozen dataclass |
| 79 | of frozen rules; the mappings inside (roles, user_roles, a rule's |
| 80 | row_filter) are plain dicts and must be treated as read-only, as every |
| 81 | caller already does. |
| 82 | |
| 83 | With DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS on, a stored ALLOW rule |
| 84 | with a serious finding (a key that would narrow it was dropped) is |
| 85 | returned marked not_applied and no decision is made from it |
| 86 | (object_permissions.apply_fail_closed). The rule is still in `rules`, so |
| 87 | the policy serialises and saves as before. Deny rules are never marked. |
| 88 | If the findings cannot be worked out, this raises ValueError exactly as |
| 89 | for a file that does not parse: no policy, so callers fail closed. With |
| 90 | the setting off (the default) none of this runs. |
| 91 | """ |
| 92 | try: |
| 93 | key = os.fspath(base_dir) |
| 94 | except TypeError: |
| 95 | key = None |
| 96 | fail_closed = object_permissions.fail_closed_widened_allows() |
| 97 | entry = _POLICY_CACHE.get(key) if key is not None else None |
| 98 | if (entry is not None and entry[3] == fail_closed |
| 99 | and _policy_file_signature(entry[0]) == entry[1]): |
| 100 | return entry[2] |
| 101 | |
| 102 | path = policy_path(base_dir) |
| 103 | signature = _policy_file_signature(str(path)) |
| 104 | read_at = time.time_ns() |
| 105 | try: |
| 106 | if not path.exists(): |
| 107 | policy = None |
| 108 | else: |
| 109 | try: |
| 110 | payload = json.loads(path.read_text()) |
| 111 | except json.JSONDecodeError as exc: |
| 112 | raise ValueError("Permission policy file contains invalid JSON") from exc |
| 113 | policy = object_permissions.policy_from_dict(payload) |
| 114 | if fail_closed: |
| 115 | try: |
| 116 | policy = object_permissions.apply_fail_closed(policy, payload) |
| 117 | except Exception as exc: # noqa: BLE001 -- unknown rules must not be applied |
| 118 | raise ValueError( |
| 119 | "Permission policy could not be checked for allow rules that apply more " |
| 120 | f"widely than written ({object_permissions.FAIL_CLOSED_WIDENED_ALLOWS_ENV} " |
| 121 | f"is on): {exc}" |
| 122 | ) from exc |
| 123 | except BaseException: |
| 124 | _drop_cached_policy(key) |
| 125 | raise |
| 126 | |
| 127 | settled = ( |
| 128 | policy is not None |
| 129 | and key is not None |
| 130 | and signature is not None |
| 131 | and read_at - max(signature[0], signature[1]) >= _POLICY_CACHE_RACY_NS |
| 132 | ) |
| 133 | if not settled: |
| 134 | _drop_cached_policy(key) |
| 135 | return DEFAULT_POLICY if policy is None else policy |
| 136 | with _POLICY_CACHE_LOCK: |
| 137 | if key not in _POLICY_CACHE and len(_POLICY_CACHE) >= _POLICY_CACHE_MAX_DIRS: |
| 138 | _POLICY_CACHE.clear() |
| 139 | _POLICY_CACHE[key] = (str(path), signature, policy, fail_closed) |
| 140 | return policy |
| 141 | |
| 142 | |
| 143 | def _policy_file_signature(path: str) -> tuple[int, int, int, int, int] | None: |
| 144 | """(mtime_ns, ctime_ns, size, inode, device) of a regular file, without |
| 145 | following a symlink; None for a symlink, a directory or nothing.""" |
| 146 | try: |
| 147 | info = os.lstat(path) |
| 148 | except OSError: |
| 149 | return None |
| 150 | if (info.st_mode & 0o170000) != 0o100000: |
| 151 | return None |
| 152 | return (info.st_mtime_ns, info.st_ctime_ns, info.st_size, info.st_ino, info.st_dev) |
| 153 | |
| 154 | |
| 155 | def _drop_cached_policy(key: str | None) -> None: |
| 156 | if key is not None: |
| 157 | with _POLICY_CACHE_LOCK: |
| 158 | _POLICY_CACHE.pop(key, None) |
| 159 | |
| 160 | |
| 161 | def save_policy( |
| 162 | policy: object_permissions.PermissionPolicy, |
| 163 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 164 | *, |
| 165 | keep_stored_mistakes: bool = True, |
| 166 | ) -> Path: |
| 167 | """Atomically save the permission policy. |
| 168 | |
| 169 | A rule the stored file holds with a SERIOUS finding (a misspelt |
| 170 | `row_filter` the engine ignores, a deny that can never apply) is written |
| 171 | back exactly as the file holds it, mistake included, when `policy` still |
| 172 | carries it as the engine reads it. Every writer that loads the policy, |
| 173 | changes something else and saves (a package install, a retraction) goes |
| 174 | through here, and written as the engine reads it the misspelt key would |
| 175 | be gone: the rule would become "an allow on every row" as if somebody |
| 176 | had written that, and the finding and its alert would vanish. The |
| 177 | engine reads the stored form and the rewritten form the same way |
| 178 | (object_permissions.canonical_rule_key), so no decision changes; this |
| 179 | holds whatever DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS says, and with |
| 180 | it on it is also what keeps a stopped rule stopped. |
| 181 | |
| 182 | The same goes for a top-level key the engine ignores with a SERIOUS |
| 183 | finding (a misspelt `rulez` or `admin_role`): it is written back under |
| 184 | the same name with the same value. `policy` cannot carry a key the |
| 185 | engine never read, so without this every such save would drop it, and |
| 186 | its finding and alert with it. The engine goes on ignoring it, so no |
| 187 | decision changes. An unknown key whose finding is not serious is |
| 188 | dropped, as always. |
| 189 | |
| 190 | A rule load_policy marked not_applied MUST be written in its stored |
| 191 | form: if that cannot be found again, nothing is written and ValueError |
| 192 | is raised. A rule that is not marked and has no stored form with a |
| 193 | serious finding is written as the engine reads it, as always. |
| 194 | |
| 195 | `keep_stored_mistakes=False` is for replace_policy only: an operator's |
| 196 | own save, already checked, is written as given. |
| 197 | """ |
| 198 | path = policy_path(base_dir) |
| 199 | path.parent.mkdir(parents=True, exist_ok=True) |
| 200 | temp_path = path.with_name(f".{path.name}.tmp") |
| 201 | payload = object_permissions.policy_to_dict(policy) |
| 202 | if keep_stored_mistakes: |
| 203 | as_stored, ignored_keys = _serious_mistakes_as_stored(base_dir) |
| 204 | keys = [object_permissions.canonical_rule_key(rule) for rule in payload["rules"]] |
| 205 | stopped = [index for index, rule in enumerate(policy.rules) |
| 206 | if rule.not_applied and rule.effect == "allow"] |
| 207 | # Stopped rules first: each must get its stored form back. |
| 208 | for index in stopped: |
| 209 | matches = as_stored.get(keys[index]) |
| 210 | if not matches: |
| 211 | raise ValueError( |
| 212 | f"Permission policy not saved: rule {index} is an allow that is not applied " |
| 213 | f"({object_permissions.FAIL_CLOSED_WIDENED_ALLOWS_ENV} is on) and the stored " |
| 214 | "rule it came from could not be found again; fix or remove it first " |
| 215 | "(GET /permissions/status lists it)." |
| 216 | ) |
| 217 | payload["rules"][index] = matches.pop(0) |
| 218 | for index in range(len(keys)): |
| 219 | if index not in stopped and as_stored.get(keys[index]): |
| 220 | payload["rules"][index] = as_stored[keys[index]].pop(0) |
| 221 | for key, value in ignored_keys.items(): |
| 222 | payload.setdefault(key, value) |
| 223 | |
| 224 | temp_path.write_text(_json_dump(payload)) |
| 225 | temp_path.replace(path) |
| 226 | return path |
| 227 | |
| 228 | |
| 229 | def _serious_mistakes_as_stored( |
| 230 | base_dir: Path | str, |
| 231 | ) -> tuple[dict[str | None, list[Any]], dict[str, Any]]: |
| 232 | """What the stored file holds with a serious finding, as the file holds it: |
| 233 | |
| 234 | - {the rule as the engine reads it: [the rule as stored, in file |
| 235 | order]} for the rules, allow or deny; |
| 236 | - {key: value} for the top-level keys the engine ignores (`rulez`, |
| 237 | `admin_role`). |
| 238 | |
| 239 | Both empty when there is no stored policy or it cannot be judged.""" |
| 240 | found: dict[str | None, list[Any]] = {} |
| 241 | ignored_keys: dict[str, Any] = {} |
| 242 | try: |
| 243 | stored = read_stored_payload(base_dir) |
| 244 | if stored is None: |
| 245 | return found, ignored_keys |
| 246 | serious = [ |
| 247 | finding |
| 248 | for finding in object_permissions.stored_policy_findings(stored, fail_closed=False) |
| 249 | if finding["serious"] |
| 250 | ] |
| 251 | for finding in serious: |
| 252 | key = finding["key"] |
| 253 | if finding["index"] is None and key in stored and key not in object_permissions.POLICY_KEYS: |
| 254 | ignored_keys[key] = stored[key] |
| 255 | indexes = sorted({finding["index"] for finding in serious if finding["index"] is not None}) |
| 256 | for index in indexes: |
| 257 | rule = stored["rules"][index] |
| 258 | key = object_permissions.canonical_rule_key(rule) |
| 259 | if key is not None: |
| 260 | found.setdefault(key, []).append(rule) |
| 261 | except Exception: # noqa: BLE001 -- nothing kept: a stopped rule then refuses the save |
| 262 | return {}, {} |
| 263 | return found, ignored_keys |
| 264 | |
| 265 | |
| 266 | def replace_policy( |
| 267 | payload: dict[str, Any], |
| 268 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 269 | ) -> object_permissions.PermissionPolicy: |
| 270 | """Validate and persist a policy an operator wrote (PUT /permissions/ |
| 271 | policy, the starter policy). |
| 272 | |
| 273 | A save is held to DRON before anything is written: a policy with a key |
| 274 | the engine would drop, or a rule the package check refuses, raises |
| 275 | object_permissions.PolicyDeclarationError (a ValueError) naming each |
| 276 | rule and key. Rules the stored policy already holds, read the same way, |
| 277 | are not judged again (object_permissions.policy_declaration_problems), |
| 278 | so a policy GET /permissions/policy returned saves back -- unless the |
| 279 | stored file holds a SERIOUS finding (a mistake that lets it allow more |
| 280 | than written) and the save would write that rule back in its widened |
| 281 | form: then it raises WidenedRuleKeptError (also a ValueError, 400) until |
| 282 | the same save fixes or removes it (object_permissions.widened_findings_kept). |
| 283 | """ |
| 284 | stored = read_stored_payload(base_dir) |
| 285 | stored_rules = stored.get("rules") if isinstance(stored, dict) else None |
| 286 | object_permissions.check_policy_declaration( |
| 287 | payload, stored_rules=stored_rules if isinstance(stored_rules, list) else []) |
| 288 | policy = object_permissions.policy_from_dict(payload) |
| 289 | # Fail closed on a widening the stored file holds by mistake: saving it |
| 290 | # back as the engine reads it would make it "written" with nobody having |
| 291 | # decided it, and erase the report. The save must fix or remove it. |
| 292 | kept = object_permissions.widened_findings_kept(stored, payload) if stored is not None else [] |
| 293 | if kept: |
| 294 | raise object_permissions.WidenedRuleKeptError(kept) |
| 295 | save_policy(policy, base_dir=base_dir, keep_stored_mistakes=False) |
| 296 | return policy |
| 297 | |
| 298 | |
| 299 | def read_stored_payload(base_dir: Path | str = DEFAULT_DATA_DIR) -> Any: |
| 300 | """The stored policy file as JSON, or None when it is missing, cannot be |
| 301 | read or is not JSON (load_policy reports those). Never raises.""" |
| 302 | try: |
| 303 | path = policy_path(base_dir) |
| 304 | if not path.exists(): |
| 305 | return None |
| 306 | return json.loads(path.read_text()) |
| 307 | except (OSError, ValueError): |
| 308 | return None |
| 309 | |
| 310 | |
| 311 | def stored_rule_payloads(base_dir: Path | str = DEFAULT_DATA_DIR) -> list[Any]: |
| 312 | """The rules of the stored policy as written, or [] when there are none |
| 313 | to read. A save does not judge these again.""" |
| 314 | payload = read_stored_payload(base_dir) |
| 315 | rules = payload.get("rules") if isinstance(payload, dict) else None |
| 316 | return list(rules) if isinstance(rules, list) else [] |
| 317 | |
| 318 | |
| 319 | def stored_policy_findings(base_dir: Path | str = DEFAULT_DATA_DIR) -> list[dict[str, Any]]: |
| 320 | """What the engine does today with each DRON mistake in the stored |
| 321 | policy file (object_permissions.stored_policy_findings). Report only; |
| 322 | what load_policy does with a serious allow depends on |
| 323 | DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS, and the finding says which. |
| 324 | Never raises.""" |
| 325 | payload = read_stored_payload(base_dir) |
| 326 | if payload is None: |
| 327 | return [] |
| 328 | try: |
| 329 | return object_permissions.stored_policy_findings(payload) |
| 330 | except Exception: # noqa: BLE001 -- a report must never take a route down |
| 331 | return [] |
| 332 | |
| 333 | |
| 334 | #: The staff roles a business assigns (decision 5, owner, 2026-11-30): keep |
| 335 | #: `registered` = customer and role:manager = staff; cashier and bookkeeper |
| 336 | #: are optional narrower staff roles, and owner sits above them all. Labels |
| 337 | #: and a sentence each -- what a role may do is the packages' rules, so a |
| 338 | #: preset grants nothing by being listed (permissions fail closed). |
| 339 | ROLE_PRESETS: dict[str, dict[str, Any]] = { |
| 340 | "owner": {"label": "Owner", "optional": False, |
| 341 | "description": "Runs the business: everything a manager does, plus the books " |
| 342 | "(chart of accounts, journals, closing periods) and settings."}, |
| 343 | "manager": {"label": "Manager", "optional": False, |
| 344 | "description": "Staff. Reads every sale, records payments and refunds, approves " |
| 345 | "corrections and expenses. Not the books."}, |
| 346 | "cashier": {"label": "Cashier", "optional": True, |
| 347 | "description": "Till work only: rings up, takes payment, voids an unpaid item, " |
| 348 | "corrects a paid one up to the shop's limit."}, |
| 349 | "finance": {"label": "Bookkeeper", "optional": True, |
| 350 | "description": "Keeps the books: chart of accounts, journals, reconciliation, " |
| 351 | "closing periods, finance policy. Not the till."}, |
| 352 | } |
| 353 | |
| 354 | |
| 355 | def starter_policy_payload() -> dict[str, Any]: |
| 356 | """Return the documented starter policy for a fresh deployment. |
| 357 | |
| 358 | Role-based, with the smallest grants that keep a public staging site |
| 359 | working once enforcement is on: anonymous visitors can run the public |
| 360 | pages and read the probe demo records; signed-in users can write probe |
| 361 | records. Admin-role subjects bypass rules entirely. Deployments should edit |
| 362 | this per app rather than widen it in place. |
| 363 | |
| 364 | There is deliberately no rule for `registered` (or `public`) without a |
| 365 | collection or an object_id. It used to be here -- "signed-in users can |
| 366 | read and run objects" -- and a rule that names no resource matches every |
| 367 | resource, so every signed-in account could run every object (runners, |
| 368 | sweepers, hooks, generators a package gives only to a manager) and read |
| 369 | every collection, and the row filters packages ship decided nothing: the |
| 370 | engine returns the first allow rule that matches and never compares it |
| 371 | with the others. What users may reach is what the installed packages' |
| 372 | rules (and the operator's own, written per resource) grant. |
| 373 | GET /permissions/unshipped flags such a rule as "wide" on a box that |
| 374 | still has one. tests/test_starter_policy_scope.py pins this. |
| 375 | """ |
| 376 | return { |
| 377 | "access_mode": "role_based", |
| 378 | # The role presets (decision 5, owner, 2026-11-30). Labels only: a |
| 379 | # role grants what the installed packages' rules give it, nothing |
| 380 | # more. `registered` (any signed-in account, no role) is a customer; |
| 381 | # the rest are staff, and only manager is needed to run a shop. |
| 382 | "roles": dict(ROLE_PRESETS), |
| 383 | "rules": [ |
| 384 | { |
| 385 | "effect": "allow", |
| 386 | "principal": "public", |
| 387 | "actions": ["execute"], |
| 388 | "object_id": "site_home", |
| 389 | "reason": "public home page", |
| 390 | }, |
| 391 | { |
| 392 | "effect": "allow", |
| 393 | "principal": "public", |
| 394 | "actions": ["execute"], |
| 395 | "object_id": "system_dashboard", |
| 396 | "reason": "public staging dashboard", |
| 397 | }, |
| 398 | { |
| 399 | "effect": "allow", |
| 400 | "principal": "public", |
| 401 | "actions": ["execute"], |
| 402 | "object_id": "system_write_probe", |
| 403 | "reason": "public write probe page", |
| 404 | }, |
| 405 | { |
| 406 | "effect": "allow", |
| 407 | "principal": "public", |
| 408 | "actions": ["read"], |
| 409 | "collection": "dbbasic_probe", |
| 410 | "reason": "probe records are public demo data", |
| 411 | }, |
| 412 | { |
| 413 | "effect": "allow", |
| 414 | "principal": "registered", |
| 415 | "actions": ["create", "update", "delete"], |
| 416 | "collection": "dbbasic_probe", |
| 417 | "reason": "signed-in users can write probe records", |
| 418 | }, |
| 419 | ], |
| 420 | } |
| 421 | |
| 422 | |
| 423 | def _json_dump(payload: dict[str, Any]) -> str: |
| 424 | return json.dumps(payload, indent=2, sort_keys=True) + "\n" |