Files
gabrielvidalandClaude Opus 5.5 c7da0f5008 feat(authz): roles, scoped credentials and one permission table for every route
- authz/catalog.py: 42 named permissions in groups and tiers (person, admin,
  host); authz/roles.py: built-in Operator (the owner), Admin (assignable with
  team mode), Member, Guest, Viewer + custom clones, in roles.json
- a person = role + allow/deny overrides (authz/policy.py); users.json's old
  switches (cli, mcp, createProjects, scratchBash, codeMode,
  computers.enabled) migrate once to exactly what they allowed, backup kept
- authz/scopes.py: what a credential acting for someone keeps (cli,
  worker.read|run, bot, phone) — a scope only narrows
- authz/routes.py: (method, path) -> permission for all 310 /api routes; the
  gate asks Caller.allows() for every caller kind, replacing GUEST_ROUTES,
  CLI_ROUTES and the worker READ/RUN_ROUTES regex lists
- golden route x caller matrix (authz/matrix.golden.txt, test_authz_matrix)
- the claude bot reads the admin app minus people/security/the machine; the
  phone key reads its unread notifications only
- loopback without the host token is logged (loopback_tokenless), refusals
  are perm_denied lines; the hub's own MCP calls send the token
- /api/roles CRUD, /api/me and /api/users carry role/allow/deny/perms
- worker-bound scheduled items and conversation-meta respect the binding

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 17:59:05 +01:00

186 lines
7.5 KiB
Python

