From 9b7c9dba55ffb336adff2c7b4a83e4e55dc079d7 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sat, 10 Oct 2026 20:25:08 +0000 Subject: [PATCH] feat(access): roles with permissions and custom roles per namespace Viewer, editor and owner become sets of permissions (read, edit, import, process, curate, share, publish, remove, members, manage). Admins make custom roles from them (Admin > Roles, /api/v1/roles) and give them per namespace like the built-in ones; routes for importing, processing, curating, sharing, publishing, removing, people and namespace settings check the permission. Existing access is unchanged. Non-admin members managers give only roles they hold all of. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_013CspHV36KRyiRJ9LsFqK53 --- CHANGELOG.md | 5 + docs/access.md | 34 ++ docs/api.md | 6 +- docs/authentication.md | 3 +- fastapi_backend/app/api/deps.py | 24 +- fastapi_backend/app/api/v1/routes/auth.py | 1 + fastapi_backend/app/api/v1/routes/comments.py | 6 +- .../app/api/v1/routes/content_types.py | 2 +- fastapi_backend/app/api/v1/routes/entities.py | 26 +- fastapi_backend/app/api/v1/routes/fields.py | 4 +- fastapi_backend/app/api/v1/routes/files.py | 2 +- fastapi_backend/app/api/v1/routes/graph.py | 2 +- .../app/api/v1/routes/graph_history.py | 2 +- .../app/api/v1/routes/import_hooks.py | 10 +- fastapi_backend/app/api/v1/routes/imports.py | 8 +- fastapi_backend/app/api/v1/routes/jobs.py | 10 +- fastapi_backend/app/api/v1/routes/metadata.py | 4 +- .../app/api/v1/routes/namespaces.py | 10 +- fastapi_backend/app/api/v1/routes/notes.py | 4 +- .../app/api/v1/routes/notifications.py | 14 +- .../app/api/v1/routes/ns_assistant.py | 10 +- .../app/api/v1/routes/pipelines.py | 2 +- fastapi_backend/app/api/v1/routes/podcasts.py | 4 +- fastapi_backend/app/api/v1/routes/rdf.py | 2 +- .../app/api/v1/routes/recordings.py | 46 +-- fastapi_backend/app/api/v1/routes/requests.py | 2 +- fastapi_backend/app/api/v1/routes/routines.py | 6 +- fastapi_backend/app/api/v1/routes/speakers.py | 18 +- fastapi_backend/app/api/v1/routes/topics.py | 14 +- fastapi_backend/app/api/v1/routes/uploads.py | 6 +- fastapi_backend/app/api/v1/routes/users.py | 73 +++- fastapi_backend/app/api/v1/routes/vaults.py | 8 +- fastapi_backend/app/api/v1/routes/video.py | 20 +- .../app/api/v1/routes/workflows.py | 4 +- fastapi_backend/app/domain/access.py | 7 +- fastapi_backend/app/domain/auth.py | 25 +- fastapi_backend/app/domain/ops_tools.py | 10 +- fastapi_backend/app/domain/roles.py | 175 ++++++++ fastapi_backend/app/domain/store.py | 1 + fastapi_backend/app/schemas/auth.py | 5 +- fastapi_backend/app/schemas/users.py | 46 ++- fastapi_backend/tests/api/test_roles.py | 109 +++++ fastapi_backend/tests/api/test_users.py | 2 +- .../app/(app)/admin/roles/page.tsx | 10 + nextjs-frontend/app/openapi-client/index.ts | 23 ++ nextjs-frontend/app/openapi-client/sdk.gen.ts | 80 +++- .../app/openapi-client/types.gen.ts | 238 ++++++++++- .../components/admin/admin-frame.tsx | 16 +- .../components/admin/namespaces.tsx | 13 +- .../components/admin/people-model.ts | 11 +- nextjs-frontend/components/admin/people.tsx | 26 +- nextjs-frontend/components/admin/roles.tsx | 232 +++++++++++ nextjs-frontend/openapi.json | 380 +++++++++++++++++- threat-model.json | 10 +- threat-model.md | 3 +- threat-model.yaml | 12 +- 56 files changed, 1623 insertions(+), 203 deletions(-) create mode 100644 fastapi_backend/app/domain/roles.py create mode 100644 fastapi_backend/tests/api/test_roles.py create mode 100644 nextjs-frontend/app/(app)/admin/roles/page.tsx create mode 100644 nextjs-frontend/components/admin/roles.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 39a6856ad..e5177831a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version ## Unreleased +- **Roles with permissions.** Viewer, editor and owner are now sets of permissions (read, edit, import, process, + curate, share, publish, remove, members, manage), and admins make custom roles from them in Admin → Roles, given per + namespace like the built-in ones. Existing access is unchanged. Someone who manages members but isn't an admin gives + only roles they hold all of ([Access](docs/access.md#roles-and-permissions)). + - **Invite and remove people.** Making an account in Admin → People now emails the sign-in link as an invitation when mail is set up, and the link is still shown to share yourself. **Remove for good** ends every way someone signs in, takes their roles and their private chats, notes and views, and keeps what they shared under their name; their email diff --git a/docs/access.md b/docs/access.md index feb060d1c..3711e204c 100644 --- a/docs/access.md +++ b/docs/access.md @@ -62,6 +62,40 @@ publishes them. Permission doesn't open the workspace: that stays with the names In the matrix, view and edit permission open the same pages; Lens has one permission for both. +## Roles and permissions + +A role in a namespace is a set of **permissions**. Every role reads; the rest are what it may change: + +| Permission | Allows | Built-in roles with it | +|---|---|---| +| `read` | see, search, listen and chat; write your own notes | viewer, editor, owner | +| `edit` | edit transcripts, catalogue records, tags, fields, collections, and notes and comments for everyone | editor, owner | +| `import` | add recordings, documents and images: uploads, imports, RDF | editor, owner | +| `process` | reprocess, run pipelines, workflows, routines and batches | editor, owner | +| `curate` | rename and merge speakers, faces, entities and topics; change the graph | editor, owner | +| `share` | make, list and revoke share links | editor, owner | +| `publish` | set access, open parts and featured; give permission on recordings; answer access requests | owner | +| `remove` | delete recordings and move them to another namespace | owner | +| `members` | give people roles in the namespace | owner | +| `manage` | namespace settings: metadata profile, notifications, import hooks, IP groups, the assistant, vaults | owner | + +**Viewer**, **editor** and **owner** are built in and can't change, so access people already had stays as it was. +Admins make **custom roles** in Admin → Roles (`POST /api/v1/roles` with a name, a label and permissions) and give +them per namespace like the built-in ones: in People's role grid, a namespace's members, or +`PUT /api/v1/namespaces//members`. A change to a custom role holds for everyone with it at once; a role someone +holds can't be deleted. Making, changing and deleting roles is audited as `role.create`, `role.update` and +`role.delete`. + +The permissions above are checked as named. A custom role also counts as the largest built-in role whose +permissions it all has (its **rank**, shown in Admin → Roles), and the checks that still ask for a rank give it +that much: the notebook, comment threads, collection roles and the pages a namespace's members see. So a custom role +never does more than its permissions, but may do less than them there until those checks move to permissions too. + +Someone with the `members` permission who isn't an admin gives only roles whose permissions they hold all of, and +changes only people whose role they hold all of: they can't promote themselves or take out an owner. Collection roles +(below) stay viewer, editor and admin. API tokens and apps keep their read or write scope on top of the role: a +read-only token can't use a role's write permissions. `GET /api/v1/auth/me` lists your permissions in each namespace. + ## Collection roles Every recording lives in a collection of its namespace ([API](api.md#collections-of-a-namespace)), and people can be diff --git a/docs/api.md b/docs/api.md index c809dabca..df250d4cd 100644 --- a/docs/api.md +++ b/docs/api.md @@ -123,7 +123,11 @@ PATCH /api/v1/users/{uid} DELETE /api/v1/users/{uid} remove for good (authentication.md#removing-someone) POST /api/v1/users/{uid}/signin-link ?email=true also emails it GET /api/v1/namespaces/{name}/members -PUT /api/v1/namespaces/{name}/members +PUT /api/v1/namespaces/{name}/members {email | account, role}: built-in or custom; null removes +GET /api/v1/roles the permissions and every role (access.md#roles-and-permissions) +POST /api/v1/roles admins: {name, label, description, permissions} +PATCH /api/v1/roles/{name} admins: a custom role's label, description, permissions +DELETE /api/v1/roles/{name} admins: a custom role nobody holds ``` ## admin diff --git a/docs/authentication.md b/docs/authentication.md index a6a8a5b15..f9de67554 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -5,7 +5,8 @@ There is no public sign-up. The first admin is created with a one-time **setup code** that the API prints in its log on first start (or `lens users add you@example.com --admin`, or `LENS_ADMIN_EMAIL` in `.env`). On a fresh install the web app then opens a short setup wizard ([Configuration](configuration.md#first-run-setup)). Admins then add people and -give them roles per namespace: viewer, editor or owner. +give them roles per namespace: viewer, editor, owner, or a custom role made of permissions +([Access](access.md#roles-and-permissions)). ## Signing in: passkeys diff --git a/fastapi_backend/app/api/deps.py b/fastapi_backend/app/api/deps.py index ee12457fc..052b8128d 100644 --- a/fastapi_backend/app/api/deps.py +++ b/fastapi_backend/app/api/deps.py @@ -25,6 +25,7 @@ from app.core import security from app.domain import access as acc from app.domain import auth, graph_history, hierarchy, ipgroups, oauth, store +from app.domain import roles as rl from app.domain.store import DB Config = dict[str, Any] @@ -51,7 +52,8 @@ class Principal: via: Literal["access", "token", "oauth"] # a signed-in session, an API token, or an app given access (OAuth) scope: Literal["read", "write"] = "write" sid: str | None = None - roles: dict[int, str] = field(default_factory=dict) + roles: dict[int, str] = field(default_factory=dict) # as built-in roles: a custom role counts as its rank + perms: dict[int, frozenset[str]] = field(default_factory=dict) # what each namespace role allows (roles.py) collections: dict[int, dict[int, str]] = field(default_factory=dict) # roles on collections: {space: {collection: role}} resource: str | None = None # an app's token: the server it was given for (RFC 8707), when the app named one @@ -93,7 +95,8 @@ def _resolve(request: Request, db: DB) -> Principal | None: if u and claims: p = Principal(u["id"], u["email"], u.get("name"), bool(u.get("admin")), "access", "write", claims.sid) if p: - p.roles = auth.roles(db, {"id": p.id, "admin": p.admin}) + p.perms = auth.permissions(db, {"id": p.id, "admin": p.admin}) + p.roles = {sid: rl.rank(perms) for sid, perms in p.perms.items()} p.collections = {} if p.admin else hierarchy.roles_of(db, p.id) request.state.principal = p return p @@ -162,12 +165,20 @@ def readable(self) -> set[int] | None: def editable(self) -> list[int]: return sorted(s for s in self.roles if auth.allows(self.roles, s, "editor")) + def can(self, sid: int, perm: str) -> bool: + """Whether this person's role in namespace `sid` has a permission (roles.py).""" + return bool(self.user) and perm in self.user.perms.get(sid, frozenset()) # type: ignore[union-attr] + def need(self, sid: int, role: str = "viewer") -> None: + """A role (viewer, editor, owner: at least that rank) or a permission (roles.PERMISSIONS) in namespace `sid`.""" if not self.user: raise HTTPException(401, "sign in first", headers={"WWW-Authenticate": "Bearer"}) if not auth.allows(self.roles, sid, "viewer"): raise HTTPException(404, "not found") - if not auth.allows(self.roles, sid, role): + if role in rl.PERMISSIONS: + if not self.can(sid, role): + raise HTTPException(403, f"needs the {role} permission in this namespace") + elif not auth.allows(self.roles, sid, role): raise HTTPException(403, f"needs {role} access to this namespace") def collection_role(self, sid: int, cid: int | None) -> str | None: @@ -193,7 +204,12 @@ def need_in(self, sid: int, cid: int | None, role: str = "viewer") -> None: have = self.rank_in(sid, cid) if not have: raise HTTPException(404, "not found") - if have < auth.ROLES[role]: + if role in rl.PERMISSIONS: + # the namespace role's permission, or a collection role ranking as the built-in role that first has it + coll = hierarchy.ROLES.get(self.collection_role(sid, cid) or "", 0) + if not self.can(sid, role) and coll < auth.ROLES[rl.minimum(role)]: + raise HTTPException(403, f"needs the {role} permission for this recording") + elif have < auth.ROLES[role]: raise HTTPException(403, f"needs {role} access to this recording") def partial(self) -> dict[int, list[int]]: diff --git a/fastapi_backend/app/api/v1/routes/auth.py b/fastapi_backend/app/api/v1/routes/auth.py index 5a2dca693..319dd8d0a 100644 --- a/fastapi_backend/app/api/v1/routes/auth.py +++ b/fastapi_backend/app/api/v1/routes/auth.py @@ -121,6 +121,7 @@ def me(user: CurrentUser, db: Db) -> Me: return Me( user=UserPublic(**(auth.active_account(db, user.id) or {})), roles=roles, + permissions={names.get(k, str(k)): sorted(v) for k, v in user.perms.items()}, partial=partial, via=user.via, scope=user.scope, diff --git a/fastapi_backend/app/api/v1/routes/comments.py b/fastapi_backend/app/api/v1/routes/comments.py index c8af05f47..17ea33131 100644 --- a/fastapi_backend/app/api/v1/routes/comments.py +++ b/fastapi_backend/app/api/v1/routes/comments.py @@ -183,7 +183,7 @@ def list_highlights(rid: int, user: CurrentUser, acl: Acl, db: Db) -> list[Highl def create_highlight(rid: int, body: HighlightCreate, user: Writer, acl: Acl, db: Db) -> Highlight: """Mark a passage (`t0`–`t1`, with the `quote` picked in the text) in a `colour` (yellow, green, blue or red), with a `label`: editors of the resource. Up to 1,000 on a resource.""" - rec = _recording(acl, db, rid, "editor") + rec = _recording(acl, db, rid, "edit") with domain_errors(): hid = highlights.create( db, rid, rec["space"], user.id, body.t0, body.t1, body.quote, body.colour, body.label, rec.get("duration_ms") @@ -194,7 +194,7 @@ def create_highlight(rid: int, body: HighlightCreate, user: Writer, acl: Acl, db @router.patch("/highlights/{hid}") def update_highlight(rid: int, hid: int, body: HighlightUpdate, user: Writer, acl: Acl, db: Db) -> Highlight: """Change its colour or its label (an empty label clears it): editors of the resource.""" - rec = _recording(acl, db, rid, "editor") + rec = _recording(acl, db, rid, "edit") _highlight(db, rid, hid) if body.colour is None and body.label is None: raise HTTPException(400, "change the colour or the label") @@ -206,7 +206,7 @@ def update_highlight(rid: int, hid: int, body: HighlightUpdate, user: Writer, ac @router.delete("/highlights/{hid}") def delete_highlight(rid: int, hid: int, user: Writer, acl: Acl, db: Db) -> Ok: """Delete it: editors of the resource. Audited (`highlight.delete`).""" - _recording(acl, db, rid, "editor") + _recording(acl, db, rid, "edit") h = _highlight(db, rid, hid) highlights.delete(db, hid) auth.audit(db, user.as_audit(), "highlight.delete", f"recording:{rid}", {"highlight": hid, "writer": h["account"] == user.id}) diff --git a/fastapi_backend/app/api/v1/routes/content_types.py b/fastapi_backend/app/api/v1/routes/content_types.py index 14867484f..9295344af 100644 --- a/fastapi_backend/app/api/v1/routes/content_types.py +++ b/fastapi_backend/app/api/v1/routes/content_types.py @@ -64,7 +64,7 @@ def get_recording_content_type(rid: int, acl: Acl, db: Db) -> RecordingContentTy @router.put("/recordings/{rid}/content-type") def set_recording_content_type(rid: int, body: RecordingContentTypeSet, user: Writer, acl: Acl, db: Db) -> RecordingContentType: """Choose the resource's subtype (null: recognise it from the file again). Editors. New runs use its pipeline.""" - acl.recording(rid, "editor") + acl.recording(rid, "edit") try: content_types.choose(db, rid, body.content_type) except ValueError as e: diff --git a/fastapi_backend/app/api/v1/routes/entities.py b/fastapi_backend/app/api/v1/routes/entities.py index b7499c5e4..4d4373efb 100644 --- a/fastapi_backend/app/api/v1/routes/entities.py +++ b/fastapi_backend/app/api/v1/routes/entities.py @@ -153,7 +153,7 @@ def get_entity_timeline(user: CurrentUser, acl: Acl, db: Db, ids: str, by: str = @router.post("/entities/retype") def retype_entities(body: EntityRetype, request: Request, user: Writer, acl: Acl, db: Db) -> Ok: for i in body.ids: - _entity_space(db, acl, i, "editor") + _entity_space(db, acl, i, "curate") with domain_errors(): ents.retype(db, body.ids, body.type) auth.audit(db, user.as_audit(), "entity.retype", None, {"ids": body.ids, "type": body.type}) @@ -164,7 +164,7 @@ def retype_entities(body: EntityRetype, request: Request, user: Writer, acl: Acl @router.post("/entities/merge") def merge_entities(body: EntityMerge, request: Request, user: Writer, acl: Acl, db: Db) -> EntityMerged: for i in [body.keep, *body.others]: - _entity_space(db, acl, i, "editor") + _entity_space(db, acl, i, "curate") with domain_errors(): mid = ents.merge(db, body.keep, body.others, user.email) auth.audit(db, user.as_audit(), "entity.merge", f"entity:{body.keep}", {"others": body.others}) @@ -177,7 +177,7 @@ def undo_entity_merge(mid: int, request: Request, user: Writer, acl: Acl, db: Db m = db.one("SELECT space FROM $r", r=R("entity_merge", mid)) if not m: raise HTTPException(404, "not found") - acl.need(m["space"], "editor") + acl.need(m["space"], "curate") with domain_errors(): ents.undo_merge(db, mid) auth.audit(db, user.as_audit(), "entity.merge.undo", f"entity_merge:{mid}") @@ -188,8 +188,8 @@ def undo_entity_merge(mid: int, request: Request, user: Writer, acl: Acl, db: Db @router.post("/entities/not-same") def mark_entities_not_same(body: EntityNotSame, user: Writer, acl: Acl, db: Db) -> Ok: """Stop suggesting that these two are the same.""" - _entity_space(db, acl, body.a, "editor") - _entity_space(db, acl, body.b, "editor") + _entity_space(db, acl, body.a, "curate") + _entity_space(db, acl, body.b, "curate") ents.not_same(db, body.a, body.b) auth.audit(db, user.as_audit(), "entity.not_same", None, {"a": body.a, "b": body.b}) return Ok() @@ -235,7 +235,7 @@ def get_entity_connections(eid: int, user: CurrentUser, acl: Acl, db: Db) -> dic @router.post("/entities/{eid}/rename") def rename_entity(eid: int, body: EntityRename, request: Request, user: Writer, acl: Acl, db: Db) -> dict[str, Any]: """Rename; with `correct`, also fix the transcript lines (re-analysing the recordings). `dry_run` previews the lines.""" - _entity_space(db, acl, eid, "editor") + _entity_space(db, acl, eid, "curate") with domain_errors(): out = ents.rename(db, eid, body.name, body.keep_alias, body.correct, body.dry_run) if not body.dry_run: @@ -248,7 +248,7 @@ def rename_entity(eid: int, body: EntityRename, request: Request, user: Writer, @router.patch("/entities/{eid}") def update_entity(eid: int, body: EntityUpdate, request: Request, user: Writer, acl: Acl, db: Db) -> EntityDetail: """Describe the entity (what it is, in your words), say how else it's said, or put it on (or off) the fixed list.""" - sid = _entity_space(db, acl, eid, "editor") + sid = _entity_space(db, acl, eid, "curate") changes = body.model_dump(exclude_unset=True) with domain_errors(): if "description" in changes: @@ -270,7 +270,7 @@ def update_entity(eid: int, body: EntityUpdate, request: Request, user: Writer, @router.delete("/entities/{eid}") def delete_entity(eid: int, request: Request, user: Writer, acl: Acl, db: Db) -> Ok: """Take a defined entity that nothing mentions off the fixed list.""" - _entity_space(db, acl, eid, "editor") + _entity_space(db, acl, eid, "curate") with domain_errors(): ents.remove(db, eid) auth.audit(db, user.as_audit(), "entity.delete", f"entity:{eid}", None) @@ -296,7 +296,7 @@ def define_entity(name: str, body: EntityDefine, request: Request, user: Writer, @router.post("/entities/{eid}/hide") def hide_entity(eid: int, request: Request, user: Writer, acl: Acl, db: Db, body: EntityHide | None = None) -> Ok: body = body or EntityHide() - _entity_space(db, acl, eid, "editor") + _entity_space(db, acl, eid, "curate") with domain_errors(): ents.hide(db, eid, body.hidden, body.reason) action = "entity.hide" if body.hidden else "entity.restore" @@ -309,8 +309,8 @@ def hide_entity(eid: int, request: Request, user: Writer, acl: Acl, db: Db, body def link_entity(eid: int, body: EntityLinkRequest, request: Request, user: Writer, acl: Acl, db: Db) -> Ok: """Say an entity in another namespace is the same thing (they stay separate; the graph joins them).""" other = body.with_ - _entity_space(db, acl, eid, "editor") - _entity_space(db, acl, other, "editor") + _entity_space(db, acl, eid, "curate") + _entity_space(db, acl, other, "curate") with domain_errors(): ents.link(db, eid, other) auth.audit(db, user.as_audit(), "entity.link", f"entity:{eid}", {"with": other}) @@ -320,7 +320,7 @@ def link_entity(eid: int, body: EntityLinkRequest, request: Request, user: Write @router.delete("/entities/{eid}/link/{other}") def unlink_entity(eid: int, other: int, request: Request, user: Writer, acl: Acl, db: Db) -> Ok: - _entity_space(db, acl, eid, "editor") + _entity_space(db, acl, eid, "curate") ents.unlink(db, eid, other) auth.audit(db, user.as_audit(), "entity.unlink", f"entity:{eid}", {"with": other}) _changed(request) @@ -333,7 +333,7 @@ def move_mention(mention: str, body: MentionMove, request: Request, user: Writer m = db.one("SELECT space FROM $r", r=R("mentions", mention)) if not m: raise HTTPException(404, "not found") - acl.need(m["space"], "editor") + acl.need(m["space"], "curate") try: tid = ents.move_mention(db, mention, body.target, body.new_name, body.new_type or "TERM", body.remove) except (ValueError, KeyError) as e: diff --git a/fastapi_backend/app/api/v1/routes/fields.py b/fastapi_backend/app/api/v1/routes/fields.py index 59254952c..2f7d224fd 100644 --- a/fastapi_backend/app/api/v1/routes/fields.py +++ b/fastapi_backend/app/api/v1/routes/fields.py @@ -171,7 +171,7 @@ def get_resource_fields(rid: int, acl: Acl, user: CurrentUser, db: Db) -> FieldV def save_resource_fields(rid: int, body: FieldValuesUpdate, acl: Acl, user: Writer, db: Db, cfg: Cfg) -> FieldValues: """Set or clear (null) the resource's values for the fields named; the others keep theirs. Editors. Kept in its metadata history (so a revert puts them back) and audited as `fields.save`.""" - rec = acl.recording(rid, "editor") + rec = acl.recording(rid, "edit") defs, row = fieldmod.resource_fields(db, rid) with domain_errors(): after = fieldmod.merged(row, defs, _changes(body)) @@ -238,7 +238,7 @@ def get_file_fields(rid: int, fid: int, acl: Acl, user: CurrentUser, db: Db) -> @router.put("/recordings/{rid}/files/{fid}/fields") def save_file_fields(rid: int, fid: int, body: FieldValuesUpdate, acl: Acl, user: Writer, db: Db) -> FieldValues: """Set or clear (null) the file's values for the fields named. Editors of the resource; audited as `fields.save`.""" - rec = acl.recording(rid, "editor") + rec = acl.recording(rid, "edit") row = _file_row(db, rid, fid) defs = fieldmod.applying(db, rec["space"], "file", rec.get("collection")) with domain_errors(): diff --git a/fastapi_backend/app/api/v1/routes/files.py b/fastapi_backend/app/api/v1/routes/files.py index f2708708c..586b91e16 100644 --- a/fastapi_backend/app/api/v1/routes/files.py +++ b/fastapi_backend/app/api/v1/routes/files.py @@ -146,7 +146,7 @@ async def _receive(request: Request, cfg: dict[str, Any]) -> pathlib.Path: def _editor(acl: Access, rid: int) -> dict[str, Any]: - return acl.recording(rid, "editor") + return acl.recording(rid, "edit") @router.post("", openapi_extra=CHUNK) diff --git a/fastapi_backend/app/api/v1/routes/graph.py b/fastapi_backend/app/api/v1/routes/graph.py index c3685093e..04113ad10 100644 --- a/fastapi_backend/app/api/v1/routes/graph.py +++ b/fastapi_backend/app/api/v1/routes/graph.py @@ -204,7 +204,7 @@ def propose_graph_change(request: Request, body: ChangeAsk, user: Writer, acl: A except KeyError: raise HTTPException(404, "not found") from None for r in rows: - acl.need(r["space"], "editor") + acl.need(r["space"], "curate") origin = {"by": user.email, "via": user.via} try: cid, status = organize.propose(db, body.kind, ids[0], ids[1], body.reason, origin, body.apply, user.email) diff --git a/fastapi_backend/app/api/v1/routes/graph_history.py b/fastapi_backend/app/api/v1/routes/graph_history.py index 7b268b5a1..5a30b7e29 100644 --- a/fastapi_backend/app/api/v1/routes/graph_history.py +++ b/fastapi_backend/app/api/v1/routes/graph_history.py @@ -132,7 +132,7 @@ def graph_rollback(request: Request, body: RollbackAsk, user: Writer, acl: Acl, if editable is not None and not editable: raise HTTPException(403, "rolling back needs editor access to a namespace") if body.namespace: - spaces: set[int] | None = {acl.namespace(body.namespace, "editor")} + spaces: set[int] | None = {acl.namespace(body.namespace, "curate")} else: spaces = editable try: diff --git a/fastapi_backend/app/api/v1/routes/import_hooks.py b/fastapi_backend/app/api/v1/routes/import_hooks.py index 8a2f32c9a..fd4c71bae 100644 --- a/fastapi_backend/app/api/v1/routes/import_hooks.py +++ b/fastapi_backend/app/api/v1/routes/import_hooks.py @@ -62,7 +62,7 @@ @router.get("/namespaces/{name}/import-hooks") def list_import_hooks(name: str, acl: Acl, user: CurrentUser, db: Db) -> list[ImportHook]: """The namespace's import webhooks (owners). Their tokens aren't shown again, only their last four characters.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") return [ImportHook.model_validate(h) for h in import_hooks.hooks(db, sid)] @@ -70,7 +70,7 @@ def list_import_hooks(name: str, acl: Acl, user: CurrentUser, db: Db) -> list[Im def create_import_hook(name: str, body: ImportHookCreate, acl: Acl, user: Writer, db: Db) -> ImportHookCreated: """Make an import webhook for the namespace (owners). Its token is in the answer and never shown again. Audited as `import_hook.create`.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") with domain_errors(): hook, token = import_hooks.create(db, sid, body.name, body.collection, body.pipeline, user.email) auth.audit(db, user.as_audit(), "import_hook.create", f"import_hook:{hook['id']}", {"namespace": name, "name": hook["name"]}) @@ -81,7 +81,7 @@ def create_import_hook(name: str, body: ImportHookCreate, acl: Acl, user: Writer def update_import_hook(name: str, hid: int, body: ImportHookUpdate, acl: Acl, user: Writer, db: Db) -> ImportHook: """Rename a hook, pause or resume it (`enabled`), or change its collection or pipeline (null for the namespace's own) (owners).""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") changes = body.model_dump(exclude_unset=True) if changes.get("name") is None: changes.pop("name", None) @@ -103,7 +103,7 @@ def update_import_hook(name: str, hid: int, body: ImportHookUpdate, acl: Acl, us @router.post("/namespaces/{name}/import-hooks/{hid}/token") def new_import_hook_token(name: str, hid: int, acl: Acl, user: Writer, db: Db) -> ImportHookToken: """A new token for the hook (owners); the old one stops working at once.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") with domain_errors(): token = import_hooks.new_token(db, hid, sid) auth.audit(db, user.as_audit(), "import_hook.token", f"import_hook:{hid}") @@ -113,7 +113,7 @@ def new_import_hook_token(name: str, hid: int, acl: Acl, user: Writer, db: Db) - @router.delete("/namespaces/{name}/import-hooks/{hid}") def delete_import_hook(name: str, hid: int, acl: Acl, user: Writer, db: Db) -> Ok: """Delete a hook (owners): its token stops working. What it imported stays.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") with domain_errors(): hook = import_hooks.delete(db, hid, sid) auth.audit(db, user.as_audit(), "import_hook.delete", f"import_hook:{hid}", {"namespace": name, "name": hook["name"]}) diff --git a/fastapi_backend/app/api/v1/routes/imports.py b/fastapi_backend/app/api/v1/routes/imports.py index 0e2aed486..494e5525b 100644 --- a/fastapi_backend/app/api/v1/routes/imports.py +++ b/fastapi_backend/app/api/v1/routes/imports.py @@ -97,7 +97,7 @@ def import_transcript(body: ImportRequest, request: Request, acl: Acl, user: Wri check_pipeline(db, body.pipeline) try: sid = store.ns_id(db, ns, create=False) - acl.need(sid, "editor") + acl.need(sid, "import") except KeyError: if not user.admin: raise HTTPException(403, "only admins can create namespaces") from None @@ -140,7 +140,7 @@ def import_web_page(body: WebImportRequest, acl: Acl, user: Writer, db: Db, cfg: check_pipeline(db, body.pipeline) try: sid = store.ns_id(db, ns, create=False) - acl.need(sid, "editor") + acl.need(sid, "import") except KeyError: if not user.admin: raise HTTPException(403, "only admins can create namespaces") from None @@ -173,7 +173,7 @@ def import_video(body: VideoImportRequest, acl: Acl, user: Writer, db: Db, cfg: sid: int | None try: sid = store.ns_id(db, ns, create=False) - acl.need(sid, "editor") + acl.need(sid, "import") except KeyError: if not user.admin: raise HTTPException(403, "only admins can create namespaces") from None @@ -209,7 +209,7 @@ def import_web_links(body: LinksImportRequest, acl: Acl, user: Writer, db: Db, c sid: int | None try: sid = store.ns_id(db, ns, create=False) - acl.need(sid, "editor") + acl.need(sid, "import") except KeyError: if not user.admin: raise HTTPException(403, "only admins can create namespaces") from None diff --git a/fastapi_backend/app/api/v1/routes/jobs.py b/fastapi_backend/app/api/v1/routes/jobs.py index 0bc62aa6a..1289d4415 100644 --- a/fastapi_backend/app/api/v1/routes/jobs.py +++ b/fastapi_backend/app/api/v1/routes/jobs.py @@ -134,7 +134,7 @@ def scan() -> None: @router.post("/jobs/{jid}/cancel") def cancel_job(jid: int, acl: Acl, user: Writer, db: Db) -> Ok: - _job(db, acl, jid, "editor") + _job(db, acl, jid, "process") with domain_errors(): jobs.cancel(db, jid) return Ok() @@ -144,7 +144,7 @@ def cancel_job(jid: int, acl: Acl, user: Writer, db: Db) -> Ok: def release_job(jid: int, body: HeldRunDecision, acl: Acl, user: AdminWriter, db: Db) -> Ok: """Pick for a job held over a budget (docs/budgets.md): run it now, once, whatever its budgets say, or skip it (admins, who set the budgets).""" - _job(db, acl, jid, "editor") + _job(db, acl, jid, "process") with domain_errors(): jobs.release(db, jid, body.run, user.email) auth.audit(db, user.as_audit(), "job.release" if body.run else "job.skip", f"job:{jid}") @@ -153,7 +153,7 @@ def release_job(jid: int, body: HeldRunDecision, acl: Acl, user: AdminWriter, db @router.post("/jobs/{jid}/retry") def retry_job(jid: int, acl: Acl, user: Writer, db: Db) -> Ok: - _job(db, acl, jid, "editor") + _job(db, acl, jid, "process") with domain_errors(): jobs.retry(db, jid) return Ok() @@ -164,13 +164,13 @@ def create_jobs(body: JobsCreate, acl: Acl, user: Writer, db: Db) -> JobsQueued: """Queue recordings (these steps, a pipeline, or their namespace's pipeline) and/or everything pending in a namespace.""" out: list[int] = [] for rid in body.recordings: - acl.recording(rid, "editor") + acl.recording(rid, "process") try: out.append(jobs.enqueue(db, rid, body.steps or None, by=user.email, pipeline=body.pipeline)) except (ValueError, KeyError) as e: raise HTTPException(400, str(e)) from None if body.namespace: - sid = acl.namespace(body.namespace, "editor") + sid = acl.namespace(body.namespace, "process") out += jobs.enqueue_pending(db, sid, by=user.email) return JobsQueued(jobs=out) diff --git a/fastapi_backend/app/api/v1/routes/metadata.py b/fastapi_backend/app/api/v1/routes/metadata.py index cfb3ddf3b..68cd61a18 100644 --- a/fastapi_backend/app/api/v1/routes/metadata.py +++ b/fastapi_backend/app/api/v1/routes/metadata.py @@ -86,7 +86,7 @@ def get_namespace_metadata(name: str, user: CurrentUser, acl: Acl, db: Db) -> Na @router.put("/namespaces/{name}/metadata") def update_namespace_metadata(name: str, body: NamespaceMetadataUpdate, user: Writer, acl: Acl, db: Db) -> NamespaceMetadata: """Collection metadata and the profile (required fields, defaults, vocabularies, default access). Owners only.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") with domain_errors(): out = md.save_namespace(db, sid, body.meta, body.profile, user.email) auth.audit(db, user.as_audit(), "metadata.namespace", name) @@ -98,7 +98,7 @@ def bulk_update_metadata(body: MetadataBulk, user: Writer, acl: Acl, db: Db, cfg """Set or clear fields on many recordings. `dry_run` (the default) reports what would change.""" rids = list(body.recordings) if body.namespace: - sid = acl.namespace(body.namespace, "editor") + sid = acl.namespace(body.namespace, "edit") rids += db.values("SELECT VALUE record::id(id) FROM recording WHERE space = $s", s=sid) for rid in set(rids): acl.recording(rid, _role_for([*body.set, *body.clear])) diff --git a/fastapi_backend/app/api/v1/routes/namespaces.py b/fastapi_backend/app/api/v1/routes/namespaces.py index 82ad7f71a..50954bb0d 100644 --- a/fastapi_backend/app/api/v1/routes/namespaces.py +++ b/fastapi_backend/app/api/v1/routes/namespaces.py @@ -78,7 +78,7 @@ def create_namespace(body: NamespaceCreate, user: AdminWriter, db: Db, request: def update_namespace(name: str, body: NamespaceUpdate, acl: Acl, user: Writer, db: Db, request: Request) -> Ok: """Owners: the graph mode (shared or isolated), the default pipeline (null for the built-in one) and a pipeline per content type.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") sent = body.model_fields_set if "graph" in sent: if body.graph is None: @@ -188,14 +188,14 @@ def _ip_group_detail(g: dict[str, Any]) -> dict[str, Any]: @router.get("/{name}/ip-groups") def list_ip_groups(name: str, request: Request, acl: Acl, user: CurrentUser, db: Db) -> IpGroups: """The namespace's IP groups (owners), and your address as the server sees it, to check the ranges against.""" - return _ip_groups(request, db, acl.namespace(name, "owner")) + return _ip_groups(request, db, acl.namespace(name, "manage")) @router.post("/{name}/ip-groups") def create_ip_group(name: str, body: IpGroupCreate, request: Request, acl: Acl, user: Writer, db: Db) -> IpGroups: """Add an IP group (owners): visitors from its addresses see all of every recording in the namespace (everything), or of the recordings chosen on each. Answers with all of the namespace's groups.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") with domain_errors(): g = ipgroups.create(db, sid, body.name, body.ranges, body.everything, user.email) auth.audit(db, user.as_audit(), "namespace.ip_group.create", f"space:{sid}", _ip_group_detail(g)) @@ -206,7 +206,7 @@ def create_ip_group(name: str, body: IpGroupCreate, request: Request, acl: Acl, def update_ip_group(name: str, gid: int, body: IpGroupUpdate, request: Request, acl: Acl, user: Writer, db: Db) -> IpGroups: """Rename an IP group, change its ranges or what it opens (owners). Choosing recordings again after opening everything brings back the ones chosen before.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") changes = {k: v for k, v in body.model_dump(exclude_unset=True).items() if v is not None} if not changes: raise HTTPException(400, "send name, ranges or everything") @@ -221,7 +221,7 @@ def update_ip_group(name: str, gid: int, body: IpGroupUpdate, request: Request, @router.delete("/{name}/ip-groups/{gid}") def delete_ip_group(name: str, gid: int, request: Request, acl: Acl, user: Writer, db: Db) -> IpGroups: """Delete an IP group (owners): its visitors lose what it opened. Answers with the groups left.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") with domain_errors(): g = ipgroups.delete(db, gid, sid) auth.audit(db, user.as_audit(), "namespace.ip_group.delete", f"space:{sid}", _ip_group_detail(g)) diff --git a/fastapi_backend/app/api/v1/routes/notes.py b/fastapi_backend/app/api/v1/routes/notes.py index 72c8db872..551f7a173 100644 --- a/fastapi_backend/app/api/v1/routes/notes.py +++ b/fastapi_backend/app/api/v1/routes/notes.py @@ -94,7 +94,7 @@ def create_note(rid: int, body: NoteCreate, user: Writer, acl: Acl, db: Db) -> N """Write a note about a moment (`t0`–`t1`, with the `quote` picked in the transcript) or about the whole recording. Anyone who can read the recording can; only you see it unless you share it with everyone who can read the recording, which needs editor access. Up to 500 each on a recording. Sharing is audited (`note.share`).""" - rec = _recording(acl, db, rid, "editor" if body.shared else "viewer") + rec = _recording(acl, db, rid, "edit" if body.shared else "viewer") with domain_errors(): nid = notes.create(db, rid, rec["space"], user.id, body.text, body.t0, body.t1, body.quote, body.shared, rec.get("duration_ms")) if body.shared: @@ -113,7 +113,7 @@ def update_note(rid: int, nid: int, body: NoteUpdate, user: Writer, acl: Acl, db if body.text is None and body.shared is None: raise HTTPException(400, "change the text, or share or unshare it") if body.shared and not n["shared"]: - acl.need_in(rec["space"], rec.get("collection"), "editor") + acl.need_in(rec["space"], rec.get("collection"), "edit") with domain_errors(): notes.update(db, nid, body.text, body.shared) if body.shared is not None and body.shared != bool(n["shared"]): diff --git a/fastapi_backend/app/api/v1/routes/notifications.py b/fastapi_backend/app/api/v1/routes/notifications.py index 80d9dc146..6bf015782 100644 --- a/fastapi_backend/app/api/v1/routes/notifications.py +++ b/fastapi_backend/app/api/v1/routes/notifications.py @@ -32,7 +32,7 @@ def _detail(t: dict[str, Any]) -> dict[str, Any]: @router.get("") def list_notify_targets(name: str, acl: Acl, user: CurrentUser, db: Db, cfg: Cfg) -> NotifyTargets: """The namespace's notification targets (owners), and the events they can get.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") return NotifyTargets( events=[EventInfo(type=k, label=v) for k, v in notify.EVENTS.items()], targets=[NotifyTarget(**notify.view(t)) for t in notify.targets(db, sid)], @@ -43,7 +43,7 @@ def list_notify_targets(name: str, acl: Acl, user: CurrentUser, db: Db, cfg: Cfg @router.post("") def create_notify_target(name: str, body: NotifyTargetCreate, acl: Acl, user: Writer, db: Db, cfg: Cfg) -> NotifyTargetCreated: """Add a target (owners). A webhook comes back with its signing secret, this once.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") with domain_errors(): t, secret = notify.create( db, cfg, sid, body.name, body.kind, body.url, body.events, body.gateway, body.username, body.token, body.enabled, user.email @@ -55,7 +55,7 @@ def create_notify_target(name: str, body: NotifyTargetCreate, acl: Acl, user: Wr @router.patch("/{tid}") def update_notify_target(name: str, tid: int, body: NotifyTargetUpdate, acl: Acl, user: Writer, db: Db, cfg: Cfg) -> NotifyTarget: """Change a target (owners): its name, address, events, whether it's on, and Matterbridge's gateway, name and token.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") changes = body.model_dump(exclude_unset=True) if not changes: raise HTTPException(400, "send something to change") @@ -68,7 +68,7 @@ def update_notify_target(name: str, tid: int, body: NotifyTargetUpdate, acl: Acl @router.delete("/{tid}") def delete_notify_target(name: str, tid: int, acl: Acl, user: Writer, db: Db) -> Ok: """Delete a target and what it was sent (owners).""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") with domain_errors(): t = notify.delete(db, tid, sid) auth.audit(db, user.as_audit(), "namespace.notification.delete", f"space:{sid}", _detail(t)) @@ -78,7 +78,7 @@ def delete_notify_target(name: str, tid: int, acl: Acl, user: Writer, db: Db) -> @router.post("/{tid}/test") def test_notify_target(name: str, tid: int, acl: Acl, user: Writer, db: Db, cfg: Cfg) -> NotifyTestResult: """Send the target a test message now (owners) and say how it went; it shows in the target's deliveries too.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") with domain_errors(): return NotifyTestResult(**notify.test(db, cfg, tid, sid, user.email)) @@ -86,7 +86,7 @@ def test_notify_target(name: str, tid: int, acl: Acl, user: Writer, db: Db, cfg: @router.post("/{tid}/secret") def rotate_notify_secret(name: str, tid: int, acl: Acl, user: Writer, db: Db, cfg: Cfg) -> NotifySecret: """A webhook's new signing secret (owners), shown this once; the old one stops working at once.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") with domain_errors(): secret = notify.rotate_secret(db, cfg, tid, sid, user.email) auth.audit(db, user.as_audit(), "namespace.notification.secret", f"space:{sid}", {"id": tid}) @@ -96,7 +96,7 @@ def rotate_notify_secret(name: str, tid: int, acl: Acl, user: Writer, db: Db, cf @router.get("/{tid}/deliveries") def list_notify_deliveries(name: str, tid: int, acl: Acl, user: CurrentUser, db: Db) -> list[NotifyDelivery]: """What the target was sent lately, newest first (owners): up to 50, kept for 30 days.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") with domain_errors(): notify.get(db, tid, sid) return [NotifyDelivery(**d) for d in notify.deliveries(db, tid)] diff --git a/fastapi_backend/app/api/v1/routes/ns_assistant.py b/fastapi_backend/app/api/v1/routes/ns_assistant.py index 248b9af45..19005fbde 100644 --- a/fastapi_backend/app/api/v1/routes/ns_assistant.py +++ b/fastapi_backend/app/api/v1/routes/ns_assistant.py @@ -32,7 +32,7 @@ def get_namespace_assistant(name: str, acl: Acl, db: Db) -> NamespaceAssistant: @router.patch("/{name}/assistant") def update_namespace_assistant(name: str, body: NamespaceAssistantUpdate, acl: Acl, user: Writer, db: Db) -> NamespaceAssistant: """Owners: turn the assistant on or off, name it, or change its instructions.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") try: ns_assistant.save_profile(db, sid, body.enabled, body.name, body.instructions, user.email) except ValueError as e: @@ -64,7 +64,7 @@ def list_assistant_memories( @router.post("/{name}/assistant/memories") def add_assistant_memory(name: str, body: AssistantMemoryCreate, acl: Acl, user: Writer, db: Db) -> Created: """Editors: tell the assistant something to remember.""" - sid = acl.namespace(name, "editor") + sid = acl.namespace(name, "edit") try: mid = ns_assistant.remember(db, sid, body.text, user.id, author="person") if body.pinned: @@ -77,7 +77,7 @@ def add_assistant_memory(name: str, body: AssistantMemoryCreate, acl: Acl, user: @router.patch("/{name}/assistant/memories/{mid}") def update_assistant_memory(name: str, mid: int, body: AssistantMemoryUpdate, acl: Acl, user: Writer, db: Db) -> AssistantMemory: """Editors: correct a memory, or pin it so it's read with every question.""" - sid = acl.namespace(name, "editor") + sid = acl.namespace(name, "edit") try: m = ns_assistant.update(db, sid, mid, body.text, body.pinned) except KeyError: @@ -90,7 +90,7 @@ def update_assistant_memory(name: str, mid: int, body: AssistantMemoryUpdate, ac @router.delete("/{name}/assistant/memories/{mid}") def forget_assistant_memory(name: str, mid: int, acl: Acl, user: Writer, db: Db) -> Ok: """Editors: forget one memory.""" - sid = acl.namespace(name, "editor") + sid = acl.namespace(name, "edit") try: ns_assistant.forget(db, sid, mid) except KeyError: @@ -101,7 +101,7 @@ def forget_assistant_memory(name: str, mid: int, acl: Acl, user: Writer, db: Db) @router.delete("/{name}/assistant/memories") def forget_all_assistant_memories(name: str, acl: Acl, user: Writer, db: Db) -> Ok: """Owners: forget everything the assistant remembers.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") ns_assistant.forget_all(db, sid) auth.audit(db, user.as_audit(), "namespace.assistant.forget_all", name) return Ok() diff --git a/fastapi_backend/app/api/v1/routes/pipelines.py b/fastapi_backend/app/api/v1/routes/pipelines.py index d6d4869bd..525aab9b2 100644 --- a/fastapi_backend/app/api/v1/routes/pipelines.py +++ b/fastapi_backend/app/api/v1/routes/pipelines.py @@ -79,7 +79,7 @@ def create_pipeline_version(pid: int, body: PipelineVersionCreate, user: AdminWr @router.post("/{pid}/run") def run_pipeline(pid: int, body: PipelineRunRequest, user: Writer, acl: Acl, db: Db) -> JobQueued: """Run this pipeline on one recording now (its outputs are kept).""" - acl.recording(body.recording, "editor") + acl.recording(body.recording, "process") try: return JobQueued(job=jobs.enqueue(db, body.recording, None, by=user.email, pipeline=pid)) except KeyError: diff --git a/fastapi_backend/app/api/v1/routes/podcasts.py b/fastapi_backend/app/api/v1/routes/podcasts.py index d7567ced2..c875fad02 100644 --- a/fastapi_backend/app/api/v1/routes/podcasts.py +++ b/fastapi_backend/app/api/v1/routes/podcasts.py @@ -85,7 +85,7 @@ def get_podcast(rid: int, acl: Acl, user: CurrentUser, db: Db) -> Podcast: def regenerate_podcast(rid: int, acl: Acl, user: Writer, db: Db) -> PodcastJob: """Make the episode again from what was asked for, reading its sources afresh (editors). A job already making it is returned instead.""" - _episode(acl, db, rid, "editor") + _episode(acl, db, rid, "process") jid = podcasts.regenerate(db, rid, by=user.email) auth.audit(db, user.as_audit(), "podcast.regenerate", f"recording:{rid}") return PodcastJob(job=jid) @@ -95,7 +95,7 @@ def regenerate_podcast(rid: int, acl: Acl, user: Writer, db: Db) -> PodcastJob: def delete_podcast(rid: int, acl: Acl, user: Writer, db: Db, cfg: Cfg, request: Request) -> Ok: """Delete an episode with its audio (editors of its namespace, unlike other recordings: Lens made it). 409 while a job is working on it.""" - _episode(acl, db, rid, "editor") + _episode(acl, db, rid, "edit") try: gone = deletion.delete(db, cfg, rid, user.email) except deletion.Running as e: diff --git a/fastapi_backend/app/api/v1/routes/rdf.py b/fastapi_backend/app/api/v1/routes/rdf.py index 1f1ac71be..ceed0c0e6 100644 --- a/fastapi_backend/app/api/v1/routes/rdf.py +++ b/fastapi_backend/app/api/v1/routes/rdf.py @@ -52,7 +52,7 @@ def get_namespace_rdf( def import_namespace_rdf(name: str, body: RdfImport, request: Request, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> RdfImportResult: """Read Dublin Core descriptions into the namespace's recordings (matched by their URI or an identifier). Each change is a metadata edit, kept in the recording's history. With dry_run (the default) nothing changes.""" - sid = acl.namespace(name, "editor") + sid = acl.namespace(name, "import") try: out = rdf_import.run(db, cfg, base_url(request, cfg), sid, body.data, body.format, body.dry_run, user.email) except rdf_import.ImportProblem as e: diff --git a/fastapi_backend/app/api/v1/routes/recordings.py b/fastapi_backend/app/api/v1/routes/recordings.py index 96e85ee29..b4eb0e222 100644 --- a/fastapi_backend/app/api/v1/routes/recordings.py +++ b/fastapi_backend/app/api/v1/routes/recordings.py @@ -259,12 +259,12 @@ def place_recordings(body: RecordingsPlace, acl: Acl, user: Writer, db: Db, cfg: to that namespace first. Their IIIF Manifests change (partOf), so harvesters hear an Update. Audited as `recording.collection`.""" for rid in dict.fromkeys(body.recordings): - acl.recording(rid, "editor") + acl.recording(rid, "edit") try: c = hierarchy.get(db, body.collection) except KeyError: raise HTTPException(404, "not found") from None - acl.need_in(c["space"], c["id"], "editor") + acl.need_in(c["space"], c["id"], "edit") with domain_errors(): moved = hierarchy.place(db, body.recordings, body.collection) for rid in moved: @@ -278,7 +278,7 @@ def place_recordings(body: RecordingsPlace, acl: Acl, user: Writer, db: Db, cfg: def retag_recordings(body: RecordingsRetag, acl: Acl, user: Writer, db: Db) -> TagsChanged: """Add and remove tags on several recordings at once (editors of each one's namespace).""" for rid in dict.fromkeys(body.recordings): - acl.recording(rid, "editor") + acl.recording(rid, "edit") with domain_errors(): return TagsChanged(changed=library.retag(db, body.recordings, body.add, body.remove)) @@ -348,7 +348,7 @@ def _attached_to(acl: Access, db: DB, link: dict[str, Any] | None) -> dict[str, @router.patch("/{rid}") def update_recording(rid: int, body: RecordingUpdate, acl: Acl, user: Writer, db: Db, cfg: Cfg) -> Recording: """Rename a recording or replace its tags (editors). A renamed recording's report is rebuilt with the new title.""" - rec = acl.recording(rid, "editor") + rec = acl.recording(rid, "edit") if body.title is None and body.tags is None: raise HTTPException(400, "send a title or tags") with domain_errors(): @@ -369,7 +369,7 @@ def delete_recording(rid: int, acl: Acl, user: Writer, db: Db, cfg: Cfg, request outputs, shares, notes, permissions and requests for access. The media file stays where it is, and scans and watched folders don't import it again; importing it on purpose brings it back. Its waiting jobs are cancelled; while a job is running on it, this answers 409. Audited as `recording.delete`.""" - acl.recording(rid, "owner") + acl.recording(rid, "remove") try: with domain_errors(): gone = deletion.delete(db, cfg, rid, user.email) @@ -394,8 +394,8 @@ def move_recording( analysis runs again there (`job`). The old namespace's scans and watched folders don't import the file again. Its files are kept under the new namespace's key. 409 when the new namespace has the same file or a job is running on it; 423 when either namespace is a vault nobody has unlocked. Audited as `recording.move`.""" - acl.recording(rid, "owner") - dst = acl.namespace(body.namespace.strip(), "editor") + acl.recording(rid, "remove") + dst = acl.namespace(body.namespace.strip(), "import") try: with domain_errors(): done = moving.move(db, cfg, rid, dst, body.rediarize, body.revoke_shares, user.email, body.collection) @@ -431,7 +431,7 @@ def update_recording_access(rid: int, body: RecordingAccessUpdate, acl: Acl, use access or open set to null follow the namespace's default again. The change is kept in the metadata history, and IIIF harvesters hear when the recording is published, changed or withdrawn.""" - acl.recording(rid, "owner") + acl.recording(rid, "publish") sent = body.model_fields_set if not sent: raise HTTPException(400, "send access, open or featured") @@ -446,7 +446,7 @@ def update_recording_access(rid: int, body: RecordingAccessUpdate, acl: Acl, use @router.get("/{rid}/permissions") def list_recording_permissions(rid: int, acl: Acl, user: CurrentUser, db: Db) -> list[Permission]: """The people given permission on the recording (owners), newest first.""" - acl.recording(rid, "owner") + acl.recording(rid, "publish") return [Permission.model_validate(p) for p in acc.people(db, rid)] @@ -454,7 +454,7 @@ def list_recording_permissions(rid: int, acl: Acl, user: CurrentUser, db: Db) -> def add_recording_permission(rid: int, body: PermissionAdd, acl: Acl, user: Writer, db: Db) -> list[Permission]: """Give someone with an account permission on the recording (owners): they see all of it on the pages visitors see and in IIIF, whatever its access; members of its namespace already do. Answers with everyone who has permission.""" - r = acl.recording(rid, "owner") + r = acl.recording(rid, "publish") acct = auth.find_account(db, body.email) if not acct or acct.get("disabled"): raise HTTPException(404, "No account uses that address. An admin can create one.") @@ -468,7 +468,7 @@ def add_recording_permission(rid: int, body: PermissionAdd, acl: Acl, user: Writ @router.delete("/{rid}/permissions/{account}") def remove_recording_permission(rid: int, account: int, acl: Acl, user: Writer, db: Db) -> list[Permission]: """Take someone's permission on the recording away (owners). Answers with everyone who still has it.""" - acl.recording(rid, "owner") + acl.recording(rid, "publish") if not acc.take(db, rid, account): raise HTTPException(404, "not found") email = (auth.get_account(db, account) or {}).get("email") @@ -486,12 +486,12 @@ def _ip_groups(db: DB, rid: int, space: int) -> list[RecordingIpGroup]: @router.get("/{rid}/ip-groups") def list_recording_ip_groups(rid: int, acl: Acl, user: CurrentUser, db: Db) -> list[RecordingIpGroup]: """The namespace's IP groups (owners), each with whether visitors from its addresses see all of this recording.""" - r = acl.recording(rid, "owner") + r = acl.recording(rid, "publish") return _ip_groups(db, rid, r["space"]) def _choose(rid: int, gid: int, on: bool, acl: Acl, user: Any, db: DB) -> list[RecordingIpGroup]: - r = acl.recording(rid, "owner") + r = acl.recording(rid, "publish") with domain_errors(): changed = ipgroups.choose(db, gid, r["space"], rid, on) name = ipgroups.get(db, gid)["name"] @@ -519,12 +519,12 @@ def close_recording_to_ip_group(rid: int, gid: int, acl: Acl, user: Writer, db: @router.get("/{rid}/requests") def list_access_requests(rid: int, acl: Acl, user: CurrentUser, db: Db) -> list[AccessRequest]: """Requests for access to the recording (owners), newest first; pending ones wait for an answer.""" - acl.recording(rid, "owner") + acl.recording(rid, "publish") return [AccessRequest.model_validate(x) for x in acc.requests(db, rids=[rid])] def _decide(rid: int, account: int, approve: bool, acl: Acl, user: Any, db: DB) -> list[AccessRequest]: - acl.recording(rid, "owner") + acl.recording(rid, "publish") req = acc.request_of(db, rid, account) if not acc.decide(db, rid, account, approve, user.email): raise HTTPException(404, "no request waits for an answer") @@ -608,7 +608,7 @@ def get_recording_wordcloud(rid: int, acl: Acl, db: Db, s: str = "") -> Response @router.post("/{rid}/reprocess") def reprocess_recording(rid: int, acl: Acl, user: Writer, db: Db, body: ReprocessRequest | None = None) -> JobQueued: - acl.recording(rid, "editor") + acl.recording(rid, "process") body = body or ReprocessRequest() try: return JobQueued(job=jobs.enqueue(db, rid, body.steps or None, by=user.email, pipeline=body.pipeline)) @@ -620,7 +620,7 @@ def reprocess_recording(rid: int, acl: Acl, user: Writer, db: Db, body: Reproces def create_share(rid: int, acl: Acl, user: Writer, db: Db, body: ShareCreate | None = None) -> ShareLink: """A read-only link to this one recording, for people without an account, with a short ``/s/`` address too. Its address is only shown now. Revoke it with DELETE /shares/{id}, or every link with DELETE /share.""" - acl.recording(rid, "editor") + acl.recording(rid, "share") link = auth.create_share(db, rid, user.id, (body or ShareCreate()).days) auth.audit(db, user.as_audit(), "share.create", f"recording:{rid}", {"link": link["id"]}) return ShareLink(id=link["id"], token=link["token"], embed=f"/embed/{rid}?s={link['token']}", short=f"/s/{link['short']}") @@ -629,7 +629,7 @@ def create_share(rid: int, acl: Acl, user: Writer, db: Db, body: ShareCreate | N @router.delete("/{rid}/share") def revoke_shares(rid: int, acl: Acl, user: Writer, db: Db) -> Ok: """Revoke every link that still works. Opening one shows a page saying the link isn't available.""" - acl.recording(rid, "editor") + acl.recording(rid, "share") n = auth.revoke_shares(db, rid, user.email) auth.audit(db, user.as_audit(), "share.revoke", f"recording:{rid}", {"links": n}) return Ok() @@ -640,7 +640,7 @@ def revoke_share( rid: int, acl: Acl, user: Writer, db: Db, sid: str = Path(pattern=r"^[0-9a-f]{10,64}$", description="the link's id") ) -> Ok: """Revoke one link. Opening it shows a page saying the link isn't available; the others keep working.""" - acl.recording(rid, "editor") + acl.recording(rid, "share") if not auth.revoke_share(db, rid, sid, user.email): raise HTTPException(404, "no such link") auth.audit(db, user.as_audit(), "share.revoke", f"recording:{rid}", {"link": sid}) @@ -651,7 +651,7 @@ def revoke_share( def list_shares(rid: int, acl: Acl, user: CurrentUser, db: Db) -> list[Share]: """The recording's share links, newest first: whether each still works, how often it was played, and the sites whose pages embed it.""" - acl.recording(rid, "editor") + acl.recording(rid, "share") people = {a["id"]: a["email"] for a in db.rows("SELECT record::id(id) AS id, email FROM account")} return [ Share( @@ -702,7 +702,7 @@ def evidence_pdf(rid: int, acl: Acl, db: Db, cfg: Cfg) -> Response: @router.patch("/{rid}/segments/{idx}") def edit_segment(rid: int, idx: int, body: SegmentUpdate, acl: Acl, user: Writer, db: Db) -> JobQueued: """Correct a transcript line (text and/or speaker); the recording is re-analysed afterwards.""" - rec = acl.recording(rid, "editor") + rec = acl.recording(rid, "edit") sr = R("segment", rid * store.SEG + idx) seg = db.one("SELECT text, speaker FROM $s", s=sr) if not seg: @@ -751,7 +751,7 @@ def split_segment(rid: int, idx: int, body: SegmentSplit, acl: Acl, user: Writer it's in. The second part starts at `t` (ms) when given, else when its first word was said (or as far into the line's time as `at` is into its text); it keeps the line's speaker unless `speaker` is sent. The lines after it move down one, with their corrections. Kept in the edit history; the recording is re-analysed afterwards.""" - rec = acl.recording(rid, "editor") + rec = acl.recording(rid, "edit") if body.speaker is not None: row = db.one("SELECT space FROM $s", s=R("speaker", body.speaker)) if not row or row["space"] != rec["space"]: @@ -766,7 +766,7 @@ def merge_segments(rid: int, idx: int, acl: Acl, user: Writer, db: Db) -> JobQue """Merge a transcript line with the next one (editors): one line with both texts, from the first's start to the second's end, with the first's speaker. The lines after it move up one, with their corrections. Kept in the edit history (with where to split it again); the recording is re-analysed afterwards.""" - acl.recording(rid, "editor") + acl.recording(rid, "edit") with domain_errors(): done = transcript.merge(db, rid, idx) return _changed(db, rid, idx, "merge", done, user) diff --git a/fastapi_backend/app/api/v1/routes/requests.py b/fastapi_backend/app/api/v1/routes/requests.py index d799df499..afb81258e 100644 --- a/fastapi_backend/app/api/v1/routes/requests.py +++ b/fastapi_backend/app/api/v1/routes/requests.py @@ -15,5 +15,5 @@ def list_pending_access_requests(acl: Acl, user: CurrentUser, db: Db) -> list[AccessRequest]: """Requests waiting for an answer, for recordings in the namespaces you own (all of them for admins), newest first. Each is answered in its recording's access settings.""" - owned = {sid for sid, role in acl.roles.items() if role == "owner"} + owned = {sid for sid in acl.roles if acl.can(sid, "publish")} return [AccessRequest.model_validate(x) for x in acc.requests(db, spaces=owned, status="pending")] if owned else [] diff --git a/fastapi_backend/app/api/v1/routes/routines.py b/fastapi_backend/app/api/v1/routes/routines.py index b4f36f894..cdc2823ab 100644 --- a/fastapi_backend/app/api/v1/routes/routines.py +++ b/fastapi_backend/app/api/v1/routes/routines.py @@ -157,7 +157,7 @@ def list_graph_changes( @router.post("/graph-changes/{cid}/accept") def accept_graph_change(cid: int, body: GraphChangeAccept, user: Writer, acl: Acl, db: Db) -> Ok: - _change(db, acl, cid, "editor") + _change(db, acl, cid, "curate") with domain_errors(): organize.accept(db, cid, user.email, body.keep) auth.audit(db, user.as_audit(), "graph_change.accept", f"graph_change:{cid}") @@ -166,7 +166,7 @@ def accept_graph_change(cid: int, body: GraphChangeAccept, user: Writer, acl: Ac @router.post("/graph-changes/{cid}/dismiss") def dismiss_graph_change(cid: int, user: Writer, acl: Acl, db: Db) -> Ok: - _change(db, acl, cid, "editor") + _change(db, acl, cid, "curate") with domain_errors(): organize.dismiss(db, cid, user.email) auth.audit(db, user.as_audit(), "graph_change.dismiss", f"graph_change:{cid}") @@ -175,7 +175,7 @@ def dismiss_graph_change(cid: int, user: Writer, acl: Acl, db: Db) -> Ok: @router.post("/graph-changes/{cid}/undo") def undo_graph_change(cid: int, user: Writer, acl: Acl, db: Db) -> Ok: - _change(db, acl, cid, "editor") + _change(db, acl, cid, "curate") with domain_errors(): organize.undo(db, cid, user.email) auth.audit(db, user.as_audit(), "graph_change.undo", f"graph_change:{cid}") diff --git a/fastapi_backend/app/api/v1/routes/speakers.py b/fastapi_backend/app/api/v1/routes/speakers.py index 2c63f7185..f28b322a5 100644 --- a/fastapi_backend/app/api/v1/routes/speakers.py +++ b/fastapi_backend/app/api/v1/routes/speakers.py @@ -121,7 +121,7 @@ def list_speaker_recordings(sid: int, acl: Acl, user: CurrentUser, db: Db) -> li @router.post("/speakers/{sid}") def rename_speaker(sid: int, body: SpeakerRename, request: Request, acl: Acl, user: Writer, db: Db) -> Ok: - acl.need(speaker_space(db, sid), "editor") + acl.need(speaker_space(db, sid), "curate") spk.rename(db, sid, body.name[:80]) request.app.state.graph_cache.clear() return Ok() @@ -130,7 +130,7 @@ def rename_speaker(sid: int, body: SpeakerRename, request: Request, acl: Acl, us @router.post("/speakers/{sid}/merge") def merge_speaker(sid: int, body: SpeakerMergeRequest, request: Request, acl: Acl, user: Writer, db: Db) -> SpeakerMerged: """Fold this speaker into ``into`` (same namespace). Undo with POST /merges/{merge_id}/undo.""" - acl.need(speaker_space(db, sid), "editor") + acl.need(speaker_space(db, sid), "curate") try: mid = spk.merge(db, sid, body.into, by=user.email) except (ValueError, KeyError, TypeError) as e: @@ -145,7 +145,7 @@ def undo_speaker_merge(mid: int, request: Request, acl: Acl, user: Writer, db: D m = db.one("SELECT space FROM $r", r=R("merge", mid)) if not m: raise HTTPException(404, "not found") - acl.need(m["space"], "editor") + acl.need(m["space"], "curate") try: spk.undo(db, mid, by=user.email) except ValueError as e: @@ -158,8 +158,8 @@ def undo_speaker_merge(mid: int, request: Request, acl: Acl, user: Writer, db: D @router.post("/speakers/{sid}/link") def link_speaker(sid: int, body: SpeakerLinkRequest, request: Request, acl: Acl, user: Writer, db: Db) -> Ok: """Mark this speaker and one in another namespace as the same person (you need editor access to both).""" - acl.need(speaker_space(db, sid), "editor") - acl.need(speaker_space(db, body.with_), "editor") + acl.need(speaker_space(db, sid), "curate") + acl.need(speaker_space(db, body.with_), "curate") try: spk.link(db, sid, body.with_) except (ValueError, KeyError, TypeError) as e: @@ -173,8 +173,8 @@ def link_speaker(sid: int, body: SpeakerLinkRequest, request: Request, acl: Acl, def unlink_speaker(sid: int, body: SpeakerPair, request: Request, acl: Acl, user: Writer, db: Db) -> Ok: """They aren't the same person after all: remove the link (editor access to both). 404 when they aren't linked. Audited as speaker.unlink.""" - acl.need(speaker_space(db, sid), "editor") - acl.need(speaker_space(db, body.with_), "editor") + acl.need(speaker_space(db, sid), "curate") + acl.need(speaker_space(db, body.with_), "curate") if not spk.unlink(db, sid, body.with_): raise HTTPException(404, "they aren't linked") auth.audit(db, user.as_audit(), "speaker.unlink", f"speaker:{sid}", {"with": body.with_}) @@ -186,8 +186,8 @@ def unlink_speaker(sid: int, body: SpeakerPair, request: Request, acl: Acl, user def not_same_speaker(sid: int, body: SpeakerPair, request: Request, acl: Acl, user: Writer, db: Db) -> Ok: """These two aren't the same person: drop the suggestion to merge them (one namespace) or link them (two), and never suggest it again. Editor access to both namespaces. Audited as speaker.not_same.""" - acl.need(speaker_space(db, sid), "editor") - acl.need(speaker_space(db, body.with_), "editor") + acl.need(speaker_space(db, sid), "curate") + acl.need(speaker_space(db, body.with_), "curate") try: spk.not_same(db, sid, body.with_, user.email) except ValueError as e: diff --git a/fastapi_backend/app/api/v1/routes/topics.py b/fastapi_backend/app/api/v1/routes/topics.py index fbd11d125..276c5e33c 100644 --- a/fastapi_backend/app/api/v1/routes/topics.py +++ b/fastapi_backend/app/api/v1/routes/topics.py @@ -78,7 +78,7 @@ def get_topic(tid: int, user: CurrentUser, acl: Acl, db: Db) -> TopicDetail: def create_topic(name: str, body: TopicCreate, request: Request, user: Writer, acl: Acl, db: Db) -> TopicDetail: """Add a topic to the namespace's vocabulary.""" sid = acl.nsid(name) - acl.need(sid, "editor") + acl.need(sid, "curate") with domain_errors(): tid = topics.create(db, sid, body.label, body.alt, body.definition, body.broader, body.related, user=user.email) auth.audit(db, user.as_audit(), "topic.create", f"topic:{tid}", body.model_dump()) @@ -99,7 +99,7 @@ def topic_candidates(name: str, user: CurrentUser, acl: Acl, db: Db, limit: int def skip_topic_candidate(name: str, body: TopicSkip, user: Writer, acl: Acl, db: Db) -> Ok: """Stop offering a label as a new topic.""" sid = acl.nsid(name) - acl.need(sid, "editor") + acl.need(sid, "curate") with domain_errors(): topics.skip_candidate(db, sid, body.label) auth.audit(db, user.as_audit(), "topic.skip", f"namespace:{name}", {"label": body.label}) @@ -109,7 +109,7 @@ def skip_topic_candidate(name: str, body: TopicSkip, user: Writer, acl: Acl, db: @router.patch("/topics/{tid}") def update_topic(tid: int, body: TopicUpdate, request: Request, user: Writer, acl: Acl, db: Db) -> TopicDetail: """Rename it, change its other labels or definition, or what it is narrower than or related to.""" - _topic_space(db, acl, tid, "editor") + _topic_space(db, acl, tid, "curate") changes = body.model_dump(exclude_unset=True) with domain_errors(): topics.update( @@ -131,7 +131,7 @@ def update_topic(tid: int, body: TopicUpdate, request: Request, user: Writer, ac @router.delete("/topics/{tid}") def delete_topic(tid: int, request: Request, user: Writer, acl: Acl, db: Db) -> Ok: """Delete it: its narrower topics move up, recordings stop being about it, and an entity it was made from shows again.""" - _topic_space(db, acl, tid, "editor") + _topic_space(db, acl, tid, "curate") with domain_errors(): eid = topics.delete(db, tid) auth.audit(db, user.as_audit(), "topic.delete", f"topic:{tid}", {"entity": eid} if eid else None) @@ -143,7 +143,7 @@ def delete_topic(tid: int, request: Request, user: Writer, acl: Acl, db: Db) -> def merge_topics(body: TopicMerge, request: Request, user: Writer, acl: Acl, db: Db) -> TopicDetail: """Fold topics into one: their labels become its other labels and their recordings are about it.""" for t in [body.keep, *body.others]: - _topic_space(db, acl, t, "editor") + _topic_space(db, acl, t, "curate") with domain_errors(): topics.merge(db, body.keep, body.others, user=user.email) auth.audit(db, user.as_audit(), "topic.merge", f"topic:{body.keep}", {"others": body.others}) @@ -154,7 +154,7 @@ def merge_topics(body: TopicMerge, request: Request, user: Writer, acl: Acl, db: @router.post("/topics/{tid}/recordings") def tag_recordings(tid: int, body: TopicRecordings, request: Request, user: Writer, acl: Acl, db: Db) -> TopicDetail: """Say recordings of the topic's namespace are about it (accepting suggestions too), or with `remove` that they aren't.""" - _topic_space(db, acl, tid, "editor") + _topic_space(db, acl, tid, "curate") with domain_errors(): topics.tag(db, tid, body.recordings, body.remove, user=user.email) auth.audit(db, user.as_audit(), "topic.untag" if body.remove else "topic.tag", f"topic:{tid}", {"recordings": body.recordings}) @@ -176,7 +176,7 @@ def entity_to_topic(eid: int, request: Request, user: Writer, acl: Acl, db: Db) row = db.one("SELECT space FROM $r", r=R("entity", int(eid))) if not row: raise HTTPException(404, "not found") - acl.need(row["space"], "editor") + acl.need(row["space"], "curate") with domain_errors(): tid = topics.from_entity(db, eid, user=user.email) auth.audit(db, user.as_audit(), "topic.from_entity", f"topic:{tid}", {"entity": eid}) diff --git a/fastapi_backend/app/api/v1/routes/uploads.py b/fastapi_backend/app/api/v1/routes/uploads.py index 465b32173..0c8858b5d 100644 --- a/fastapi_backend/app/api/v1/routes/uploads.py +++ b/fastapi_backend/app/api/v1/routes/uploads.py @@ -62,7 +62,7 @@ def _may_add(acl: Access, db: Any, user: Principal, ns: str) -> None: if not user.admin: raise HTTPException(403, "only admins can create namespaces") from None return - acl.need(sid, "editor") + acl.need(sid, "import") def _may_send(acl: Access, db: Any, user: Principal, row: dict[str, Any]) -> None: @@ -71,7 +71,7 @@ def _may_send(acl: Access, db: Any, user: Principal, row: dict[str, Any]) -> Non if row.get("hold"): return if row.get("attach"): - acl.recording(row["attach"], "editor") + acl.recording(row["attach"], "import") else: _may_add(acl, db, user, row["namespace"]) @@ -109,7 +109,7 @@ def start_upload(body: UploadStart, acl: Acl, user: Writer, db: Db, cfg: Cfg) -> if body.hold: ns = "" elif body.recording is not None: - rec = acl.recording(body.recording, "editor") + rec = acl.recording(body.recording, "import") home = store.space_names(db).get(rec["space"], "") if ns and ns != home: raise HTTPException(400, f"that recording is in {home}") diff --git a/fastapi_backend/app/api/v1/routes/users.py b/fastapi_backend/app/api/v1/routes/users.py index 3ade6c638..2a938aa40 100644 --- a/fastapi_backend/app/api/v1/routes/users.py +++ b/fastapi_backend/app/api/v1/routes/users.py @@ -7,9 +7,20 @@ from fastapi import APIRouter, HTTPException from app.api.deps import Acl, AdminReader, AdminWriter, Cfg, CurrentUser, Db, Writer, domain_errors -from app.domain import auth, store +from app.domain import auth, roles, store from app.schemas.common import Created, Ok -from app.schemas.users import Member, MemberSet, UserCreate, UserUpdate, UserWithRoles +from app.schemas.users import ( + Member, + MemberSet, + RoleCreate, + RoleOut, + RolePermission, + Roles, + RoleUpdate, + UserCreate, + UserUpdate, + UserWithRoles, +) router = APIRouter(tags=["users"]) @@ -84,17 +95,67 @@ def remove_user(uid: int, user: AdminWriter, db: Db, cfg: Cfg, lose_vaults: bool @router.get("/namespaces/{name}/members") def list_members(name: str, user: CurrentUser, acl: Acl, db: Db) -> list[Member]: """Who has a role in this namespace (owners only).""" - return auth.members(db, acl.namespace(name, "owner")) + return auth.members(db, acl.namespace(name, "members")) @router.put("/namespaces/{name}/members") def set_member(name: str, body: MemberSet, user: Writer, acl: Acl, db: Db) -> Ok: - """Give someone a role in this namespace, change it, or (role null) remove them. Owners only.""" - sid = acl.namespace(name, "owner") + """Give someone a role in this namespace (built-in or custom), change it, or (role null) remove them. Needs the + members permission; someone who isn't an admin gives only roles they hold every permission of, and changes only + people whose role they hold every permission of.""" + sid = acl.namespace(name, "members") acct = auth.find_account(db, body.email) if body.email else auth.get_account(db, body.account or 0) - if not acct: + if not acct or acct.get("removed_at"): raise HTTPException(404, "no such person") + if not user.admin: + mine = user.perms.get(sid, frozenset()) + table = roles.table(db) + now = db.one("SELECT VALUE role FROM $r", r=auth.R("membership", f"{acct['id']}-{sid}")) + for r in (body.role, now): + if r and not table.get(r, roles.ALL) <= mine: + raise HTTPException(403, f"the {r} role can do more than yours here") with domain_errors(): auth.set_role(db, acct["id"], sid, body.role) auth.audit(db, user.as_audit(), "member.set", f"space:{sid}", {"account": acct["id"], "role": body.role}) return Ok() + + +@router.get("/roles") +def list_roles(user: CurrentUser, db: Db) -> Roles: + """The permissions a role can have, and every role: viewer, editor and owner, then the custom ones.""" + return Roles( + permissions=[RolePermission(name=n, label=label, first=first) for n, (first, label) in roles.PERMISSIONS.items()], + roles=[RoleOut.model_validate(r) for r in roles.listing(db)], + ) + + +@router.post("/roles") +def create_role(body: RoleCreate, user: AdminWriter, db: Db) -> RoleOut: + """A custom role (admins), given per namespace like the built-in ones. Audited as `role.create`.""" + with domain_errors(): + name = roles.create(db, body.name, body.permissions, body.label, body.description) + auth.audit(db, user.as_audit(), "role.create", f"role:{name}", {"permissions": sorted(body.permissions)}) + return next(RoleOut.model_validate(r) for r in roles.listing(db) if r["name"] == name) + + +@router.patch("/roles/{name}") +def update_role(name: str, body: RoleUpdate, user: AdminWriter, db: Db) -> RoleOut: + """Change a custom role's label, description or permissions; everyone holding it gets the change at once. + Built-in roles can't change. Audited as `role.update`.""" + with domain_errors(): + roles.update(db, name, body.permissions, body.label, body.description) + auth.audit(db, user.as_audit(), "role.update", f"role:{name}", body.model_dump(exclude_unset=True)) + return next(RoleOut.model_validate(r) for r in roles.listing(db) if r["name"] == name) + + +@router.delete("/roles/{name}") +def delete_role(name: str, user: AdminWriter, db: Db) -> Ok: + """Delete a custom role. Refused (409) while anyone holds it. Audited as `role.delete`.""" + try: + roles.delete(db, name) + except KeyError: + raise HTTPException(404, "not found") from None + except ValueError as e: + raise HTTPException(409, str(e)) from None + auth.audit(db, user.as_audit(), "role.delete", f"role:{name}") + return Ok() diff --git a/fastapi_backend/app/api/v1/routes/vaults.py b/fastapi_backend/app/api/v1/routes/vaults.py index ca3ccc1f6..fc8d45a38 100644 --- a/fastapi_backend/app/api/v1/routes/vaults.py +++ b/fastapi_backend/app/api/v1/routes/vaults.py @@ -23,7 +23,7 @@ def _signed_in(user: CurrentUser) -> None: def _space(acl: Acl, name: str, kind: str) -> int: - return acl.namespace(name, "owner") if kind in ("seal", "add") else acl.namespace(name) + return acl.namespace(name, "manage") if kind in ("seal", "add") else acl.namespace(name) def _run(fn, *args): @@ -91,7 +91,7 @@ def add_vault_passkey(name: str, body: VaultAnswer, user: Writer, acl: Acl, db: @router.delete("/{name}/vault/passkeys/{pid}") def remove_vault_passkey(name: str, pid: str, user: Writer, acl: Acl, db: Db) -> VaultStatus: """Stop a passkey opening the vault; never the last one. Audited as `vault.remove`.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") out = _run(vaults.remove, db, sid, pid) auth.audit(db, user.as_audit(), "vault.remove", f"space:{sid}", [pid]) return VaultStatus(**out) @@ -100,7 +100,7 @@ def remove_vault_passkey(name: str, pid: str, user: Writer, acl: Acl, db: Db) -> @router.post("/{name}/vault/lock") def lock_vault(name: str, user: Writer, acl: Acl, db: Db) -> VaultStatus: """Close the vault on this server now (owners). Audited as `vault.lock`.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") out = _run(vaults.lock, db, sid) auth.audit(db, user.as_audit(), "vault.lock", f"space:{sid}") return VaultStatus(**out) @@ -110,7 +110,7 @@ def lock_vault(name: str, user: Writer, acl: Acl, db: Db) -> VaultStatus: def unseal_vault(name: str, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> VaultStatus: """Make the vault an ordinary namespace again, which the server can open (it must be unlocked). Audited as `vault.unseal`.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") out = _run(vaults.unseal, db, cfg, sid) auth.audit(db, user.as_audit(), "vault.unseal", f"space:{sid}") return VaultStatus(**out) diff --git a/fastapi_backend/app/api/v1/routes/video.py b/fastapi_backend/app/api/v1/routes/video.py index c8b6227ea..37168976e 100644 --- a/fastapi_backend/app/api/v1/routes/video.py +++ b/fastapi_backend/app/api/v1/routes/video.py @@ -109,7 +109,7 @@ def _picture(db: DB, cfg: dict[str, Any], rec: dict[str, Any], rid: int, name: s @router.patch("/recordings/{rid}/ocr/{span}") def fix_screen_text(rid: int, span: str, body: OcrFix, user: Writer, acl: Acl, db: Db) -> Ok: """Correct text read off the screen (the machine's reading is kept as `machine_text`).""" - acl.recording(rid, "editor") + acl.recording(rid, "edit") row = db.one("SELECT recording, text FROM $r", r=R("ocr_span", span)) text = body.text.strip() if not row or row["recording"] != rid: @@ -124,7 +124,7 @@ def fix_screen_text(rid: int, span: str, body: OcrFix, user: Writer, acl: Acl, d @router.delete("/recordings/{rid}/faces/{track}") def delete_face_track(rid: int, track: str, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> Ok: """Not a face: remove this track (and its crop) from the recording.""" - acl.recording(rid, "editor") + acl.recording(rid, "curate") row = db.one("SELECT recording, cover FROM $r", r=R("face_track", track)) if not row or row["recording"] != rid: raise HTTPException(404, "not found") @@ -176,7 +176,7 @@ def get_namespace_faces(name: str, user: CurrentUser, acl: Acl, db: Db) -> Names def set_namespace_faces_mode(name: str, body: FacesMode, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> FacesModeSet: """off, detect or recognize (which needs a purpose), and whether faces are pixelated for visitors. Owners only. `reprocess` queues the namespace's videos, documents and images (faces on their pages).""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") if body.mode is None and body.pixelate is None: raise HTTPException(400, "say the mode, or whether to pixelate faces") with domain_errors(): @@ -198,7 +198,7 @@ def set_namespace_faces_mode(name: str, body: FacesMode, user: Writer, acl: Acl, @router.delete("/namespaces/{name}/faces") def delete_namespace_faces(name: str, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> Ok: """Delete every face, track and crop in the namespace. Owners only.""" - sid = acl.namespace(name, "owner") + sid = acl.namespace(name, "manage") facemod.delete_namespace(db, cfg, sid) auth.audit(db, user.as_audit(), "faces.delete_all", name) return Ok() @@ -209,7 +209,7 @@ def undo_face_merge(mid: int, user: Writer, acl: Acl, db: Db) -> Ok: m = db.one("SELECT space FROM $r", r=R("face_merge", mid)) if not m: raise HTTPException(404, "not found") - acl.need(m["space"], "editor") + acl.need(m["space"], "curate") with domain_errors(): facemod.undo(db, mid) auth.audit(db, user.as_audit(), "face.merge.undo", f"face_merge:{mid}") @@ -218,7 +218,7 @@ def undo_face_merge(mid: int, user: Writer, acl: Acl, db: Db) -> Ok: @router.post("/faces/{fid}") def rename_face(fid: int, body: FaceRename, user: Writer, acl: Acl, db: Db) -> Ok: - _face_space(db, acl, fid, "editor") + _face_space(db, acl, fid, "curate") facemod.rename(db, fid, body.name) auth.audit(db, user.as_audit(), "face.rename", f"face:{fid}") return Ok() @@ -227,8 +227,8 @@ def rename_face(fid: int, body: FaceRename, user: Writer, acl: Acl, db: Db) -> O @router.post("/faces/{fid}/merge") def merge_face(fid: int, body: FaceMerge, user: Writer, acl: Acl, db: Db) -> FaceMerged: """Merge this face into another (the same person).""" - _face_space(db, acl, fid, "editor") - _face_space(db, acl, body.into, "editor") + _face_space(db, acl, fid, "curate") + _face_space(db, acl, body.into, "curate") try: mid = facemod.merge(db, fid, body.into, user.email) except (ValueError, KeyError) as e: @@ -240,7 +240,7 @@ def merge_face(fid: int, body: FaceMerge, user: Writer, acl: Acl, db: Db) -> Fac @router.post("/faces/{fid}/speaker") def link_face_speaker(fid: int, body: FaceSpeaker, user: Writer, acl: Acl, db: Db) -> Ok: """Say whose voice goes with this face (null unlinks).""" - _face_space(db, acl, fid, "editor") + _face_space(db, acl, fid, "curate") with domain_errors(): facemod.link_speaker(db, fid, body.speaker) auth.audit(db, user.as_audit(), "face.speaker", f"face:{fid}", {"speaker": body.speaker}) @@ -250,7 +250,7 @@ def link_face_speaker(fid: int, body: FaceSpeaker, user: Writer, acl: Acl, db: D @router.post("/faces/{fid}/dismiss") def dismiss_face_suggestion(fid: int, body: FaceDismiss, user: Writer, acl: Acl, db: Db) -> Ok: """Drop a suggestion (`kind` face or speaker, with its id).""" - _face_space(db, acl, fid, "editor") + _face_space(db, acl, fid, "curate") facemod.dismiss(db, fid, body.kind or "face", body.id) return Ok() diff --git a/fastapi_backend/app/api/v1/routes/workflows.py b/fastapi_backend/app/api/v1/routes/workflows.py index 6e62c2c94..9b143a076 100644 --- a/fastapi_backend/app/api/v1/routes/workflows.py +++ b/fastapi_backend/app/api/v1/routes/workflows.py @@ -65,7 +65,7 @@ def try_workflow(body: WorkflowTryRequest, user: AdminWriter, acl: Acl, db: Db, if body.scope == "recording": if body.recording is None: raise HTTPException(400, "choose a recording to try it on") - acl.recording(body.recording, "editor") + acl.recording(body.recording, "process") else: spaces = [acl.namespace(n) for n in body.namespaces] if body.namespaces else sorted(store.space_names(db)) with domain_errors(): @@ -111,7 +111,7 @@ def create_workflow_version(wid: int, body: WorkflowVersionCreate, user: AdminWr @router.post("/{wid}/run") def run_workflow(wid: int, body: WorkflowRunRequest, user: Writer, acl: Acl, db: Db) -> JobQueued: """Run this workflow on one recording now, as a job (after anything its current job still has to do).""" - acl.recording(body.recording, "editor") + acl.recording(body.recording, "process") try: w = workflows.get(db, wid, body.version) except KeyError: diff --git a/fastapi_backend/app/domain/access.py b/fastapi_backend/app/domain/access.py index 981feacbe..9e3e778b2 100644 --- a/fastapi_backend/app/domain/access.py +++ b/fastapi_backend/app/domain/access.py @@ -268,8 +268,11 @@ def decide(db, rid, account, approve, by=None): def owners(db, space): - """The email addresses of a namespace's owners (members with the owner role; admins when it has none).""" - ids = db.values("SELECT VALUE account FROM membership WHERE space = $s AND role = 'owner'", s=space) + """The email addresses of a namespace's owners (members whose role has the publish permission; admins when it has + none).""" + from . import roles + + ids = roles.holders(db, space, "publish") cond = "id IN $ids" if ids else "admin = true" return db.values(f"SELECT VALUE email FROM account WHERE {cond} AND disabled != true", ids=[R("account", i) for i in ids]) diff --git a/fastapi_backend/app/domain/auth.py b/fastapi_backend/app/domain/auth.py index 52d3ba1b9..aedb3c7bf 100644 --- a/fastapi_backend/app/domain/auth.py +++ b/fastapi_backend/app/domain/auth.py @@ -450,12 +450,24 @@ def drop_token(db, tid): # ---------- roles ---------- def roles(db, user): - """{space id: role} for this person; admins own everything.""" + """{space id: role} for this person, as a built-in role (a custom role counts as its rank, roles.py); admins own + everything.""" + from . import roles as rl + + return {sid: rl.rank(perms) for sid, perms in permissions(db, user).items()} + + +def permissions(db, user): + """{space id: the permissions this person's role there has}; admins have all of them everywhere.""" + from . import roles as rl + if not user: return {} if user.get("admin"): - return {sid: "owner" for sid in db.values("SELECT VALUE record::id(id) FROM space")} - return {r["space"]: r["role"] for r in db.rows("SELECT space, role FROM membership WHERE account = $a", a=user["id"])} + return {sid: rl.ALL for sid in db.values("SELECT VALUE record::id(id) FROM space")} + rows = db.rows("SELECT space, role FROM membership WHERE account = $a", a=user["id"]) + table = rl.table(db) if any(r["role"] not in rl.BUILTIN for r in rows) else rl.BUILTIN + return {r["space"]: table[r["role"]] for r in rows if r["role"] in table} def allows(role_map, sid, need="viewer"): @@ -463,13 +475,16 @@ def allows(role_map, sid, need="viewer"): def set_role(db, uid, sid, role): + """Give someone a role in a namespace (built-in or custom), or take it away (None).""" + from . import roles as rl + rid = R("membership", f"{uid}-{sid}") if role is None: db.q("DELETE $r", r=rid) - elif role in ROLES: + elif rl.exists(db, role): db.q("UPSERT $r CONTENT $d", r=rid, d={"account": uid, "space": sid, "role": role}) else: - raise ValueError("role is viewer, editor or owner") + raise ValueError(f"there's no role called {role}") def members(db, sid): diff --git a/fastapi_backend/app/domain/ops_tools.py b/fastapi_backend/app/domain/ops_tools.py index 0beda9beb..67aa5ae11 100644 --- a/fastapi_backend/app/domain/ops_tools.py +++ b/fastapi_backend/app/domain/ops_tools.py @@ -11,7 +11,7 @@ from __future__ import annotations -from . import auth, blobs, convert, decide, feeds, jobs, links, llm, metadata, settings, setup, sources, store, uploads +from . import auth, blobs, convert, decide, feeds, jobs, links, llm, metadata, roles, settings, setup, sources, store, uploads R = store.R _S = {"type": "string"} @@ -110,7 +110,7 @@ "invite_person", "Add someone by email, optionally with a role in one namespace (viewer, editor or owner). Lens emails them a " "sign-in link when mail is set up; otherwise an admin sends one from Admin → People. No passwords.", - {"email": _S, "name": _S, "namespace": _S, "role": {"type": "string", "enum": ["viewer", "editor", "owner"]}}, + {"email": _S, "name": _S, "namespace": _S, "role": {"type": "string", "description": "viewer, editor, owner or a custom role"}}, ["email"], True, ), @@ -122,7 +122,7 @@ { "email": _S, "namespace": _S, - "role": {"type": "string", "enum": ["viewer", "editor", "owner", "none"]}, + "role": {"type": "string", "description": "viewer, editor, owner, a custom role, or none"}, "disabled": {"type": "boolean"}, }, ["email"], @@ -422,6 +422,8 @@ def t_invite_person(self, email, name=None, namespace=None, role=None): raise ValueError(f"{email} already has an account: change_person gives them a role") if namespace: _space(self.db, namespace) + if role and not roles.exists(self.db, role): + raise ValueError(f"there's no role called {role}") where = f" as {role or 'viewer'} of {namespace}" if namespace else "" args = store.clean({"email": email, "name": name, "namespace": namespace, "role": (role or "viewer") if namespace else None}) return self._change("invite_person", args, f"Invite {email}{where}") @@ -434,6 +436,8 @@ def t_change_person(self, email, namespace=None, role=None, disabled=None): raise ValueError("give a namespace and a role, or disabled") if namespace: _space(self.db, namespace) + if role and role != "none" and not roles.exists(self.db, role): + raise ValueError(f"there's no role called {role}") parts = [f"{'no role' if role == 'none' else role} in {namespace}"] if namespace and role else [] if disabled is not None: parts.append("disable the account" if disabled else "enable the account") diff --git a/fastapi_backend/app/domain/roles.py b/fastapi_backend/app/domain/roles.py new file mode 100644 index 000000000..102a3a433 --- /dev/null +++ b/fastapi_backend/app/domain/roles.py @@ -0,0 +1,175 @@ +"""Roles and their permissions (docs/access.md#roles-and-permissions). + +A role in a namespace is a set of permissions. Lens has three built-in roles, viewer, editor and owner, and admins +can add their own (a `role` row: name, label, description, permissions), given per namespace like the built-in ones +(the `membership` row holds the role's name). Built-in roles can't be changed, so existing access stays as it was. + +Every role can read. A custom role also counts as the largest built-in role whose permissions it has all of (its +rank: viewer, editor or owner), and the checks that still ask for a rank (most of a recording's pages) give it that +much. The checks that ask for a permission (importing, processing, curating, sharing, publishing, removing, people, +namespace settings) give it exactly what it holds. +""" + +from __future__ import annotations + +import re + +from . import store + +R = store.R + +# name: (the built-in role that first has it, what it allows) +PERMISSIONS = { + "read": ("viewer", "See, search, listen and chat; write your own notes"), + "edit": ("editor", "Edit transcripts, catalogue records, tags, fields, collections, and notes and comments for everyone"), + "import": ("editor", "Add recordings, documents and images: uploads, imports and RDF"), + "process": ("editor", "Reprocess, and run pipelines, workflows, routines and batches"), + "curate": ("editor", "Rename and merge speakers, faces, entities and topics; change the graph"), + "share": ("editor", "Make, list and revoke share links"), + "publish": ("owner", "Set access, open parts and featured; give permission on recordings; answer access requests"), + "remove": ("owner", "Delete recordings and move them to another namespace"), + "members": ("owner", "Give people roles in the namespace"), + "manage": ("owner", "Namespace settings: metadata profile, notifications, import hooks, IP groups, the assistant, vaults"), +} +RANKS = {"viewer": 1, "editor": 2, "owner": 3} +BUILTIN = {role: frozenset(p for p, (first, _) in PERMISSIONS.items() if RANKS[first] <= rank) for role, rank in RANKS.items()} +LABELS = {"viewer": "Viewer", "editor": "Editor", "owner": "Owner"} +DESCRIPTIONS = { + "viewer": "Reads everything in the namespace.", + "editor": "Reads, edits, imports, processes and curates.", + "owner": "Everything, including publishing, people and settings.", +} +NAME = re.compile(r"^[a-z][a-z0-9_-]{1,39}$") +ALL = frozenset(PERMISSIONS) + + +def minimum(perm): + """The built-in role that first holds a permission (its rank, for collection roles and rank checks).""" + return PERMISSIONS[perm][0] + + +def rank(perms): + """The largest built-in role whose permissions all of `perms` cover: viewer, editor or owner.""" + return next(r for r in ("owner", "editor", "viewer") if BUILTIN[r] <= perms or r == "viewer") + + +def custom(db): + """The custom roles: {name: row}.""" + rows = db.rows("SELECT record::id(id) AS name, label, description, permissions, created_at, updated_at FROM role") + return {r["name"]: r for r in rows} + + +def table(db): + """{role name: its permissions}, built-in and custom.""" + out = dict(BUILTIN) + for name, r in custom(db).items(): + out[name] = frozenset(r.get("permissions") or ()) | {"read"} + return out + + +def exists(db, name): + return name in BUILTIN or bool(db.one("SELECT VALUE id FROM $r", r=R("role", name))) + + +def listing(db): + """Every role, built-in first, with its permissions and how many people hold it.""" + held = {} + for r in db.values("SELECT VALUE role FROM membership"): + held[r] = held.get(r, 0) + 1 + out = [ + { + "name": n, + "label": LABELS[n], + "description": DESCRIPTIONS[n], + "permissions": sorted(BUILTIN[n], key=list(PERMISSIONS).index), + "builtin": True, + "rank": n, + "members": held.get(n, 0), + } + for n in RANKS + ] + for n, r in sorted(custom(db).items()): + perms = frozenset(r.get("permissions") or ()) | {"read"} + out.append( + { + "name": n, + "label": r.get("label") or n, + "description": r.get("description") or "", + "permissions": sorted(perms, key=list(PERMISSIONS).index), + "builtin": False, + "rank": rank(perms), + "members": held.get(n, 0), + } + ) + return out + + +def _perms(permissions): + perms = set(permissions or ()) + unknown = perms - ALL + if unknown: + raise ValueError(f"unknown permissions: {', '.join(sorted(unknown))}; they are {', '.join(PERMISSIONS)}") + return sorted(perms | {"read"}, key=list(PERMISSIONS).index) + + +def _label(label, name): + label = " ".join((label or "").split()) or name.replace("-", " ").replace("_", " ").capitalize() + if len(label) > 60: + raise ValueError("a role's label has at most 60 characters") + return label + + +def create(db, name, permissions, label=None, description=None): + name = (name or "").strip().lower() + if not NAME.match(name): + raise ValueError("a role's name is 2 to 40 lowercase letters, digits, - and _, starting with a letter") + if name in BUILTIN or name == "admin" or exists(db, name): + raise ValueError(f"there's already a role called {name}") + t = store.now() + db.q( + "CREATE $r CONTENT $d", + r=R("role", name), + d={ + "label": _label(label, name), + "description": (description or "").strip()[:300], + "permissions": _perms(permissions), + "created_at": t, + "updated_at": t, + }, + ) + return name + + +def update(db, name, permissions=None, label=None, description=None): + """Change a custom role; everyone holding it gets the change at once. Built-in roles can't change.""" + if name in BUILTIN: + raise ValueError("built-in roles can't be changed; make a custom role instead") + if not db.one("SELECT VALUE id FROM $r", r=R("role", name)): + raise KeyError(name) + patch = store.clean( + { + "permissions": _perms(permissions) if permissions is not None else None, + "label": _label(label, name) if label is not None else None, + "description": description.strip()[:300] if description is not None else None, + } + ) + db.q("UPDATE $r MERGE $p", r=R("role", name), p={**patch, "updated_at": store.now()}) + + +def delete(db, name): + """Delete a custom role nobody holds (ValueError otherwise: give them another role first).""" + if name in BUILTIN: + raise ValueError("built-in roles can't be deleted") + if not db.one("SELECT VALUE id FROM $r", r=R("role", name)): + raise KeyError(name) + n = len(db.values("SELECT VALUE id FROM membership WHERE role = $n", n=name)) + if n: + raise ValueError(f"{n} {'person holds' if n == 1 else 'people hold'} this role: give them another one first") + db.q("DELETE $r", r=R("role", name)) + + +def holders(db, sid, perm): + """The accounts whose role in namespace `sid` has permission `perm` (admins aside).""" + t = table(db) + rows = db.rows("SELECT account, role FROM membership WHERE space = $s", s=sid) + return [r["account"] for r in rows if perm in t.get(r["role"], frozenset())] diff --git a/fastapi_backend/app/domain/store.py b/fastapi_backend/app/domain/store.py index 2478bf383..6664ffa7a 100644 --- a/fastapi_backend/app/domain/store.py +++ b/fastapi_backend/app/domain/store.py @@ -1126,6 +1126,7 @@ def close(self): "DEFINE TABLE IF NOT EXISTS data_key SCHEMALESS", "DEFINE TABLE IF NOT EXISTS account SCHEMALESS", "DEFINE INDEX IF NOT EXISTS account_email ON account FIELDS email UNIQUE", + "DEFINE TABLE IF NOT EXISTS role SCHEMALESS", # custom roles (roles.py), keyed by name "DEFINE TABLE IF NOT EXISTS membership SCHEMALESS", "DEFINE INDEX IF NOT EXISTS membership_account ON membership FIELDS account", "DEFINE INDEX IF NOT EXISTS membership_space ON membership FIELDS space", diff --git a/fastapi_backend/app/schemas/auth.py b/fastapi_backend/app/schemas/auth.py index 84bcd677d..29ed6fcc2 100644 --- a/fastapi_backend/app/schemas/auth.py +++ b/fastapi_backend/app/schemas/auth.py @@ -51,7 +51,10 @@ class TokenPair(ResponseModel): class Me(ResponseModel): user: UserPublic - roles: dict[str, Role] = Field(description="namespace name -> role") + roles: dict[str, Role] = Field(description="namespace name -> role, as a built-in role (a custom role counts as its rank)") + permissions: dict[str, list[str]] = Field( + default_factory=dict, description="namespace name -> what your role there allows (docs/access.md#roles-and-permissions)" + ) partial: list[str] = Field( default_factory=list, description="namespaces you have no role in but see some collections of (roles on collections)" ) diff --git a/fastapi_backend/app/schemas/users.py b/fastapi_backend/app/schemas/users.py index 5aca9692f..9cdab178d 100644 --- a/fastapi_backend/app/schemas/users.py +++ b/fastapi_backend/app/schemas/users.py @@ -2,14 +2,18 @@ from __future__ import annotations +from typing import Annotated + from pydantic import Field from app.schemas.auth import UserPublic -from app.schemas.common import RequestModel, ResponseModel, Role +from app.schemas.common import RequestModel, ResponseModel + +RoleName = Annotated[str, Field(min_length=1, max_length=40, description="viewer, editor, owner or a custom role's name")] class UserWithRoles(UserPublic): - roles: dict[str, Role] = Field(default_factory=dict, description="namespace name -> role") + roles: dict[str, str] = Field(default_factory=dict, description="namespace name -> role (built-in or custom)") passkeys: int = Field(0, description="how many passkeys they have") password: bool = Field(False, description="whether they have a password") @@ -30,7 +34,7 @@ class UserUpdate(RequestModel): class Member(ResponseModel): account: int - role: Role + role: str email: str | None = None name: str | None = None @@ -40,4 +44,38 @@ class MemberSet(RequestModel): email: str | None = None account: int | None = None - role: Role | None = None + role: RoleName | None = None + + +class RolePermission(ResponseModel): + name: str + label: str + first: str = Field(description="the built-in role that first has it") + + +class RoleOut(ResponseModel): + name: str + label: str + description: str = "" + permissions: list[str] + builtin: bool + rank: str = Field(description="the largest built-in role it covers; the checks that ask for a rank give it that much") + members: int = Field(0, description="how many people hold it, across namespaces") + + +class Roles(ResponseModel): + permissions: list[RolePermission] + roles: list[RoleOut] + + +class RoleCreate(RequestModel): + name: str = Field(description="2 to 40 lowercase letters, digits, - and _; can't change later") + label: str | None = None + description: str | None = None + permissions: list[str] = Field(default_factory=list, description="read is always included") + + +class RoleUpdate(RequestModel): + label: str | None = None + description: str | None = None + permissions: list[str] | None = None diff --git a/fastapi_backend/tests/api/test_roles.py b/fastapi_backend/tests/api/test_roles.py new file mode 100644 index 000000000..dbc5e4f42 --- /dev/null +++ b/fastapi_backend/tests/api/test_roles.py @@ -0,0 +1,109 @@ +"""Roles with permissions: the built-in viewer, editor and owner, custom roles admins make, and what each lets +people do in a namespace (docs/access.md#roles-and-permissions).""" + +from __future__ import annotations + +from app.domain import roles, store +from tests.helpers import login, make_user, seed + + +def test_builtin_roles_keep_their_meaning(): + assert roles.BUILTIN["viewer"] == {"read"} + assert roles.BUILTIN["editor"] == {"read", "edit", "import", "process", "curate", "share"} + assert roles.BUILTIN["owner"] == roles.ALL + assert [roles.rank(roles.BUILTIN[r]) for r in ("viewer", "editor", "owner")] == ["viewer", "editor", "owner"] + assert roles.rank(frozenset({"read", "import"})) == "viewer" + assert roles.rank(roles.BUILTIN["editor"] | {"members"}) == "editor" + + +def test_admins_make_custom_roles(client, new_client, db): + make_user(db, "root@x.io", "root password 1", admin=True) + make_user(db, "own@x.io", "owner password 1", roles={"pods": "owner"}) + h = login(client, "root@x.io", "root password 1") + ho = login(new_client(), "own@x.io", "owner password 1") + + listed = client.get("/api/v1/roles", headers=ho).json() # anyone signed in sees them, to give them + assert [r["name"] for r in listed["roles"]] == ["viewer", "editor", "owner"] + assert {p["name"] for p in listed["permissions"]} == set(roles.PERMISSIONS) + + body = {"name": "importer", "label": "Importer", "permissions": ["import"]} + assert client.post("/api/v1/roles", json=body, headers=ho).status_code == 403 # admins only + r = client.post("/api/v1/roles", json=body, headers=h) + assert r.status_code == 200, r.text + assert r.json() | {"members": 0} == { + "name": "importer", + "label": "Importer", + "description": "", + "permissions": ["read", "import"], # every role reads + "builtin": False, + "rank": "viewer", + "members": 0, + } + assert client.post("/api/v1/roles", json=body, headers=h).status_code == 400 # taken + assert client.post("/api/v1/roles", json={"name": "owner"}, headers=h).status_code == 400 + assert client.post("/api/v1/roles", json={"name": "Bad Name"}, headers=h).status_code == 400 + assert client.post("/api/v1/roles", json={"name": "x2", "permissions": ["fly"]}, headers=h).status_code == 400 + assert client.patch("/api/v1/roles/editor", json={"permissions": []}, headers=h).status_code == 400 # built-in + assert client.patch("/api/v1/roles/nope", json={"label": "x"}, headers=h).status_code == 404 + audit = {a["action"] for a in client.get("/api/v1/audit", headers=h).json()} + assert "role.create" in audit + + +def test_custom_roles_allow_exactly_their_permissions(client, new_client, db, cfg, folder): + a, _, _ = seed(db, cfg, folder) + make_user(db, "root@x.io", "root password 1", admin=True) + imp = make_user(db, "imp@x.io", "importer password 1") + h = login(client, "root@x.io", "root password 1") + assert client.post("/api/v1/roles", json={"name": "importer", "permissions": ["import"]}, headers=h).status_code == 200 + assert client.put("/api/v1/namespaces/pods/members", json={"account": imp, "role": "importer"}, headers=h).status_code == 200 + hi = login(new_client(), "imp@x.io", "importer password 1") + + me = client.get("/api/v1/auth/me", headers=hi).json() + assert me["roles"] == {"pods": "viewer"} and me["permissions"] == {"pods": ["import", "read"]} + assert client.get(f"/api/v1/recordings/{a}", headers=hi).status_code == 200 # reads + up = {"filename": "talk.wav", "size": 10, "namespace": "pods"} + assert client.post("/api/v1/uploads", json=up, headers=hi).status_code == 201 # imports + assert client.patch(f"/api/v1/recordings/{a}", json={"title": "x"}, headers=hi).status_code == 403 # doesn't edit + assert client.post(f"/api/v1/recordings/{a}/share", json={}, headers=hi).status_code == 403 # nor share + assert client.get("/api/v1/namespaces/pods/notifications", headers=hi).status_code == 403 # nor manage + assert client.get("/api/v1/namespaces/calls/members", headers=hi).status_code == 404 # elsewhere: nothing + + # a change to the role holds for everyone with it, at once + r = client.patch("/api/v1/roles/importer", json={"permissions": ["import", "edit", "share"]}, headers=h) + assert r.status_code == 200 and r.json()["members"] == 1 + assert client.patch(f"/api/v1/recordings/{a}", json={"title": "Edited"}, headers=hi).status_code == 200 + assert client.delete(f"/api/v1/recordings/{a}", headers=hi).status_code == 403 # removing is still the owners' + + # a role somebody holds can't go + assert client.delete("/api/v1/roles/importer", headers=h).status_code == 409 + assert client.put("/api/v1/namespaces/pods/members", json={"account": imp, "role": None}, headers=h).status_code == 200 + assert client.delete("/api/v1/roles/importer", headers=h).status_code == 200 + assert client.put("/api/v1/namespaces/pods/members", json={"account": imp, "role": "importer"}, headers=h).status_code == 400 + + +def test_people_managers_give_only_what_they_have(client, new_client, db): + make_user(db, "root@x.io", "root password 1", admin=True) + mgr = make_user(db, "mgr@x.io", "manager password 1") + own = make_user(db, "own@x.io", "owner password 1", roles={"pods": "owner"}) + vi = make_user(db, "vi@x.io", "viewer password 1") + h = login(client, "root@x.io", "root password 1") + assert client.post("/api/v1/roles", json={"name": "people", "permissions": ["members"]}, headers=h).status_code == 200 + assert client.put("/api/v1/namespaces/pods/members", json={"account": mgr, "role": "people"}, headers=h).status_code == 200 + hm = login(new_client(), "mgr@x.io", "manager password 1") + + assert {m["email"]: m["role"] for m in client.get("/api/v1/namespaces/pods/members", headers=hm).json()} == { + "mgr@x.io": "people", + "own@x.io": "owner", + } + put = "/api/v1/namespaces/pods/members" + assert client.put(put, json={"account": vi, "role": "viewer"}, headers=hm).status_code == 200 + assert client.put(put, json={"account": vi, "role": "editor"}, headers=hm).status_code == 403 # more than theirs + assert client.put(put, json={"account": mgr, "role": "owner"}, headers=hm).status_code == 403 # no promoting yourself + assert client.put(put, json={"account": own, "role": None}, headers=hm).status_code == 403 # nor taking an owner out + assert client.put(put, json={"account": vi, "role": None}, headers=hm).status_code == 200 + # owners hold everything, so they still give any role, custom ones included + ho = login(new_client(), "own@x.io", "owner password 1") + assert client.put(put, json={"account": vi, "role": "people"}, headers=ho).status_code == 200 + people = {p["email"]: p["roles"] for p in client.get("/api/v1/users", headers=h).json()} + assert people["vi@x.io"] == {"pods": "people"} + assert set(roles.holders(db, store.ns_id(db, "pods"), "members")) == {mgr, own, vi} diff --git a/fastapi_backend/tests/api/test_users.py b/fastapi_backend/tests/api/test_users.py index 7f5d8aa09..68870dbf4 100644 --- a/fastapi_backend/tests/api/test_users.py +++ b/fastapi_backend/tests/api/test_users.py @@ -53,7 +53,7 @@ def test_owners_manage_members(client, new_client, db): assert client.put("/api/v1/namespaces/pods/members", json={"email": "VI@x.io", "role": "viewer"}, headers=h).status_code == 200 assert client.put("/api/v1/namespaces/pods/members", json={"account": ed, "role": "owner"}, headers=h).status_code == 200 assert client.put("/api/v1/namespaces/pods/members", json={"email": "ghost@x.io", "role": "viewer"}, headers=h).status_code == 404 - assert client.put("/api/v1/namespaces/pods/members", json={"account": vi, "role": "admin"}, headers=h).status_code == 422 + assert client.put("/api/v1/namespaces/pods/members", json={"account": vi, "role": "admin"}, headers=h).status_code == 400 assert client.put("/api/v1/namespaces/calls/members", json={"account": vi, "role": "viewer"}, headers=h).status_code == 404 members = {m["email"]: m["role"] for m in client.get("/api/v1/namespaces/pods/members", headers=h).json()} assert members == {"own@x.io": "owner", "ed@x.io": "owner", "vi@x.io": "viewer"} diff --git a/nextjs-frontend/app/(app)/admin/roles/page.tsx b/nextjs-frontend/app/(app)/admin/roles/page.tsx new file mode 100644 index 000000000..2314414f0 --- /dev/null +++ b/nextjs-frontend/app/(app)/admin/roles/page.tsx @@ -0,0 +1,10 @@ +import type { Metadata } from "next"; + +import { RolesPage } from "@/components/admin/roles"; + +export const metadata: Metadata = { title: "Roles" }; + +/** Roles and their permissions: the built-in ones and the custom ones admins make. */ +export default function AdminRolesPage() { + return ; +} diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index 01f082955..84f5d7bd8 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -470,6 +470,11 @@ export type { CreatePodcastErrors, CreatePodcastResponse, CreatePodcastResponses, + CreateRoleData, + CreateRoleError, + CreateRoleErrors, + CreateRoleResponse, + CreateRoleResponses, CreateRoutineData, CreateRoutineError, CreateRoutineErrors, @@ -710,6 +715,11 @@ export type { DeleteRemoteBackupErrors, DeleteRemoteBackupResponse, DeleteRemoteBackupResponses, + DeleteRoleData, + DeleteRoleError, + DeleteRoleErrors, + DeleteRoleResponse, + DeleteRoleResponses, DeleteRoutineData, DeleteRoutineError, DeleteRoutineErrors, @@ -1734,6 +1744,9 @@ export type { ListRecordingsErrors, ListRecordingsResponse, ListRecordingsResponses, + ListRolesData, + ListRolesResponse, + ListRolesResponses, ListRoutinesData, ListRoutinesResponse, ListRoutinesResponses, @@ -2460,6 +2473,11 @@ export type { RevokeTokenErrors, RevokeTokenResponse, RevokeTokenResponses, + RoleCreate, + RoleOut, + RolePermission, + Roles, + RoleUpdate, RollbackAsk, RotateNotifySecretData, RotateNotifySecretError, @@ -3128,6 +3146,11 @@ export type { UpdateRecordingMetadataResponses, UpdateRecordingResponse, UpdateRecordingResponses, + UpdateRoleData, + UpdateRoleError, + UpdateRoleErrors, + UpdateRoleResponse, + UpdateRoleResponses, UpdateRoutineData, UpdateRoutineError, UpdateRoutineErrors, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index d2e7362ef..53880327b 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -203,6 +203,9 @@ import type { CreatePodcastData, CreatePodcastErrors, CreatePodcastResponses, + CreateRoleData, + CreateRoleErrors, + CreateRoleResponses, CreateRoutineData, CreateRoutineErrors, CreateRoutineResponses, @@ -343,6 +346,9 @@ import type { DeleteRemoteBackupData, DeleteRemoteBackupErrors, DeleteRemoteBackupResponses, + DeleteRoleData, + DeleteRoleErrors, + DeleteRoleResponses, DeleteRoutineData, DeleteRoutineErrors, DeleteRoutineResponses, @@ -885,6 +891,8 @@ import type { ListRecordingsData, ListRecordingsErrors, ListRecordingsResponses, + ListRolesData, + ListRolesResponses, ListRoutinesData, ListRoutinesResponses, ListRunsData, @@ -1529,6 +1537,9 @@ import type { UpdateRecordingMetadataErrors, UpdateRecordingMetadataResponses, UpdateRecordingResponses, + UpdateRoleData, + UpdateRoleErrors, + UpdateRoleResponses, UpdateRoutineData, UpdateRoutineErrors, UpdateRoutineResponses, @@ -2379,7 +2390,9 @@ export class Users { /** * Set Member * - * Give someone a role in this namespace, change it, or (role null) remove them. Owners only. + * Give someone a role in this namespace (built-in or custom), change it, or (role null) remove them. Needs the + * members permission; someone who isn't an admin gives only roles they hold every permission of, and changes only + * people whose role they hold every permission of. */ public static setMember( options: Options, @@ -2393,6 +2406,71 @@ export class Users { }, }); } + + /** + * List Roles + * + * The permissions a role can have, and every role: viewer, editor and owner, then the custom ones. + */ + public static listRoles( + options?: Options, + ): RequestResult { + return (options?.client ?? client).get({ + url: "/api/v1/roles", + ...options, + }); + } + + /** + * Create Role + * + * A custom role (admins), given per namespace like the built-in ones. Audited as `role.create`. + */ + public static createRole( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/roles", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } + + /** + * Delete Role + * + * Delete a custom role. Refused (409) while anyone holds it. Audited as `role.delete`. + */ + public static deleteRole( + options: Options, + ): RequestResult { + return (options.client ?? client).delete({ + url: "/api/v1/roles/{name}", + ...options, + }); + } + + /** + * Update Role + * + * Change a custom role's label, description or permissions; everyone holding it gets the change at once. + * Built-in roles can't change. Audited as `role.update`. + */ + public static updateRole( + options: Options, + ): RequestResult { + return (options.client ?? client).patch({ + url: "/api/v1/roles/{name}", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } } export class Oauth { diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index 1ab7cf551..c901267bd 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -8265,11 +8265,19 @@ export type Me = { /** * Roles * - * namespace name -> role + * namespace name -> role, as a built-in role (a custom role counts as its rank) */ roles: { [key: string]: "viewer" | "editor" | "owner"; }; + /** + * Permissions + * + * namespace name -> what your role there allows (docs/access.md#roles-and-permissions) + */ + permissions?: { + [key: string]: Array; + }; /** * Partial * @@ -8316,7 +8324,7 @@ export type Member = { /** * Role */ - role: "viewer" | "editor" | "owner"; + role: string; /** * Email */ @@ -8345,7 +8353,7 @@ export type MemberSet = { /** * Role */ - role?: "viewer" | "editor" | "owner" | null; + role?: string | null; }; /** @@ -13932,6 +13940,125 @@ export type Reviewed = { [key: string]: unknown; }; +/** + * RoleCreate + */ +export type RoleCreate = { + /** + * Name + * + * 2 to 40 lowercase letters, digits, - and _; can't change later + */ + name: string; + /** + * Label + */ + label?: string | null; + /** + * Description + */ + description?: string | null; + /** + * Permissions + * + * read is always included + */ + permissions?: Array; +}; + +/** + * RoleOut + */ +export type RoleOut = { + /** + * Name + */ + name: string; + /** + * Label + */ + label: string; + /** + * Description + */ + description?: string; + /** + * Permissions + */ + permissions: Array; + /** + * Builtin + */ + builtin: boolean; + /** + * Rank + * + * the largest built-in role it covers; the checks that ask for a rank give it that much + */ + rank: string; + /** + * Members + * + * how many people hold it, across namespaces + */ + members?: number; + [key: string]: unknown; +}; + +/** + * RolePermission + */ +export type RolePermission = { + /** + * Name + */ + name: string; + /** + * Label + */ + label: string; + /** + * First + * + * the built-in role that first has it + */ + first: string; + [key: string]: unknown; +}; + +/** + * RoleUpdate + */ +export type RoleUpdate = { + /** + * Label + */ + label?: string | null; + /** + * Description + */ + description?: string | null; + /** + * Permissions + */ + permissions?: Array | null; +}; + +/** + * Roles + */ +export type Roles = { + /** + * Permissions + */ + permissions: Array; + /** + * Roles + */ + roles: Array; + [key: string]: unknown; +}; + /** * RollbackAsk */ @@ -18768,10 +18895,10 @@ export type UserWithRoles = { /** * Roles * - * namespace name -> role + * namespace name -> role (built-in or custom) */ roles?: { - [key: string]: "viewer" | "editor" | "owner"; + [key: string]: string; }; /** * Passkeys @@ -21341,6 +21468,107 @@ export type SetMemberResponses = { export type SetMemberResponse = SetMemberResponses[keyof SetMemberResponses]; +export type ListRolesData = { + body?: never; + path?: never; + query?: never; + url: "/api/v1/roles"; +}; + +export type ListRolesResponses = { + /** + * Successful Response + */ + 200: Roles; +}; + +export type ListRolesResponse = ListRolesResponses[keyof ListRolesResponses]; + +export type CreateRoleData = { + body: RoleCreate; + path?: never; + query?: never; + url: "/api/v1/roles"; +}; + +export type CreateRoleErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type CreateRoleError = CreateRoleErrors[keyof CreateRoleErrors]; + +export type CreateRoleResponses = { + /** + * Successful Response + */ + 200: RoleOut; +}; + +export type CreateRoleResponse = CreateRoleResponses[keyof CreateRoleResponses]; + +export type DeleteRoleData = { + body?: never; + path: { + /** + * Name + */ + name: string; + }; + query?: never; + url: "/api/v1/roles/{name}"; +}; + +export type DeleteRoleErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type DeleteRoleError = DeleteRoleErrors[keyof DeleteRoleErrors]; + +export type DeleteRoleResponses = { + /** + * Successful Response + */ + 200: Ok; +}; + +export type DeleteRoleResponse = DeleteRoleResponses[keyof DeleteRoleResponses]; + +export type UpdateRoleData = { + body: RoleUpdate; + path: { + /** + * Name + */ + name: string; + }; + query?: never; + url: "/api/v1/roles/{name}"; +}; + +export type UpdateRoleErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type UpdateRoleError = UpdateRoleErrors[keyof UpdateRoleErrors]; + +export type UpdateRoleResponses = { + /** + * Successful Response + */ + 200: RoleOut; +}; + +export type UpdateRoleResponse = UpdateRoleResponses[keyof UpdateRoleResponses]; + export type GetSettingsData = { body?: never; path?: never; diff --git a/nextjs-frontend/components/admin/admin-frame.tsx b/nextjs-frontend/components/admin/admin-frame.tsx index d7da502fd..d4b1590d2 100644 --- a/nextjs-frontend/components/admin/admin-frame.tsx +++ b/nextjs-frontend/components/admin/admin-frame.tsx @@ -12,7 +12,7 @@ import { Tabs } from "@/components/ui/tabs"; import { data, useApiClient } from "@/lib/api/browser"; import { useArchive } from "@/lib/hooks/session"; -export type AdminTab = "people" | "namespaces" | "audit" | "health"; +export type AdminTab = "people" | "roles" | "namespaces" | "audit" | "health"; /** Everyone, for admins (the role matrix, audit names). */ export function usePeople() { @@ -26,6 +26,19 @@ export function usePeople() { }); } +/** Every role (viewer, editor, owner, then custom ones) and the permissions they can have. */ +export function useRoles() { + const client = useApiClient(); + const q = useQuery({ queryKey: ["roles"], queryFn: () => data(Users.listRoles({ client })), staleTime: 30_000 }); + const list = q.data?.roles ?? [ + { name: "viewer", label: "Viewer" }, + { name: "editor", label: "Editor" }, + { name: "owner", label: "Owner" }, + ]; + const labels = Object.fromEntries(list.map((r) => [r.name, r.label])); + return { ...q, names: list.map((r) => r.name), labels }; +} + /** * Admin is one sub-nav (Admin AD1–AD5): People, Namespaces, Audit log, System health. Namespace owners who aren't * admins see only their namespaces' members. @@ -82,6 +95,7 @@ export function AdminFrame({ count: people.data?.length, href: "/admin/people", }, + { value: "roles", label: "Roles", href: "/admin/roles" }, { value: "namespaces", label: "Namespaces", href: "/admin/namespaces" }, { value: "audit", label: "Audit log", href: "/admin/audit" }, { value: "health", label: "System health", href: "/admin/health" }, diff --git a/nextjs-frontend/components/admin/namespaces.tsx b/nextjs-frontend/components/admin/namespaces.tsx index 6ec48154e..34d70fe71 100644 --- a/nextjs-frontend/components/admin/namespaces.tsx +++ b/nextjs-frontend/components/admin/namespaces.tsx @@ -9,7 +9,7 @@ import { Namespaces, Pipelines, Users } from "@/app/openapi-client"; import { IpGroupsSection } from "@/components/access/ip-groups"; import { NsAssistantSection } from "@/components/assistant/ns-assistant-section"; import { ImportHooksSection } from "@/components/imports/import-hooks"; -import { AdminFrame, usePeople } from "@/components/admin/admin-frame"; +import { AdminFrame, usePeople, useRoles } from "@/components/admin/admin-frame"; import { roleLabel, type Role } from "@/components/admin/people-model"; import { ActivityPanel, BudgetPanel, CostCell, useBudgets, useCosts } from "@/components/costs/costs"; import { isUnreachable } from "@/components/errors/error-states"; @@ -101,7 +101,7 @@ export function NamespacesPage() { - + ))} @@ -211,6 +211,7 @@ export function NamespaceDetail({ ns }: { ns: string }) { const { namespaces, admin, can, me } = useArchive(); const known = namespaces.find((n) => n.name === ns); const isOwner = can("owner", ns); + const roles = useRoles(); const members = useQuery({ queryKey: ["members", ns], queryFn: () => data(Users.listMembers({ client, path: { name: ns } })), @@ -362,9 +363,9 @@ export function NamespaceDetail({ ns }: { ns: string }) { id={f.id} value={role} onChange={(e) => setRole(e.target.value as Role)} - options={["viewer", "editor", "owner"].map((r) => ({ + options={roles.names.map((r) => ({ value: r, - label: roleLabel(r as Role), + label: roleLabel(r, roles.labels), }))} /> )} @@ -440,9 +441,9 @@ export function NamespaceDetail({ ns }: { ns: string }) { self ? "bg-surface text-fg-muted" : "bg-background text-fg", )} > - {["viewer", "editor", "owner"].map((r) => ( + {roles.names.map((r) => ( ))} diff --git a/nextjs-frontend/components/admin/people-model.ts b/nextjs-frontend/components/admin/people-model.ts index 32ce49f93..9faf87f6d 100644 --- a/nextjs-frontend/components/admin/people-model.ts +++ b/nextjs-frontend/components/admin/people-model.ts @@ -1,7 +1,8 @@ /** * People (Admin AD1–AD2): pending changes in the role matrix, and temporary passwords that are easy to read out. */ -export type Role = "viewer" | "editor" | "owner"; +/** viewer, editor, owner, or a custom role's name (Admin › Roles). */ +export type Role = string; export type Person = { id: number; email: string; @@ -20,16 +21,16 @@ export type Person = { export type Pending = { uid: number; ns: string; role: Role | null } | { uid: number; admin: boolean }; export const cellKey = (uid: number, col: string) => `${uid}:${col}`; -export function roleLabel(r: Role | null | undefined): string { - return r ? r[0].toUpperCase() + r.slice(1) : "—"; +export function roleLabel(r: Role | null | undefined, labels?: Record): string { + return r ? (labels?.[r] ?? r[0].toUpperCase() + r.slice(1)) : "—"; } /** "Sam Whitaker · customer-calls — → Viewer", "Lena Vogel · platform admin off → on". */ -export function describePending(p: Pending, people: Person[]): string { +export function describePending(p: Pending, people: Person[], labels?: Record): string { const who = people.find((x) => x.id === p.uid); const name = who?.name || who?.email || `Account ${p.uid}`; if ("admin" in p) return `${name} · platform admin ${p.admin ? "off → on" : "on → off"}`; - return `${name} · ${p.ns} ${roleLabel(who?.roles?.[p.ns])} → ${roleLabel(p.role)}`; + return `${name} · ${p.ns} ${roleLabel(who?.roles?.[p.ns], labels)} → ${roleLabel(p.role, labels)}`; } /** Applies a cell edit to the pending map: back to the saved value removes it. */ diff --git a/nextjs-frontend/components/admin/people.tsx b/nextjs-frontend/components/admin/people.tsx index a5888677d..b0d442811 100644 --- a/nextjs-frontend/components/admin/people.tsx +++ b/nextjs-frontend/components/admin/people.tsx @@ -5,7 +5,7 @@ import { ChevronDown, Ellipsis, RefreshCw, UserPlus, Users as UsersIcon } from " import { useRef, useState, type KeyboardEvent } from "react"; import { Auth, Users } from "@/app/openapi-client"; -import { AdminFrame, usePeople } from "@/components/admin/admin-frame"; +import { AdminFrame, usePeople, useRoles } from "@/components/admin/admin-frame"; import { cellKey, describePending, @@ -30,8 +30,6 @@ import { count, nameFromEmail, shortDate } from "@/lib/format"; import { useArchive } from "@/lib/hooks/session"; import { cn } from "@/lib/utils"; -const ROLES: (Role | "")[] = ["", "viewer", "editor", "owner"]; - type Dialogs = | { kind: "create" } | { kind: "reset"; person: Person } @@ -47,6 +45,7 @@ export function PeoplePage() { const toast = useToast(); const { me, namespaces } = useArchive(); const people = usePeople(); + const roles = useRoles(); const [pending, setPending] = useState>(new Map()); const [dialog, setDialog] = useState(null); const status = useQuery({ queryKey: ["auth-status"], queryFn: () => data(Auth.status({ client })) }); @@ -156,6 +155,8 @@ export function PeoplePage() { describePending(c, list)) + .map((c) => describePending(c, list, roles.labels)) .join("; ")} {changes.length > 2 ? ` and ${changes.length - 2} more` : ""} @@ -217,6 +218,8 @@ type Action = "reset" | "disable" | "enable" | "rename" | "link" | "passkeys" | function RoleGrid({ people, namespaces, + roles, + labels, pending, myId, passwords, @@ -225,6 +228,8 @@ function RoleGrid({ }: { people: Person[]; namespaces: string[]; + roles: string[]; + labels: Record; pending: Map; myId?: number; passwords?: boolean; @@ -408,9 +413,9 @@ function RoleGrid({ changed ? "border-blue bg-blue-surface" : "border-border bg-background", )} > - {ROLES.map((x) => ( + {["", ...roles].map((x) => ( ))} @@ -583,7 +588,8 @@ function CreateDialog({ passwords, onClose }: { passwords: boolean; onClose: () const [admin, setAdmin] = useState(false); const usePassword = passwords && withPassword; const [ns, setNs] = useState(topNs ?? namespaces[0]?.name ?? ""); - const [role, setRole] = useState<"none" | "viewer" | "editor" | "owner">("viewer"); + const roles = useRoles(); + const [role, setRole] = useState("viewer"); const shownName = name.trim() || nameFromEmail(email); const create = useMutation({ mutationFn: async () => { @@ -704,11 +710,9 @@ function CreateDialog({ passwords, onClose }: { passwords: boolean; onClose: () setLabel(e.target.value)} maxLength={60} autoFocus />} + + + {(f) => ( + setDescription(e.target.value)} maxLength={300} /> + )} + +
+ Permissions + {perms.map((p) => ( + + setChosen((s) => { + const n = new Set(s); + if (v) n.add(p.name); + else n.delete(p.name); + return n; + }) + } + label={ + <> + {p.name}{" "} + · {p.label} + + } + /> + ))} +
+