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_policy_diff.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
object_policy_diff.py · 21.4 KB · 524 lines
1"""The difference in permission policy a restore would make.
2
3A restore can put back an older permission policy: rules added since the
4snapshot to close a hole disappear, a user given a role since keeps it or
5loses it, a field hidden since becomes editable again. Nobody should apply
6that without seeing it. This module computes, for a runtime backup and a
7live data directory, what the restore would change in who may do what:
8
9- ``data/permissions/policy.json``: access mode, admin roles, user roles,
10 role metadata and the rules (added, removed, changed, reordered). A
11 missing file is the server's default policy, exactly as load_policy
12 reads it, because a package restore prunes a policy the snapshot did
13 not have.
14- the field permissions declared in ``data/schemas/*.json``.
15
16Every change is classified by what it does, read from the live state to the
17snapshot's: ``loosens`` (someone may do something they may not do now),
18``tightens``, or ``neutral`` (labels, reasons). When a change cannot be
19proven to tighten it is counted as loosening: a row filter that changed,
20a validity window that moved, a reordering of rules. A restore that loosens
21is called out separately by every caller.
22
23Fail closed: a policy or schema that cannot be read or parsed, on either
24side, raises PolicyDiffError, and callers refuse the restore. Nothing here
25writes.
26"""
27from __future__ import annotations
28
29import hashlib
30import json
31import tarfile
32from pathlib import Path, PurePosixPath
33from typing import Any, Iterable, Mapping, Sequence
34
35import object_field_permissions
36import object_permission_store
37import object_permissions
38
39POLICY_MEMBER = "data/permissions/policy.json"
40SCHEMAS_PREFIX = "data/schemas/"
41
42LOOSENS = "loosens"
43TIGHTENS = "tightens"
44NEUTRAL = "neutral"
45
46_ACCESS_RANK = {"hidden": 0, "read": 1, "edit": 2}
47_UNCONSTRAINED = "edit"
48_DEFAULT_KEY = "(anyone else)"
49
50
51class PolicyDiffError(Exception):
52 """The policy difference cannot be computed; the restore must be refused."""
53
54
55# --- reading both sides ---------------------------------------------------------
56
57
58def restore_policy_diff(
59 backup_path: Path | str,
60 data_dir: Path | str,
61 *,
62 select: Sequence[str] | None = None,
63 prune: bool = True,
64) -> dict[str, Any]:
65 """What restoring ``backup_path`` over ``data_dir`` changes in policy.
66
67 ``select`` (archive-relative selectors, as restore_runtime_backup takes
68 them) limits the comparison to the members a scoped restore writes;
69 None compares everything a whole restore writes. ``prune`` says whether
70 the restore removes what the snapshot does not have (a package restore
71 does); without it a policy or schema missing from the archive stays.
72 """
73 try:
74 snapshot_policy_raw, snapshot_schemas_raw = _archive_policy_sources(backup_path)
75 live_policy_raw, live_schemas_raw = _live_policy_sources(Path(data_dir))
76 except (OSError, tarfile.TarError, UnicodeDecodeError) as exc:
77 raise PolicyDiffError(f"cannot read the policy to compare: {exc}") from exc
78
79 def selected(name: str) -> bool:
80 if select is None:
81 return True
82 return any(
83 name == s.strip("/") or name.startswith(s.strip("/") + "/") for s in select
84 )
85
86 if not selected(POLICY_MEMBER) or (snapshot_policy_raw is None and not prune):
87 snapshot_policy_raw = live_policy_raw
88 schema_names = set(snapshot_schemas_raw) | set(live_schemas_raw)
89 for name in schema_names:
90 kept = name not in snapshot_schemas_raw and not prune
91 if kept or not selected(f"{SCHEMAS_PREFIX}{name}.json"):
92 if name in live_schemas_raw:
93 snapshot_schemas_raw[name] = live_schemas_raw[name]
94 else:
95 snapshot_schemas_raw.pop(name, None)
96
97 current = _parse_policy(live_policy_raw, where="the live policy")
98 snapshot = _parse_policy(snapshot_policy_raw, where="the snapshot's policy")
99 current_fields = _field_permissions(live_schemas_raw, where="live")
100 snapshot_fields = _field_permissions(snapshot_schemas_raw, where="snapshot")
101 diff = compute_policy_diff(current, snapshot, current_fields, snapshot_fields)
102 # A restore puts a stored file back; it is not refused for DRON mistakes
103 # (a box reads its own files as it always did), but the preview says
104 # which the restored file holds and what the engine will do with each,
105 # because the comparison above sees only the engine's reading of it.
106 diff["findings"] = _snapshot_findings(snapshot_policy_raw)
107 return diff
108
109
110def _snapshot_findings(raw: str | None) -> list[dict[str, Any]]:
111 if raw is None:
112 return []
113 try:
114 return object_permissions.stored_policy_findings(json.loads(raw))
115 except ValueError: # _parse_policy has already refused anything worse
116 return []
117
118
119def _archive_policy_sources(backup_path: Path | str) -> tuple[str | None, dict[str, str]]:
120 policy: str | None = None
121 schemas: dict[str, str] = {}
122 with tarfile.open(backup_path, "r:*") as archive:
123 for member in archive.getmembers():
124 if not member.isfile():
125 continue
126 name = member.name
127 if name == POLICY_MEMBER:
128 policy = _member_text(archive, member)
129 elif _schema_member_name(name) is not None:
130 schemas[_schema_member_name(name)] = _member_text(archive, member)
131 return policy, schemas
132
133
134def _member_text(archive: tarfile.TarFile, member: tarfile.TarInfo) -> str:
135 extracted = archive.extractfile(member)
136 if extracted is None:
137 raise PolicyDiffError(f"cannot read archive member: {member.name}")
138 return extracted.read().decode("utf-8")
139
140
141def _schema_member_name(name: str) -> str | None:
142 parts = PurePosixPath(name).parts
143 if len(parts) == 3 and parts[:2] == ("data", "schemas") and parts[2].endswith(".json"):
144 return parts[2][: -len(".json")]
145 return None
146
147
148def _live_policy_sources(data_dir: Path) -> tuple[str | None, dict[str, str]]:
149 policy_file = object_permission_store.policy_path(data_dir)
150 # Read as load_policy reads it: through a link, absent means default.
151 policy = policy_file.read_text() if policy_file.exists() else None
152 schemas: dict[str, str] = {}
153 schemas_dir = data_dir / "schemas"
154 if schemas_dir.is_dir():
155 for path in sorted(schemas_dir.glob("*.json")):
156 if path.is_file():
157 schemas[path.stem] = path.read_text()
158 return policy, schemas
159
160
161def _parse_policy(raw: str | None, *, where: str) -> dict[str, Any]:
162 if raw is None:
163 return object_permissions.policy_to_dict(object_permission_store.DEFAULT_POLICY)
164 try:
165 payload = json.loads(raw)
166 policy = object_permissions.policy_from_dict(payload)
167 except Exception as exc: # fail closed: anything unreadable refuses the restore
168 raise PolicyDiffError(f"{where} cannot be read: {exc}") from exc
169 return object_permissions.policy_to_dict(policy)
170
171
172def _field_permissions(
173 schemas: Mapping[str, str], *, where: str
174) -> dict[tuple[str, str], tuple[dict[str, str], str | None] | None]:
175 """{(collection, field): (per-principal access, default) or None}.
176
177 None is a field with no permissions (unconstrained); a field in no
178 schema is absent from the map and reads the same.
179 """
180 result: dict[tuple[str, str], tuple[dict[str, str], str | None] | None] = {}
181 for collection, raw in schemas.items():
182 try:
183 schema = json.loads(raw)
184 except ValueError as exc:
185 raise PolicyDiffError(f"{where} schema {collection} cannot be read: {exc}") from exc
186 fields = schema.get("fields", []) if isinstance(schema, Mapping) else []
187 if not isinstance(fields, list):
188 continue
189 for field in fields:
190 if not isinstance(field, Mapping) or not isinstance(field.get("name"), str):
191 continue
192 permissions = field.get("permissions")
193 if permissions is None:
194 result[(collection, field["name"])] = None
195 continue
196 try:
197 entries, default = object_field_permissions._permission_entries(
198 permissions, field_name=field["name"]
199 )
200 except Exception as exc: # fail closed
201 raise PolicyDiffError(
202 f"{where} schema {collection} field {field['name']}: {exc}"
203 ) from exc
204 by_principal: dict[str, str] = {}
205 for principal, access in entries:
206 held = by_principal.get(principal)
207 if held is None or _ACCESS_RANK[access] < _ACCESS_RANK[held]:
208 by_principal[principal] = access
209 result[(collection, field["name"])] = (by_principal, default)
210 return result
211
212
213# --- the difference -------------------------------------------------------------
214
215
216def compute_policy_diff(
217 current: Mapping[str, Any],
218 snapshot: Mapping[str, Any],
219 current_fields: Mapping[tuple[str, str], Any] | None = None,
220 snapshot_fields: Mapping[tuple[str, str], Any] | None = None,
221) -> dict[str, Any]:
222 """The changes from ``current`` to ``snapshot`` (policy_to_dict shapes)."""
223 changes: list[dict[str, Any]] = []
224
225 if current["access_mode"] != snapshot["access_mode"]:
226 to_mode = snapshot["access_mode"]
227 changes.append(_change(
228 "access_mode",
229 TIGHTENS if to_mode == "role_based" else LOOSENS,
230 f"access mode {current['access_mode']} -> {to_mode}",
231 before=current["access_mode"], after=to_mode,
232 ))
233
234 for role in sorted(set(snapshot["admin_roles"]) - set(current["admin_roles"])):
235 changes.append(_change("admin_role_added", LOOSENS,
236 f"role {role} becomes an admin role (bypasses every rule)",
237 after=role))
238 for role in sorted(set(current["admin_roles"]) - set(snapshot["admin_roles"])):
239 changes.append(_change("admin_role_removed", TIGHTENS,
240 f"role {role} is no longer an admin role", before=role))
241
242 users = sorted(set(current["user_roles"]) | set(snapshot["user_roles"]))
243 for user in users:
244 now = set(current["user_roles"].get(user, ()))
245 then = set(snapshot["user_roles"].get(user, ()))
246 for role in sorted(then - now):
247 changes.append(_change("user_role_added", LOOSENS,
248 f"user {user} gets role {role}", user_id=user, after=role))
249 for role in sorted(now - then):
250 changes.append(_change("user_role_removed", TIGHTENS,
251 f"user {user} loses role {role}", user_id=user, before=role))
252
253 for role in sorted(set(current["roles"]) | set(snapshot["roles"])):
254 before, after = current["roles"].get(role), snapshot["roles"].get(role)
255 if before == after:
256 continue
257 kind = "role_added" if before is None else "role_removed" if after is None else "role_changed"
258 changes.append(_change(kind, NEUTRAL, f"role {role} metadata {kind.split('_')[1]}",
259 before=before, after=after))
260
261 changes.extend(_rule_changes(list(current["rules"]), list(snapshot["rules"])))
262 changes.extend(_field_changes(current_fields or {}, snapshot_fields or {}))
263
264 loosens = [c for c in changes if c["effect"] == LOOSENS]
265 return {
266 "changed": bool(changes),
267 "loosens": bool(loosens),
268 "counts": {
269 LOOSENS: len(loosens),
270 TIGHTENS: sum(1 for c in changes if c["effect"] == TIGHTENS),
271 NEUTRAL: sum(1 for c in changes if c["effect"] == NEUTRAL),
272 },
273 "changes": changes,
274 }
275
276
277def _change(kind: str, effect: str, text: str, **extra: Any) -> dict[str, Any]:
278 return {"kind": kind, "effect": effect, "text": text, **extra}
279
280
281def _canonical(rule: Mapping[str, Any]) -> str:
282 return json.dumps(rule, sort_keys=True, separators=(",", ":"))
283
284
285def _rule_key(rule: Mapping[str, Any]) -> tuple:
286 return (rule["effect"], rule["principal"], rule.get("collection"), rule.get("object_id"))
287
288
289def _rule_changes(current: list[dict[str, Any]], snapshot: list[dict[str, Any]]) -> list[dict[str, Any]]:
290 # Rules present on both sides, matched exactly (as a multiset).
291 remaining_snapshot = [_canonical(r) for r in snapshot]
292 common_current: list[str] = []
293 only_current: list[dict[str, Any]] = []
294 for rule in current:
295 canonical = _canonical(rule)
296 if canonical in remaining_snapshot:
297 remaining_snapshot.remove(canonical)
298 common_current.append(canonical)
299 else:
300 only_current.append(rule)
301 only_snapshot = [json.loads(c) for c in remaining_snapshot]
302
303 changes: list[dict[str, Any]] = []
304 # Same who/what/where on both sides, exactly one each: a changed rule.
305 paired: set[int] = set()
306 for i, before in enumerate(only_current):
307 same_current = [r for r in only_current if _rule_key(r) == _rule_key(before)]
308 same_snapshot = [j for j, r in enumerate(only_snapshot) if _rule_key(r) == _rule_key(before)]
309 if len(same_current) == 1 and len(same_snapshot) == 1:
310 after = only_snapshot[same_snapshot[0]]
311 paired.add(same_snapshot[0])
312 effect = _rule_change_effect(before, after)
313 changes.append(_change(
314 "rule_changed", effect,
315 f"{describe_rule(before)} -> {describe_rule(after)}",
316 before=before, after=after,
317 ))
318 else:
319 changes.append(_change(
320 "rule_removed", LOOSENS if before["effect"] == "deny" else TIGHTENS,
321 describe_rule(before), before=before,
322 ))
323 for j, after in enumerate(only_snapshot):
324 if j in paired:
325 continue
326 changes.append(_change(
327 "rule_added", LOOSENS if after["effect"] == "allow" else TIGHTENS,
328 describe_rule(after), after=after,
329 ))
330
331 # The rules kept on both sides, in a different order: the engine takes
332 # the first allow that matches, so order can decide which row filter
333 # applies.
334 snapshot_common_order = [
335 c for c in (_canonical(r) for r in snapshot) if c in common_current
336 ]
337 if _dedupe_order(common_current) != _dedupe_order(snapshot_common_order):
338 changes.append(_change("rules_reordered", LOOSENS,
339 "rules kept on both sides are in a different order"))
340 return changes
341
342
343def _dedupe_order(items: Iterable[str]) -> list[str]:
344 seen: list[str] = []
345 for item in items:
346 if item not in seen:
347 seen.append(item)
348 return seen
349
350
351def _rule_change_effect(before: Mapping[str, Any], after: Mapping[str, Any]) -> str:
352 """What changing ``before`` into ``after`` does; LOOSENS unless provably not."""
353 differs = {k for k in set(before) | set(after) if before.get(k) != after.get(k)}
354 if differs <= {"reason", "package"}:
355 return NEUTRAL
356 actions_before, actions_after = set(before["actions"]), set(after["actions"])
357 if before["effect"] == "allow":
358 loosens = (
359 not _actions_within(actions_after, actions_before)
360 or before.get("row_filter") != after.get("row_filter")
361 or before.get("valid_from") != after.get("valid_from")
362 or before.get("expires_at") != after.get("expires_at")
363 or (bool(after.get("on_behalf")) and not bool(before.get("on_behalf")))
364 or not _fields_within(after.get("fields"), before.get("fields"))
365 or not set(before.get("denied_fields", ())) <= set(after.get("denied_fields", ()))
366 )
367 else:
368 loosens = (
369 not _actions_within(actions_before, actions_after)
370 or before.get("row_filter") != after.get("row_filter")
371 or before.get("valid_from") != after.get("valid_from")
372 or before.get("expires_at") != after.get("expires_at")
373 )
374 return LOOSENS if loosens else TIGHTENS
375
376
377def _actions_within(inner: set[str], outer: set[str]) -> bool:
378 return "*" in outer or ("*" not in inner and inner <= outer)
379
380
381def _fields_within(inner: Any, outer: Any) -> bool:
382 if outer is None: # all fields
383 return True
384 if inner is None:
385 return False
386 return set(inner) <= set(outer)
387
388
389def _field_changes(
390 current: Mapping[tuple[str, str], Any],
391 snapshot: Mapping[tuple[str, str], Any],
392) -> list[dict[str, Any]]:
393 changes: list[dict[str, Any]] = []
394 for key in sorted(set(current) | set(snapshot)):
395 before, after = current.get(key), snapshot.get(key)
396 if before == after:
397 continue
398 principals = set()
399 for side in (before, after):
400 if side is not None:
401 principals.update(side[0])
402 loosens = any(
403 _ACCESS_RANK[_effective(after, p)] > _ACCESS_RANK[_effective(before, p)]
404 for p in [*sorted(principals), None]
405 )
406 collection, field = key
407 changes.append(_change(
408 "field_permissions", LOOSENS if loosens else TIGHTENS,
409 f"field {collection}.{field}: {_describe_field(before)} -> {_describe_field(after)}",
410 collection=collection, field=field,
411 before=_field_payload(before), after=_field_payload(after),
412 ))
413 return changes
414
415
416def _effective(side: Any, principal: str | None) -> str:
417 if side is None:
418 return _UNCONSTRAINED
419 entries, default = side
420 if principal is not None and principal in entries:
421 return entries[principal]
422 if default is not None:
423 return default
424 return _UNCONSTRAINED
425
426
427def _describe_field(side: Any) -> str:
428 if side is None:
429 return "unrestricted"
430 entries, default = side
431 parts = [f"{p}={a}" for p, a in sorted(entries.items())]
432 if default is not None:
433 parts.append(f"default={default}")
434 return ", ".join(parts) or "unrestricted"
435
436
437def _field_payload(side: Any) -> dict[str, Any] | None:
438 if side is None:
439 return None
440 entries, default = side
441 return {"principals": dict(sorted(entries.items())), "default": default}
442
443
444def describe_rule(rule: Mapping[str, Any]) -> str:
445 """One readable line for a rule_to_dict rule."""
446 where = (
447 f"collection {rule['collection']}" if rule.get("collection")
448 else f"object {rule['object_id']}" if rule.get("object_id")
449 else "EVERY object and collection"
450 )
451 if rule.get("collection") and rule.get("object_id"):
452 where = f"collection {rule['collection']} object {rule['object_id']}"
453 text = f"{rule['effect']} {rule['principal']} {','.join(rule['actions']) or 'nothing'} on {where}"
454 extras = []
455 if rule.get("row_filter"):
456 extras.append(f"rows {json.dumps(rule['row_filter'], sort_keys=True)}")
457 if rule.get("fields") is not None:
458 extras.append(f"fields {','.join(rule['fields'])}")
459 if rule.get("denied_fields"):
460 extras.append(f"not fields {','.join(rule['denied_fields'])}")
461 if rule.get("valid_from"):
462 extras.append(f"from {rule['valid_from']}")
463 if rule.get("expires_at"):
464 extras.append(f"until {rule['expires_at']}")
465 if rule.get("on_behalf"):
466 extras.append("on behalf of others")
467 if rule.get("package"):
468 extras.append(f"package {rule['package']}")
469 return text + (f" ({'; '.join(extras)})" if extras else "")
470
471
472# --- confirming what was seen ---------------------------------------------------
473
474
475def policy_diff_hash(diff: Mapping[str, Any], **binding: Any) -> str:
476 """A digest of a difference (and what it is about), for a two-step apply.
477
478 The operator previews, sees the difference, and sends back this digest;
479 the apply recomputes it and refuses on any mismatch, so what is applied
480 is what was seen.
481 """
482 payload = json.dumps(
483 {"binding": binding, "changes": diff.get("changes", [])},
484 sort_keys=True, separators=(",", ":"), default=str,
485 )
486 return "sha256:" + hashlib.sha256(payload.encode("utf-8")).hexdigest()
487
488
489def format_policy_diff(diff: Mapping[str, Any]) -> str:
490 """The difference as text for a terminal, loosening first and marked."""
491 findings = _format_findings(diff.get("findings") or [])
492 if not diff.get("changed"):
493 return "\n".join(["Policy difference: none (the restore does not change who may do what)."]
494 + findings)
495 counts = diff["counts"]
496 lines = [
497 "Policy difference (now -> after the restore): "
498 f"{counts[LOOSENS]} loosen, {counts[TIGHTENS]} tighten, {counts[NEUTRAL]} other.",
499 ]
500 if diff.get("loosens"):
501 lines.append("WARNING: this restore LOOSENS permissions: someone may do something "
502 "they may not do now.")
503 marks = {"rule_added": "+", "rule_removed": "-", "rule_changed": "~"}
504 for effect, title in ((LOOSENS, "Loosens"), (TIGHTENS, "Tightens"), (NEUTRAL, "Other")):
505 items = [c for c in diff["changes"] if c["effect"] == effect]
506 if not items:
507 continue
508 lines.append(f"{title}:")
509 for change in items:
510 mark = marks.get(change["kind"], "*")
511 label = change["kind"].replace("_", " ")
512 lines.append(f" {mark} [{label}] {change['text']}")
513 return "\n".join(lines + findings)
514
515
516def _format_findings(findings: Sequence[Mapping[str, Any]]) -> list[str]:
517 if not findings:
518 return []
519 lines = [f"The restored policy file has {len(findings)} DRON mistake(s) the engine reads "
520 "loosely (a save would refuse them; the restore keeps them as written):"]
521 for finding in findings:
522 mark = "!" if finding.get("serious") else "*"
523 lines.append(f" {mark} {object_permissions.finding_text(finding)}")
524 return lines