234 lines
10 KiB
Python
234 lines
10 KiB
Python
"""Roles: named bundles of permissions (``authz/catalog.py``).
|
|
|
|
Five are built in, each with a ceiling it can never exceed:
|
|
|
|
========= ========================== =========== ==========
|
|
role holds assignable editable
|
|
========= ========================== =========== ==========
|
|
operator everything (the owner) no no
|
|
admin person + admin tiers not yet yes
|
|
member person tier yes yes
|
|
guest today's guest defaults yes yes
|
|
viewer read what's theirs yes yes
|
|
========= ========================== =========== ==========
|
|
|
|
*Admin* is the hub's administration without the machine (no host-tier
|
|
permission). Nobody in ``users.json`` can hold it yet: most handlers still
|
|
tell the owner from a guest by identity, so it comes with team mode.
|
|
|
|
Custom roles are clones (Settings → Users → Roles → *Clone*), always within the
|
|
person tier. A built-in's edits and every custom role live in ``roles.json``
|
|
(``ROLES_PATH``), a whole-file rewrite like ``users.json``; a built-in nobody
|
|
edited is not stored, so its defaults can improve in code.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import threading
|
|
|
|
from authz import catalog as cat
|
|
|
|
ROLES_PATH = pathlib.Path(os.environ.get("ROLES_PATH", "/data/roles.json"))
|
|
|
|
OPERATOR, ADMIN, MEMBER, GUEST, VIEWER = "operator", "admin", "member", "guest", "viewer"
|
|
DEFAULT_ROLE = GUEST
|
|
|
|
GUEST_DEFAULT = frozenset({
|
|
"whoami", "self", "app.read", "self.claude",
|
|
"conversations.read", "conversations.edit", "conversations.share",
|
|
"runs.start", "runs.scratch.bash", "runs.codemode", "cli.use",
|
|
"inbox.read", "inbox.answer", "projects.read", "files.upload", "cron.own",
|
|
"plugins.use",
|
|
})
|
|
|
|
BUILTIN: dict[str, dict] = {
|
|
OPERATOR: {"name": "Operator", "ceiling": cat.ALL, "perms": cat.ALL,
|
|
"assignable": False, "editable": False,
|
|
"description": "The machine's owner: everything, host-level included."},
|
|
ADMIN: {"name": "Admin", "ceiling": cat.ADMIN_PERMS, "perms": cat.ADMIN_PERMS,
|
|
"assignable": False, "editable": True,
|
|
"description": "Runs the hub — people, settings, every conversation — "
|
|
"but not the machine. Assignable with team mode."},
|
|
MEMBER: {"name": "Member", "ceiling": cat.PERSON_PERMS, "perms": cat.PERSON_PERMS,
|
|
"assignable": True, "editable": True,
|
|
"description": "A teammate: their own conversations and logins, "
|
|
"every person-level feature."},
|
|
GUEST: {"name": "Guest", "ceiling": cat.PERSON_PERMS, "perms": GUEST_DEFAULT,
|
|
"assignable": True, "editable": True,
|
|
"description": "Someone you invited into a few projects."},
|
|
VIEWER: {"name": "Viewer", "ceiling": cat.PERSON_PERMS,
|
|
"perms": frozenset({"whoami", "self", "app.read", "conversations.read",
|
|
"inbox.read", "projects.read"}),
|
|
"assignable": True, "editable": True,
|
|
"description": "Reads what is shared with them; starts nothing."},
|
|
}
|
|
ORDER = (OPERATOR, ADMIN, MEMBER, GUEST, VIEWER)
|
|
_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
|
|
|
|
|
|
def _slug(name: str) -> str:
|
|
s = re.sub(r"[^a-z0-9]+", "-", (name or "").lower()).strip("-")[:32]
|
|
return s or "role"
|
|
|
|
|
|
class RolesStore:
|
|
def __init__(self, path: pathlib.Path = ROLES_PATH):
|
|
self.path = pathlib.Path(path)
|
|
self._lock = threading.RLock()
|
|
self._data = self._load()
|
|
self.version = 0
|
|
|
|
def _load(self) -> dict:
|
|
try:
|
|
raw = json.loads(self.path.read_text())
|
|
except (OSError, ValueError):
|
|
raw = {}
|
|
roles = raw.get("roles") if isinstance(raw, dict) else None
|
|
return {"roles": roles if isinstance(roles, dict) else {}}
|
|
|
|
def _save(self) -> None:
|
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp = self.path.with_suffix(".tmp")
|
|
tmp.write_text(json.dumps(self._data, indent=1, sort_keys=True))
|
|
os.replace(tmp, self.path)
|
|
self.version += 1
|
|
|
|
# ── reads ────────────────────────────────────────────────────────────────
|
|
def get(self, rid: str | None) -> dict | None:
|
|
"""A role as ``{id, name, description, perms (frozenset), builtin,
|
|
assignable, editable, ceiling}``, or None."""
|
|
with self._lock:
|
|
stored = self._data["roles"].get(rid or "")
|
|
if rid in BUILTIN:
|
|
b = BUILTIN[rid]
|
|
perms = b["perms"]
|
|
if stored and b["editable"] and isinstance(stored.get("perms"), list):
|
|
perms = frozenset(stored["perms"])
|
|
return {"id": rid, "name": b["name"],
|
|
"description": (stored or {}).get("description") or b["description"],
|
|
"perms": (perms & b["ceiling"]) | cat.CORE,
|
|
"builtin": True, "assignable": b["assignable"],
|
|
"editable": b["editable"], "ceiling": b["ceiling"],
|
|
"edited": bool(stored)}
|
|
if not stored:
|
|
return None
|
|
return {"id": rid, "name": stored.get("name") or rid,
|
|
"description": stored.get("description") or "",
|
|
"perms": (frozenset(stored.get("perms") or ()) & cat.PERSON_PERMS) | cat.CORE,
|
|
"builtin": False, "assignable": True, "editable": True,
|
|
"ceiling": cat.PERSON_PERMS, "edited": True,
|
|
"from": stored.get("from")}
|
|
|
|
def all(self) -> list[dict]:
|
|
with self._lock:
|
|
custom = sorted((k for k in self._data["roles"] if k not in BUILTIN),
|
|
key=lambda k: (self._data["roles"][k].get("name") or k).lower())
|
|
return [r for r in (self.get(k) for k in (*ORDER, *custom)) if r]
|
|
|
|
def assignable(self, rid: str | None) -> bool:
|
|
r = self.get(rid)
|
|
return bool(r and r["assignable"])
|
|
|
|
def perms(self, rid: str | None) -> frozenset[str]:
|
|
"""A role's permissions; an unknown or unassignable role is the guest's
|
|
(a person never holds admin or operator through a hand-edited file)."""
|
|
r = self.get(rid)
|
|
if not r or not r["assignable"]:
|
|
r = self.get(DEFAULT_ROLE)
|
|
return r["perms"]
|
|
|
|
# ── writes ───────────────────────────────────────────────────────────────
|
|
def update(self, rid: str, *, perms=None, name=None, description=None) -> dict:
|
|
with self._lock:
|
|
r = self.get(rid)
|
|
if not r:
|
|
raise KeyError(rid)
|
|
if not r["editable"]:
|
|
raise ValueError(f"the {r['name']} role can't be changed")
|
|
rec = dict(self._data["roles"].get(rid) or {})
|
|
if perms is not None:
|
|
bad = set(perms) - r["ceiling"] - cat.CORE
|
|
if bad - cat.ALL:
|
|
raise ValueError(f"unknown permissions: {sorted(bad - cat.ALL)}")
|
|
if bad:
|
|
raise ValueError(f"the {r['name']} role can't hold: {sorted(bad)}")
|
|
rec["perms"] = cat.clean(set(perms) | cat.CORE, r["ceiling"] | cat.CORE)
|
|
elif r["builtin"] and "perms" not in rec:
|
|
rec["perms"] = cat.clean(r["perms"])
|
|
if description is not None:
|
|
rec["description"] = " ".join(str(description).split())[:200]
|
|
if name is not None and not r["builtin"]:
|
|
n = " ".join(str(name).split())[:40]
|
|
if not n:
|
|
raise ValueError("a role needs a name")
|
|
rec["name"] = n
|
|
self._data["roles"][rid] = rec
|
|
self._save()
|
|
return self.get(rid)
|
|
|
|
def clone(self, src: str, name: str) -> dict:
|
|
with self._lock:
|
|
r = self.get(src)
|
|
if not r:
|
|
raise KeyError(src)
|
|
n = " ".join(str(name or "").split())[:40]
|
|
if not n:
|
|
raise ValueError("a role needs a name")
|
|
if any(x["name"].lower() == n.lower() for x in self.all()):
|
|
raise ValueError("a role with this name already exists")
|
|
base, rid, i = _slug(n), "", 1
|
|
while not rid or rid in BUILTIN or rid in self._data["roles"]:
|
|
rid = base if i == 1 else f"{base}-{i}"
|
|
i += 1
|
|
if not _ID_RE.match(rid):
|
|
raise ValueError("bad role name")
|
|
self._data["roles"][rid] = {
|
|
"name": n, "description": r["description"] if not r["builtin"] else
|
|
f"Made from {r['name']}.", "from": src,
|
|
"perms": cat.clean(r["perms"], cat.PERSON_PERMS | cat.CORE)}
|
|
self._save()
|
|
return self.get(rid)
|
|
|
|
def reset(self, rid: str) -> dict:
|
|
"""A built-in back to its defaults."""
|
|
with self._lock:
|
|
if rid not in BUILTIN:
|
|
raise ValueError("only a built-in role has defaults")
|
|
self._data["roles"].pop(rid, None)
|
|
self._save()
|
|
return self.get(rid)
|
|
|
|
def delete(self, rid: str) -> None:
|
|
with self._lock:
|
|
if rid in BUILTIN:
|
|
raise ValueError("a built-in role can't be deleted")
|
|
if rid not in self._data["roles"]:
|
|
raise KeyError(rid)
|
|
del self._data["roles"][rid]
|
|
self._save()
|
|
|
|
|
|
_STORE: RolesStore | None = None
|
|
_STORE_LOCK = threading.Lock()
|
|
|
|
|
|
def store() -> RolesStore:
|
|
"""The process's roles store (``ROLES_PATH``)."""
|
|
global _STORE
|
|
with _STORE_LOCK:
|
|
if _STORE is None:
|
|
_STORE = RolesStore()
|
|
return _STORE
|
|
|
|
|
|
def public(r: dict, members: int = 0) -> dict:
|
|
return {"id": r["id"], "name": r["name"], "description": r["description"],
|
|
"perms": cat.clean(r["perms"]), "ceiling": cat.clean(r["ceiling"]),
|
|
"builtin": r["builtin"], "assignable": r["assignable"],
|
|
"editable": r["editable"], "edited": r["edited"],
|
|
"clonedFrom": r.get("from"), "members": members}
|