awscope 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
awscope/graph.py ADDED
@@ -0,0 +1,570 @@
1
+ """ScopeGraph: scopes, memberships and consented cross-scope links.
2
+
3
+ Two modes:
4
+
5
+ ScopeGraph() in memory (tests, embedding)
6
+ ScopeGraph("scopes.json") a JSON file, written atomically (temp + os.replace)
7
+ under an advisory lock file, re-read before every
8
+ mutation so two CLIs never lose each other's writes
9
+
10
+ `check` is FAIL-CLOSED: every path that is not an explicit allow is a deny with
11
+ the cause named, including an exception raised mid-evaluation.
12
+
13
+ TRUST BOUNDARY: every mutation takes an `actor` (`granted_by` / `by` on links)
14
+ and authorizes it against the graph -- but awscope cannot know who is calling.
15
+ The actor is a string the HOST asserts. The embedding service must authenticate
16
+ the caller and pass the authenticated identity, never a value from a request
17
+ body; awscope then decides whether that identity may make the change.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import contextlib
22
+ import json
23
+ import math
24
+ import os
25
+ import tempfile
26
+ import time
27
+ import uuid
28
+ from typing import Callable, Dict, Iterator, List, Optional, Tuple
29
+
30
+ from .model import (
31
+ ADMIN_ROLES,
32
+ ALLOWED_PARENTS,
33
+ COMPANY_KINDS,
34
+ KINDS,
35
+ ROLES,
36
+ ConsentLink,
37
+ Decision,
38
+ Membership,
39
+ RefusedError,
40
+ Scope,
41
+ StoreError,
42
+ capability_covers,
43
+ realm_of_root,
44
+ valid_capability,
45
+ valid_id,
46
+ )
47
+
48
+ SCHEMA = "awscope/1"
49
+ _LOCK_TIMEOUT_S = 10.0
50
+
51
+
52
+ def _try_lock(f) -> None:
53
+ """Non-blocking exclusive OS lock on an open file. Raises OSError if held.
54
+
55
+ An OS lock dies with its process, so there is no "stale" lock to steal and
56
+ no window in which two waiters both decide the holder is gone.
57
+ """
58
+ if os.name == "nt":
59
+ import msvcrt
60
+ f.seek(0)
61
+ msvcrt.locking(f.fileno(), msvcrt.LK_NBLCK, 1)
62
+ else:
63
+ import fcntl
64
+ fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
65
+
66
+
67
+ def _unlock(f) -> None:
68
+ if os.name == "nt":
69
+ import msvcrt
70
+ f.seek(0)
71
+ msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 1)
72
+ else:
73
+ import fcntl
74
+ fcntl.flock(f.fileno(), fcntl.LOCK_UN)
75
+
76
+
77
+ def _finite(v: Optional[float]) -> bool:
78
+ return v is None or (isinstance(v, (int, float)) and math.isfinite(v))
79
+
80
+
81
+ class ScopeGraph:
82
+ def __init__(self, path: Optional[str] = None, *,
83
+ clock: Callable[[], float] = time.time, lock: bool = True) -> None:
84
+ self.path = path
85
+ self.clock = clock
86
+ self.lock = lock
87
+ self.scopes: Dict[str, Scope] = {}
88
+ self.members: List[Membership] = []
89
+ self.links: Dict[str, ConsentLink] = {}
90
+ if path is not None and os.path.exists(path):
91
+ self._load()
92
+
93
+ # ── persistence ────────────────────────────────────────────────────────
94
+
95
+ def to_dict(self) -> dict:
96
+ return {"schema": SCHEMA,
97
+ "scopes": [s.to_dict() for s in self.scopes.values()],
98
+ "members": [m.to_dict() for m in self.members],
99
+ "links": [lk.to_dict() for lk in self.links.values()]}
100
+
101
+ def _load(self) -> None:
102
+ assert self.path is not None
103
+ try:
104
+ with open(self.path, encoding="utf-8") as f:
105
+ data = json.load(f)
106
+ except (OSError, ValueError) as exc:
107
+ raise StoreError(f"cannot read store {self.path}: {exc}") from exc
108
+ self._replace_from(data)
109
+
110
+ def _replace_from(self, data: dict) -> None:
111
+ if not isinstance(data, dict) or data.get("schema") != SCHEMA:
112
+ got = data.get("schema") if isinstance(data, dict) else type(data).__name__
113
+ raise StoreError(f"store schema is {got!r}, expected {SCHEMA!r}")
114
+ try:
115
+ scopes = {d["id"]: Scope.from_dict(d) for d in data.get("scopes") or []}
116
+ members = [Membership.from_dict(d) for d in data.get("members") or []]
117
+ links = {d["id"]: ConsentLink.from_dict(d) for d in data.get("links") or []}
118
+ except (KeyError, TypeError, ValueError) as exc:
119
+ raise StoreError(f"malformed store record: {type(exc).__name__}: {exc}") from exc
120
+ problems = validate(scopes, members, links)
121
+ if problems:
122
+ # A hand-edited store with a cycle or an orphan is not "mostly fine":
123
+ # every ancestor walk over it is suspect, so nothing is answered.
124
+ raise StoreError("store is inconsistent: " + "; ".join(problems))
125
+ self.scopes, self.members, self.links = scopes, members, links
126
+
127
+ def _save(self) -> None:
128
+ if self.path is None:
129
+ return
130
+ d = os.path.dirname(os.path.abspath(self.path)) or "."
131
+ os.makedirs(d, exist_ok=True)
132
+ fd, tmp = tempfile.mkstemp(prefix=".awscope-", suffix=".tmp", dir=d)
133
+ try:
134
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as f:
135
+ json.dump(self.to_dict(), f, indent=2, sort_keys=True)
136
+ f.write("\n")
137
+ f.flush()
138
+ os.fsync(f.fileno())
139
+ os.replace(tmp, self.path)
140
+ except BaseException:
141
+ with contextlib.suppress(OSError):
142
+ os.unlink(tmp)
143
+ raise
144
+
145
+ @contextlib.contextmanager
146
+ def _locked(self) -> Iterator[None]:
147
+ if self.path is None or not self.lock:
148
+ yield
149
+ return
150
+ # The lock file is permanent and never unlinked: the OS lock on it is the
151
+ # mutex. Deleting a lock file is what lets a second holder in.
152
+ lock_path = self.path + ".lock"
153
+ os.makedirs(os.path.dirname(os.path.abspath(lock_path)) or ".", exist_ok=True)
154
+ deadline = time.monotonic() + _LOCK_TIMEOUT_S
155
+ with open(lock_path, "a+b") as f:
156
+ while True:
157
+ try:
158
+ _try_lock(f)
159
+ break
160
+ except OSError:
161
+ if time.monotonic() > deadline:
162
+ raise StoreError(f"store is locked: {lock_path} "
163
+ f"(held > {_LOCK_TIMEOUT_S:.0f}s)") from None
164
+ time.sleep(0.05)
165
+ try:
166
+ yield
167
+ finally:
168
+ with contextlib.suppress(OSError):
169
+ _unlock(f)
170
+
171
+ @contextlib.contextmanager
172
+ def _mutation(self) -> Iterator[None]:
173
+ """Lock, re-read, mutate, save. On any exception the in-memory graph is
174
+ restored, so a refused operation never leaves a half-applied change."""
175
+ with self._locked():
176
+ if self.path is not None and os.path.exists(self.path):
177
+ self._load()
178
+ snapshot = self.to_dict()
179
+ try:
180
+ yield
181
+ except BaseException:
182
+ self._replace_from(snapshot)
183
+ raise
184
+ self._save()
185
+
186
+ # ── reads ──────────────────────────────────────────────────────────────
187
+
188
+ def get(self, scope_id: str) -> Scope:
189
+ s = self.scopes.get(scope_id)
190
+ if s is None:
191
+ raise RefusedError(f"unknown scope {scope_id!r}")
192
+ return s
193
+
194
+ def ancestors(self, scope_id: str) -> List[str]:
195
+ """Parent first, root last. Bounded, so a corrupted in-memory graph cannot loop."""
196
+ out: List[str] = []
197
+ cur = self.get(scope_id).parent_id
198
+ while cur is not None:
199
+ if cur in out or cur == scope_id or len(out) > len(self.scopes):
200
+ raise StoreError(f"parent cycle through {cur!r}")
201
+ out.append(cur)
202
+ cur = self.get(cur).parent_id
203
+ return out
204
+
205
+ def descendants(self, scope_id: str) -> List[str]:
206
+ self.get(scope_id)
207
+ children: Dict[str, List[str]] = {}
208
+ for s in self.scopes.values():
209
+ if s.parent_id is not None:
210
+ children.setdefault(s.parent_id, []).append(s.id)
211
+ out: List[str] = []
212
+ stack = sorted(children.get(scope_id, []), reverse=True)
213
+ while stack:
214
+ cur = stack.pop()
215
+ if cur in out:
216
+ continue
217
+ out.append(cur)
218
+ stack.extend(sorted(children.get(cur, []), reverse=True))
219
+ return out
220
+
221
+ def scope_path(self, scope_id: str) -> str:
222
+ """`org:acme/team:eng` -- root first. Usable as an awbac permission prefix."""
223
+ chain = [scope_id] + self.ancestors(scope_id)
224
+ return "/".join(f"{self.scopes[i].kind}:{i}" for i in reversed(chain))
225
+
226
+ def roles_of(self, subject: str, scope_id: str) -> List[str]:
227
+ return sorted({m.role for m in self.members
228
+ if m.subject == subject and m.scope_id == scope_id})
229
+
230
+ def scopes_of(self, subject: str) -> List[Tuple[str, str]]:
231
+ """(scope_id, role) for every DIRECT membership."""
232
+ return sorted((m.scope_id, m.role) for m in self.members if m.subject == subject)
233
+
234
+ def administers(self, subject: str, scope_id: str) -> Optional[str]:
235
+ """The scope through which `subject` is owner/admin of `scope_id`
236
+ (itself or an ancestor), or None."""
237
+ if scope_id not in self.scopes:
238
+ return None
239
+ for sid in [scope_id] + self.ancestors(scope_id):
240
+ if any(r in ADMIN_ROLES for r in self.roles_of(subject, sid)):
241
+ return sid
242
+ return None
243
+
244
+ def links_for(self, scope_id: str, *, include_inactive: bool = False) -> List[ConsentLink]:
245
+ """Every link where `scope_id` is the source or the target."""
246
+ now = self.clock()
247
+ out = [lk for lk in self.links.values()
248
+ if scope_id in (lk.source_scope, lk.target_scope)
249
+ and (include_inactive or lk.state(now) == "active")]
250
+ return sorted(out, key=lambda lk: (lk.created_at, lk.id))
251
+
252
+ # ── the decision ───────────────────────────────────────────────────────
253
+
254
+ def check(self, subject: str, acting_scope: str, capability: str,
255
+ target_scope: str) -> Decision:
256
+ """May `subject`, acting from `acting_scope`, use `capability` on
257
+ `target_scope`'s data? Fail-closed: any exception is a denial."""
258
+ try:
259
+ return self._check(subject, acting_scope, capability, target_scope)
260
+ except Exception as exc: # noqa: BLE001 - a raise must never read as an allow
261
+ return Decision(False, f"denied: evaluation failed ({type(exc).__name__}: {exc})")
262
+
263
+ def _check(self, subject: str, acting: str, capability: str, target: str) -> Decision:
264
+ if not subject:
265
+ return Decision(False, "denied: anonymous subject")
266
+ if not valid_capability(capability) or capability.endswith(".*"):
267
+ return Decision(False, f"denied: {capability!r} is not a concrete capability")
268
+ for label, sid in (("target", target), ("acting", acting)):
269
+ if sid not in self.scopes:
270
+ return Decision(False, f"denied: unknown {label} scope {sid!r}")
271
+
272
+ if self.roles_of(subject, target):
273
+ return Decision(True, f"{subject} is a member of {target}", via=f"member:{target}")
274
+ for anc in self.ancestors(target):
275
+ if any(r in ADMIN_ROLES for r in self.roles_of(subject, anc)):
276
+ return Decision(True, f"{subject} administers {anc}, an ancestor of {target}",
277
+ via=f"admin:{anc}")
278
+
279
+ if not self.roles_of(subject, acting):
280
+ return Decision(False, f"denied: {subject} is a member of neither {target} "
281
+ f"nor the acting scope {acting}")
282
+ now = self.clock()
283
+ seen_inactive = []
284
+ for lk in self.links.values():
285
+ if lk.source_scope != target or lk.target_scope != acting:
286
+ continue
287
+ if not any(capability_covers(g, capability) for g in lk.grants):
288
+ continue
289
+ state = lk.state(now)
290
+ if state != "active":
291
+ seen_inactive.append(f"{lk.id} ({state})")
292
+ continue
293
+ if self.administers(lk.granted_by, target) is None:
294
+ # Belt and braces with offboarding: a link outlives nothing its
295
+ # granter no longer has the authority to give.
296
+ seen_inactive.append(
297
+ f"{lk.id} (granter {lk.granted_by} no longer administers {target})")
298
+ continue
299
+ return Decision(True, f"{subject} acts from {acting}; link {lk.id} from {target} "
300
+ f"grants {capability}", via=f"link:{lk.id}")
301
+ if seen_inactive:
302
+ return Decision(False, f"denied: the only link(s) granting {capability} from "
303
+ f"{target} to {acting} are not usable: "
304
+ f"{', '.join(seen_inactive)}")
305
+ return Decision(False, f"denied: no consent link from {target} to {acting} "
306
+ f"grants {capability}")
307
+
308
+ # ── mutations ──────────────────────────────────────────────────────────
309
+
310
+ def _require_admin(self, actor: str, scope_id: str, doing: str) -> str:
311
+ via = self.administers(actor, scope_id) if actor else None
312
+ if via is None:
313
+ raise RefusedError(f"{actor or '<anonymous>'} is not an owner/admin of "
314
+ f"{scope_id} (or an ancestor); may not {doing}")
315
+ return via
316
+
317
+ def _owns(self, actor: str, scope_id: str) -> bool:
318
+ return any("owner" in self.roles_of(actor, sid)
319
+ for sid in [scope_id] + self.ancestors(scope_id))
320
+
321
+ def _realm_for(self, kind: str, parent_id: Optional[str]) -> str:
322
+ return realm_of_root(kind) if parent_id is None else self.get(parent_id).realm
323
+
324
+ def create_scope(self, scope_id: str, kind: str, name: Optional[str] = None,
325
+ parent_id: Optional[str] = None,
326
+ attrs: Optional[dict] = None, *, actor: str) -> Scope:
327
+ """Create a scope. A top-level scope makes `actor` its owner; a child
328
+ scope needs `actor` to administer the parent."""
329
+ with self._mutation():
330
+ if not actor:
331
+ raise RefusedError("actor is empty")
332
+ if not valid_id(scope_id):
333
+ raise RefusedError(f"invalid scope id {scope_id!r} "
334
+ "(lowercase, digits, . _ -; no ':' or '/')")
335
+ if scope_id in self.scopes:
336
+ raise RefusedError(f"scope {scope_id!r} already exists")
337
+ if kind not in KINDS:
338
+ raise RefusedError(f"unknown kind {kind!r}; one of {', '.join(KINDS)}")
339
+ self._check_parent(kind, parent_id)
340
+ if parent_id is not None:
341
+ self._require_admin(actor, parent_id, f"create {scope_id} under it")
342
+ s = Scope(scope_id, kind, name or scope_id, parent_id, dict(attrs or {}),
343
+ realm=self._realm_for(kind, parent_id))
344
+ self.scopes[scope_id] = s
345
+ if parent_id is None:
346
+ self.members.append(Membership(actor, scope_id, "owner"))
347
+ return s
348
+
349
+ def move_scope(self, scope_id: str, new_parent_id: Optional[str], *, actor: str) -> Scope:
350
+ """Re-parent a scope. `actor` must administer the old parent (the scope
351
+ itself if it is top-level) and the new one. Refuses a cycle, and refuses
352
+ any move that changes the scope's realm: personal data never moves under
353
+ an org, and company data never moves into a personal scope."""
354
+ with self._mutation():
355
+ s = self.get(scope_id)
356
+ self._check_parent(s.kind, new_parent_id)
357
+ if new_parent_id is not None and (
358
+ new_parent_id == scope_id or new_parent_id in self.descendants(scope_id)):
359
+ raise RefusedError(
360
+ f"moving {scope_id} under {new_parent_id} would create a parent cycle")
361
+ new_realm = self._realm_for(s.kind, new_parent_id)
362
+ if new_realm != s.realm:
363
+ raise RefusedError(
364
+ f"moving {scope_id} under {new_parent_id or 'top-level'} would take it "
365
+ f"from the {s.realm} realm to the {new_realm} realm; a scope never "
366
+ f"changes sides (create a new one and share it with a consent link)")
367
+ self._require_admin(actor, s.parent_id or scope_id, f"move {scope_id} out of it")
368
+ if new_parent_id is not None:
369
+ self._require_admin(actor, new_parent_id, f"move {scope_id} into it")
370
+ s.parent_id = new_parent_id
371
+ return s
372
+
373
+ def _check_parent(self, kind: str, parent_id: Optional[str]) -> None:
374
+ allowed = ALLOWED_PARENTS[kind]
375
+ if parent_id is None:
376
+ if None not in allowed:
377
+ raise RefusedError(f"a {kind} scope needs a parent of kind "
378
+ f"{' or '.join(k for k in allowed if k)}")
379
+ return
380
+ parent = self.get(parent_id)
381
+ if parent.kind not in allowed:
382
+ if allowed == (None,):
383
+ raise RefusedError(f"a {kind} scope is top-level only -- personal scopes "
384
+ f"are never filed under another scope, so no org can "
385
+ f"offboard them")
386
+ raise RefusedError(f"a {kind} scope cannot sit under a {parent.kind} "
387
+ f"(allowed: {', '.join(k or 'top-level' for k in allowed)})")
388
+
389
+ def add_member(self, subject: str, scope_id: str, role: str, *, actor: str) -> Membership:
390
+ """Add or change a membership. `actor` must administer `scope_id`; only
391
+ an owner may make, or change, an owner."""
392
+ with self._mutation():
393
+ if not subject:
394
+ raise RefusedError("subject is empty")
395
+ if role not in ROLES:
396
+ raise RefusedError(f"unknown role {role!r}; one of {', '.join(ROLES)}")
397
+ self.get(scope_id)
398
+ self._require_admin(actor, scope_id, f"add members to {scope_id}")
399
+ if (role == "owner" or "owner" in self.roles_of(subject, scope_id)) \
400
+ and not self._owns(actor, scope_id):
401
+ raise RefusedError(f"{actor} is not an owner of {scope_id}; only an owner "
402
+ f"may make or change an owner")
403
+ self.members = [m for m in self.members
404
+ if not (m.subject == subject and m.scope_id == scope_id)]
405
+ m = Membership(subject, scope_id, role)
406
+ self.members.append(m)
407
+ return m
408
+
409
+ def remove_member(self, subject: str, scope_id: str, *, actor: str) -> dict:
410
+ """Remove `subject` from `scope_id`. `actor` is the subject leaving, or
411
+ an owner/admin of `scope_id`.
412
+
413
+ Removing someone from an org or team also removes their memberships in
414
+ every scope BELOW it -- and nowhere else. Personal scopes sit in the
415
+ personal realm and are never below an org, so they are never touched.
416
+ Then two kinds of link the subject granted are revoked:
417
+
418
+ * links on a scope they no longer administer (their authority is gone);
419
+ * on org/team removal, links INTO the scopes they just left: consent the
420
+ leaver gave their employer (their own calendar shared with the org)
421
+ ends with the membership it was given for.
422
+
423
+ Returns what was removed and revoked.
424
+ """
425
+ with self._mutation():
426
+ s = self.get(scope_id)
427
+ if actor != subject:
428
+ self._require_admin(actor, scope_id, f"remove {subject} from it")
429
+ affected = {scope_id}
430
+ if s.kind in COMPANY_KINDS:
431
+ affected.update(self.descendants(scope_id))
432
+ removed = [m for m in self.members if m.subject == subject and m.scope_id in affected]
433
+ if not removed:
434
+ raise RefusedError(f"{subject} is not a member of {scope_id} or anything below it")
435
+ self.members = [m for m in self.members if m not in removed]
436
+ revoked = self._revoke_orphaned_grants(subject)
437
+ if s.kind in COMPANY_KINDS:
438
+ revoked += self._revoke_inbound_grants(subject, affected, scope_id)
439
+ return {"removed": [m.to_dict() for m in removed], "revoked": sorted(revoked)}
440
+
441
+ def offboard(self, subject: str, org_id: str, *, actor: str) -> dict:
442
+ """Alias for `remove_member` on an org, refusing anything that is not one."""
443
+ if self.get(org_id).kind != "org":
444
+ raise RefusedError(f"{org_id} is a {self.scopes[org_id].kind}, not an org")
445
+ return self.remove_member(subject, org_id, actor=actor)
446
+
447
+ def _revoke_orphaned_grants(self, subject: str) -> List[str]:
448
+ now = self.clock()
449
+ out = []
450
+ for lk in self.links.values():
451
+ if lk.granted_by == subject and lk.state(now) == "active" \
452
+ and self.administers(subject, lk.source_scope) is None:
453
+ lk.revoked_at, lk.revoked_by = now, "awscope"
454
+ lk.revoke_reason = f"granter {subject} no longer administers {lk.source_scope}"
455
+ out.append(lk.id)
456
+ return out
457
+
458
+ def _revoke_inbound_grants(self, subject: str, affected: set, left: str) -> List[str]:
459
+ now = self.clock()
460
+ out = []
461
+ for lk in self.links.values():
462
+ if lk.granted_by == subject and lk.target_scope in affected \
463
+ and lk.state(now) == "active":
464
+ lk.revoked_at, lk.revoked_by = now, "awscope"
465
+ lk.revoke_reason = f"granter {subject} left {left}"
466
+ out.append(lk.id)
467
+ return out
468
+
469
+ def grant_link(self, source_scope: str, target_scope: str, grants: List[str],
470
+ granted_by: str, *, expires_at: Optional[float] = None,
471
+ ttl_s: Optional[float] = None, link_id: Optional[str] = None) -> ConsentLink:
472
+ """`granted_by` is the actor and must administer `source_scope`. It is
473
+ host-asserted: authenticate it before it gets here."""
474
+ with self._mutation():
475
+ self.get(source_scope)
476
+ self.get(target_scope)
477
+ if source_scope == target_scope:
478
+ raise RefusedError(
479
+ "a link from a scope to itself grants nothing membership does not")
480
+ grants = list(dict.fromkeys(grants or []))
481
+ if not grants:
482
+ raise RefusedError("a link must grant at least one capability")
483
+ bad = [g for g in grants if not valid_capability(g)]
484
+ if bad:
485
+ raise RefusedError(
486
+ f"invalid capability {bad[0]!r} (dotted lowercase, e.g. calendar.read)")
487
+ if not granted_by or self.administers(granted_by, source_scope) is None:
488
+ raise RefusedError(f"{granted_by or '<anonymous>'} is not an owner/admin of "
489
+ f"{source_scope}; only the source scope can consent")
490
+ # NaN compares False to everything: `expires_at <= now` would let it
491
+ # through and `now >= expires_at` would keep the link active forever.
492
+ if not _finite(ttl_s) or not _finite(expires_at):
493
+ raise RefusedError("ttl_s / expires_at must be finite numbers")
494
+ now = self.clock()
495
+ if ttl_s is not None:
496
+ if expires_at is not None:
497
+ raise RefusedError("give expires_at or ttl_s, not both")
498
+ expires_at = now + float(ttl_s)
499
+ if expires_at is not None and expires_at <= now:
500
+ raise RefusedError("expires_at is not in the future")
501
+ lid = link_id or f"lnk-{uuid.uuid4().hex[:12]}"
502
+ if not valid_id(lid) or lid in self.links:
503
+ raise RefusedError(f"link id {lid!r} is invalid or taken")
504
+ lk = ConsentLink(lid, source_scope, target_scope, grants, granted_by, now, expires_at)
505
+ self.links[lid] = lk
506
+ return lk
507
+
508
+ def revoke_link(self, link_id: str, by: str, reason: str = "") -> ConsentLink:
509
+ """The granter, or any owner/admin of either end, may revoke. The target
510
+ side can always decline what it was given. `by` is host-asserted."""
511
+ with self._mutation():
512
+ lk = self.links.get(link_id)
513
+ if lk is None:
514
+ raise RefusedError(f"unknown link {link_id!r}")
515
+ if lk.revoked_at is not None:
516
+ raise RefusedError(f"link {link_id} is already revoked")
517
+ if not by or not (by == lk.granted_by or self.administers(by, lk.source_scope)
518
+ or self.administers(by, lk.target_scope)):
519
+ raise RefusedError(f"{by or '<anonymous>'} may not revoke {link_id}")
520
+ lk.revoked_at, lk.revoked_by, lk.revoke_reason = self.clock(), by, reason or None
521
+ return lk
522
+
523
+
524
+ def validate(scopes: Dict[str, Scope], members: List[Membership],
525
+ links: Dict[str, ConsentLink]) -> List[str]:
526
+ """Every structural invariant, as a list of problems. Pure."""
527
+ out: List[str] = []
528
+ for s in scopes.values():
529
+ if s.kind not in KINDS:
530
+ out.append(f"{s.id}: unknown kind {s.kind!r}")
531
+ continue
532
+ if not valid_id(s.id):
533
+ out.append(f"{s.id!r}: invalid id")
534
+ if s.parent_id is not None and s.parent_id not in scopes:
535
+ out.append(f"{s.id}: parent {s.parent_id!r} does not exist")
536
+ elif s.parent_id is None and None not in ALLOWED_PARENTS[s.kind]:
537
+ out.append(f"{s.id}: a {s.kind} needs a parent")
538
+ elif s.parent_id is not None and scopes[s.parent_id].kind not in ALLOWED_PARENTS[s.kind]:
539
+ out.append(f"{s.id}: a {s.kind} cannot sit under {scopes[s.parent_id].kind}")
540
+ seen = {s.id}
541
+ cur, root = s.parent_id, s
542
+ while cur is not None and cur in scopes:
543
+ if cur in seen:
544
+ out.append(f"{s.id}: parent cycle through {cur}")
545
+ root = None
546
+ break
547
+ seen.add(cur)
548
+ root = scopes[cur]
549
+ cur = root.parent_id
550
+ if root is not None and cur is None and s.realm != realm_of_root(root.kind):
551
+ # A recorded realm that disagrees with where the scope now sits means
552
+ # it was moved across the personal/company line by hand.
553
+ out.append(f"{s.id}: realm is {s.realm!r} but it sits under "
554
+ f"{root.kind}:{root.id} ({realm_of_root(root.kind)})")
555
+ for m in members:
556
+ if m.scope_id not in scopes:
557
+ out.append(f"membership of {m.subject} in unknown scope {m.scope_id}")
558
+ if m.role not in ROLES:
559
+ out.append(f"membership of {m.subject} in {m.scope_id}: unknown role {m.role!r}")
560
+ for lk in links.values():
561
+ for end in (lk.source_scope, lk.target_scope):
562
+ if end not in scopes:
563
+ out.append(f"link {lk.id}: unknown scope {end}")
564
+ if not lk.grants or not all(valid_capability(g) for g in lk.grants):
565
+ out.append(f"link {lk.id}: invalid grants {lk.grants}")
566
+ for name in ("created_at", "expires_at", "revoked_at"):
567
+ v = getattr(lk, name)
568
+ if not _finite(v) or (name == "created_at" and v is None):
569
+ out.append(f"link {lk.id}: {name} is {v!r}, not a finite time")
570
+ return out