"""
Conversation-level access for guests.
A conversation belongs to a guest when its metadata says ``owner: <user id>``
(stamped by the spawn — a conversation without one is the owner's), and is
**shared** with the ids in ``participants``. A guest sees exactly those two
sets; the owner sees everything.
Seeing a conversation is not hearing about it: its pushes, asks and forms
reach its **audience** (:func:`audience`) — whoever started it and the people
it's shared with, plus the owner once they follow a guest's conversation
(writing in it is enough), minus anyone who muted it (``meta.follow``). A conversation id is a UUIDv7
(conversations/ids.py — a root transcript's or a subagent's), a legacy path id
(``<dir>/<sid>.jsonl``, ``<dir>/<sid>/subagents/agent-….jsonl``) or a bare
session id — :func:`session_of` maps them all to the root session whose
metadata decides.
"""
from __future__ import annotations
import pathlib
from fastapi import HTTPException
from conversations import ids
from users.caller import OWNER_ID, Caller
def session_of(conv_id: str) -> str:
# A uid stands for a transcript path: decide on that path. (A bare session
# id is a UUID too, but never one the registry handed out.)
if ids.is_uid(conv_id):
conv_id = ids.REGISTRY.rel(conv_id) or conv_id
parts = pathlib.PurePosixPath(conv_id or "").parts
if "subagents" in parts:
i = parts.index("subagents")
if i > 0:
return parts[i - 1]
name = parts[-1] if parts else ""
return name[:-6] if name.endswith(".jsonl") else name
def unrestricted(caller: Caller) -> bool:
"""Sees every conversation (``conversations.all``: the owner) — unless
narrowed to one profile (an MCP connection bound to a worker,
workers/bound.py)."""
return caller.has("conversations.all") and not caller.profile
def meta_visible(caller: Caller, meta: dict) -> bool:
"""``meta`` is a card's (its ``profile`` resolved, cards.py)."""
if caller.has("conversations.all"):
return not caller.profile or meta.get("profile") == caller.profile
return (meta.get("owner") == caller.id
or caller.id in (meta.get("participants") or ()))
def visible(deps, caller: Caller, conv_id_or_sid: str) -> bool:
if unrestricted(caller):
return True
meta = deps.meta_store.peek(session_of(conv_id_or_sid))
if caller.has("conversations.all"): # narrowed to a profile: the conversation's, resolved
return deps.profile_store.of_meta(meta, meta.get("account")) == caller.profile
return meta_visible(caller, meta)
def ensure_visible(deps, caller: Caller, conv_id_or_sid: str) -> None:
"""404 — not 403 — so a guest can't probe which conversations exist."""
if not visible(deps, caller, conv_id_or_sid):
raise HTTPException(404, "not found")
def ensure_runs_here(deps, caller: Caller, sid: str) -> None:
"""A caller bound to a worker (``caller.via_worker``, workers/bound.py)
acts only on conversations that
live on that worker — the one it launched or mirrored (``meta.worker`` /
``meta.workerSource``). 404 for one it can't see, 403 for one it can."""
if not caller.via_worker:
return
ensure_visible(deps, caller, sid)
m = deps.meta_store.peek(session_of(sid))
if (m.get("worker") or m.get("workerSource")) != caller.via_worker:
raise HTTPException(403, {"message": "this connection only acts on "
"conversations that ran on its worker",
"kind": "worker_elsewhere"})
def project_of(meta: dict) -> str | None:
ps = meta.get("projects") or []
return ps[0] if ps else None
def can_send(deps, caller: Caller, sid: str, *, stop: bool = False) -> bool:
"""May ``caller`` add a turn (or, ``stop``, stop the run) of conversation
``sid``?
The owner always. A participant always — sharing a conversation *is* the
invitation to talk in it. The guest who started it while they still hold
``chat`` on its project (a revoked grant stops them) — or, on one of their
own computers (no project there: users/computers.py), while that computer
is still theirs; one with no project at all (``meta.scratch``) always. A run of one of their scheduled jobs is a report: they
may stop it, not write in it (its « Discuter » starts a conversation of
its own — ``meta.cronChat`` — which they may, while the job is theirs)."""
if caller.is_owner:
return True
meta = deps.meta_store.peek(sid)
if caller.id in (meta.get("participants") or ()):
return True
if meta.get("owner") != caller.id:
return False
if (meta.get("cron") or {}).get("guest"):
return stop
chat = meta.get("cronChat") or {}
if chat.get("id"):
job = deps.cron_store.get(chat["id"])
return bool(job and job.get("owner") == caller.id)
wid = meta.get("worker") or meta.get("workerSource")
w = deps.worker_store.get(wid) if wid else None
if w and w.get("owner") == caller.id:
return True
if meta.get("scratch"):
# Their No project conversation (users/runs.scratch_scope): no grant
# to lose, it is theirs to keep talking in.
return True
return caller.can(project_of(meta), "chat")
def filter_cards(caller: Caller, cards: list[dict]) -> list[dict]:
if unrestricted(caller):
return cards
return [c for c in cards if meta_visible(caller, c.get("meta") or {})]
def owner_of(meta: dict) -> str:
"""Whose conversation this is: a guest's id, else the owner's."""
return meta.get("owner") or OWNER_ID
def audience(meta: dict) -> list[str]:
"""Who hears about this conversation (pushes, asks, forms; the feed).
By default the person who started it and everyone it's shared with. The
owner sees every conversation but only *hears* about a guest's one once
they follow it — ``meta.follow`` (``{user id: bool}``) adds them, and lets
anyone mute a conversation they'd otherwise hear about. A guest can't
follow their way into a conversation they can't see: only the owner's
``True`` adds a name."""
pref = meta.get("follow") or {}
people = [owner_of(meta), *(meta.get("participants") or ())]
if pref.get(OWNER_ID):
people.append(OWNER_ID)
return [u for u in dict.fromkeys(people) if pref.get(u, True)]
def hears(caller: Caller, meta: dict) -> bool:
return caller.id in audience(meta)
def set_follow(deps, sid: str, uid: str, on: bool) -> None:
"""Record ``uid``'s choice to hear (or not) about conversation ``sid``."""
pref = dict(deps.meta_store.peek(sid).get("follow") or {})
pref[uid] = bool(on)
deps.meta_store.update(sid, {"follow": pref})
deps.hub.publish({"type": "meta", "id": sid})
def forget_user(deps, uid: str) -> list[str]:
"""Take a deleted user out of every conversation shared with them
(``participants``, ``follow``), in one save. ``owner`` stays: whose
conversation it was is history, and the id is never reused. Returns the
sessions changed."""
patches = {}
for sid, m in deps.meta_store.items():
ps, pref = m.get("participants") or [], m.get("follow") or {}
if uid in ps or uid in pref:
patches[sid] = {"participants": [p for p in ps if p != uid],
"follow": {k: v for k, v in pref.items() if k != uid}}
if patches:
deps.meta_store.stamp_many(patches)
return list(patches)
def is_shared(meta: dict) -> bool:
"""Several people may write here: the thread labels who said what."""
return bool(meta.get("owner") or meta.get("participants"))