From 42b85d0d42baa1621dba799f471eb07b3999fe90 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sat, 10 Oct 2026 20:10:27 +0000 Subject: [PATCH] feat(users): email invitations and remove people for good Admins' sign-in links can be emailed as an invitation when mail is set up (?email=true; the web app asks for it). DELETE /users/{id} ends every way someone signs in, takes their roles and private things, keeps what they shared, and frees their email. The assistant gets list_people, invite_person and change_person, which always wait for approval. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_013CspHV36KRyiRJ9LsFqK53 --- CHANGELOG.md | 6 + docs/api.md | 2 + docs/assistant.md | 7 +- docs/authentication.md | 22 ++- fastapi_backend/app/api/v1/routes/passkeys.py | 18 ++- fastapi_backend/app/api/v1/routes/users.py | 27 +++- fastapi_backend/app/domain/ai_tools.py | 2 +- fastapi_backend/app/domain/auth.py | 56 ++++++- fastapi_backend/app/domain/ops_tools.py | 139 +++++++++++++++++- fastapi_backend/app/email.py | 31 ++++ .../app/email_templates/invite.html | 14 ++ fastapi_backend/app/schemas/auth.py | 1 + .../tests/api/test_setup_assistant.py | 35 +++++ fastapi_backend/tests/api/test_users.py | 78 ++++++++++ nextjs-frontend/app/openapi-client/index.ts | 5 + nextjs-frontend/app/openapi-client/sdk.gen.ts | 23 ++- .../app/openapi-client/types.gen.ts | 48 +++++- nextjs-frontend/components/admin/people.tsx | 105 +++++++++++-- nextjs-frontend/openapi.json | 69 ++++++++- threat-model.json | 8 + threat-model.md | 3 +- threat-model.yaml | 10 +- 22 files changed, 680 insertions(+), 29 deletions(-) create mode 100644 fastapi_backend/app/email_templates/invite.html diff --git a/CHANGELOG.md b/CHANGELOG.md index 5112764c6..92380eca1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version ## Unreleased +- **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 + can be invited again ([Authentication](docs/authentication.md#removing-someone)). The assistant gets `list_people`, + `invite_person` and `change_person`, which always wait for an admin's approval. + - **Install on Windows, or by double-clicking.** `install.ps1` installs Lens on Windows: it gets Python 3 if needed and opens the web installer, which installs Docker Desktop (and WSL) and runs Lens in it. Each release now carries launchers that need no terminal at all: **Install Lens.app** for macOS, **Install Lens.cmd** for Windows and diff --git a/docs/api.md b/docs/api.md index 8d862bc80..ba6613b07 100644 --- a/docs/api.md +++ b/docs/api.md @@ -118,6 +118,8 @@ server itself is at `/mcp`, outside `/api/v1` ([MCP server](mcp.md)). GET /api/v1/users POST /api/v1/users 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 ``` diff --git a/docs/assistant.md b/docs/assistant.md index 1ca8ebef2..aec9ac5da 100644 --- a/docs/assistant.md +++ b/docs/assistant.md @@ -178,11 +178,14 @@ Find the meeting, read it, and answer with three bullets: decisions, owners, dat Admins also get the server tools: `server_status` (what's set up and what's missing), `find_model_servers`, `read_settings` and `change_settings` (the processing and AI sections, not the server's hosts, cookies or tokens) and -`create_namespace`. In an ordinary conversation their changes are approval cards. In a **setup conversation** +`create_namespace`, and the people tools: `list_people`, `invite_person` (an account, optionally with a role in one +namespace; Lens emails the sign-in link when mail is set up) and `change_person` (a role in a namespace, or disabling +and enabling an account). Removing an account for good stays in the web app and the API. In an ordinary conversation +their changes are approval cards. In a **setup conversation** (`POST /api/v1/chats` with `"kind": "setup"`, or **Finish with the assistant** in the setup wizard once a model is connected) the admin has asked the assistant to set the server up, so it makes the changes itself and says what it changed. Every change is audited with `assistant` in its detail, and all of them stay changeable in Settings. -Turning telemetry on or off always asks first. +Turning telemetry on or off, inviting people and changing their access always ask first. ### Routine choices diff --git a/docs/authentication.md b/docs/authentication.md index bf7ba763b..9240f5438 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -16,7 +16,8 @@ no passwords on a fresh install (`auth.passwords` is off), so there is nothing t plain `http://` address other than localhost, or an IP address) the code alone makes the admin, still without a password; they sign in later with a passkey at the `https://` address, or with a sign-in link. * **Everyone else** gets a one-time **sign-in link** from an admin (People › Send a sign-in link, or - `lens users link them@example.com` on the server). Opening it adds a passkey on that device and signs them in; on an + `lens users link them@example.com` on the server). When mail is set up (Settings › Email), the web app also emails + it to them as an invitation (`POST /api/v1/users/{id}/signin-link?email=true`); either way the admin sees the link. Opening it adds a passkey on that device and signs them in; on an address browsers won't use passkeys on, the link alone signs them in. A link lasts three days and works once; making another stops the last. The token is in the link's `#fragment`, so it never reaches a server log. * **More devices**: Profile and sign-in › Add a passkey. Passkeys synced by a password manager or the device's cloud @@ -39,6 +40,22 @@ in). With passwords off, password sign-in, changes and resets answer 403. Passwo least 10 characters. Failed sign-ins are throttled per email and address (8 per 15 minutes). Unknown emails take as long to reject as wrong passwords; an account without a password matches none. +## Removing someone + +An admin can **disable** an account (People › Disable account, with Undo): the person is signed out everywhere and +nothing else changes. **Remove for good** (People › Remove for good…, `DELETE /api/v1/users/{id}`) can't be undone: + +* every way they sign in ends at once: sessions, passkeys, sign-in links, connected accounts, API tokens, apps they + gave access to, IIIF tokens; +* every role they had goes: namespace roles, collection roles, permission on recordings, access requests; +* what only they could see goes: their chats, their own notes and highlights, saved views and collections only they + used, and unfinished uploads; +* what they shared stays under their name: notes and views for everyone, comments, edits, the audit log. + +Their email can then be invited again as a new account, which inherits nothing. Admins can't remove themselves or the +account Matterbridge answers as (choose another first); when their passkeys are the only way into a vault, removing +them is refused unless the admin agrees to lose its files (`lose_vaults=true`). Audited as `user.remove`. + ## Signing in with another account: Google, GitHub, Microsoft, OpenID Connect Admins add providers in **Settings › Sign-in › Sign in with another account**: Google, GitHub, Microsoft, or any @@ -101,7 +118,8 @@ Sign out ──► POST /api/v1/auth/logout (ends the session on the API too) | `POST /api/v1/auth/signin-link/use` | sign in with a sign-in link alone, without adding a passkey | | `POST /api/v1/auth/signin-link/lost` | email a sign-in link; answers the same for unknown addresses | | `GET` · `POST /api/v1/auth/passkeys` (and `/options`) · `PATCH` · `DELETE /api/v1/auth/passkeys/{id}` | your passkeys: list, add, rename, remove (not the last); audited as `passkey.add` and `passkey.remove` | -| `POST /api/v1/users/{id}/signin-link` · `DELETE /api/v1/users/{id}/passkeys` | admins: a sign-in link for someone; remove all their passkeys | +| `POST /api/v1/users/{id}/signin-link` · `DELETE /api/v1/users/{id}/passkeys` | admins: a sign-in link for someone (`?email=true` emails it to them when mail is set up); remove all their passkeys | +| `DELETE /api/v1/users/{id}` | admins: [remove someone for good](#removing-someone) | | `GET /api/v1/auth/external` | the outside accounts people can sign in with (for the sign-in page) | | `POST /api/v1/auth/external/{name}/start` · `/connect` | the provider's sign-in page to open (connect: signed in, adds it to your account) | | `GET /api/v1/auth/external/{name}/callback` | where the provider comes back; ends on the web app's `/external-signin` | diff --git a/fastapi_backend/app/api/v1/routes/passkeys.py b/fastapi_backend/app/api/v1/routes/passkeys.py index 8dd26a796..636c3d5b9 100644 --- a/fastapi_backend/app/api/v1/routes/passkeys.py +++ b/fastapi_backend/app/api/v1/routes/passkeys.py @@ -15,7 +15,7 @@ from app.config import settings from app.core.security import create_access_token from app.domain import auth, external_login, passkeys -from app.email import app_url, send_signin_link_email +from app.email import app_url, mail_enabled, send_invite_email, send_signin_link_email from app.schemas.auth import ( ForgotPasswordRequest, LoginTicket, @@ -279,18 +279,24 @@ def remove_passkey(pid: str, user: Writer, request: Request, db: Db, cfg: Cfg) - # ---------- admins ---------- @people.post("/users/{uid}/signin-link") -def make_signin_link(uid: int, user: AdminWriter, request: Request, db: Db) -> SigninLink: +def make_signin_link( + uid: int, user: AdminWriter, request: Request, db: Db, cfg: Cfg, tasks: BackgroundTasks, email: bool = False +) -> SigninLink: """A one-time link for this person to add a passkey and sign in (a new person, or one who lost theirs). It lasts - three days; making another stops the last one. Share it privately. Audited as `user.signin_link`.""" + three days; making another stops the last one. Share it privately, or with email=true Lens emails it to them + when mail is set up (`emailed` says whether it did). Audited as `user.signin_link`.""" u = auth.active_account(db, uid) if not u: raise HTTPException(404, "not found (or disabled)") raw = passkeys.create_link(db, uid, by=user.email) auth.audit(db, user.as_audit(), "user.signin_link", f"account:{uid}") row = db.one("SELECT expires_at FROM $r", r=auth.R("signin_link", auth.sha(raw))) - return SigninLink( - url=passkeys.link_url(raw, web_origin(request) if request.headers.get("x-forwarded-host") else None), expires_at=row["expires_at"] - ) + url = passkeys.link_url(raw, web_origin(request) if request.headers.get("x-forwarded-host") else None) + emailed = email and mail_enabled(cfg) + if emailed: + mailed = url if request.headers.get("x-forwarded-host") else passkeys.link_url(raw, app_url(cfg)) + tasks.add_task(send_invite_email, cfg, u["email"], u.get("name"), user.name or user.email, mailed, passkeys.LINK_HOURS) + return SigninLink(url=url, expires_at=row["expires_at"], emailed=emailed) @people.delete("/users/{uid}/passkeys") diff --git a/fastapi_backend/app/api/v1/routes/users.py b/fastapi_backend/app/api/v1/routes/users.py index d878be1f0..3ade6c638 100644 --- a/fastapi_backend/app/api/v1/routes/users.py +++ b/fastapi_backend/app/api/v1/routes/users.py @@ -18,7 +18,8 @@ def list_users(user: AdminReader, db: Db) -> list[UserWithRoles]: """Every account, with its role in each namespace.""" people = db.rows( - "SELECT record::id(id) AS id, email, name, admin, disabled, created_at, last_login_at, pw != NONE AS password FROM account ORDER BY id" + "SELECT record::id(id) AS id, email, name, admin, disabled, created_at, last_login_at, pw != NONE AS password FROM account " + "WHERE removed_at = NONE ORDER BY id" ) keys: dict[int, int] = defaultdict(int) for a in db.values("SELECT VALUE account FROM passkey"): @@ -50,7 +51,8 @@ def update_user(uid: int, body: UserUpdate, user: AdminWriter, db: Db, cfg: Cfg) raise HTTPException(400, "passwords are turned off here; send a sign-in link instead") if uid == user.id and (body.admin is False or body.disabled): raise HTTPException(400, "you can't remove your own admin rights or disable yourself") - if not auth.get_account(db, uid): + target = auth.get_account(db, uid) + if not target or target.get("removed_at"): raise HTTPException(404, "not found") with domain_errors(): auth.update_account(db, uid, body.name, body.admin, body.disabled, body.password) @@ -58,6 +60,27 @@ def update_user(uid: int, body: UserUpdate, user: AdminWriter, db: Db, cfg: Cfg) return Ok() +@router.delete("/users/{uid}") +def remove_user(uid: int, user: AdminWriter, db: Db, cfg: Cfg, lose_vaults: bool = False) -> Ok: + """Remove someone for good (docs/authentication.md#removing-someone): their sign-ins, roles, permissions and + private things go; what they shared stays under their name, and their email can be invited again. Disabling + (PATCH) is the reversible way. Refused (409) for the account Matterbridge answers as, and when their passkeys are + the only way into a vault, unless lose_vaults=true. Audited as `user.remove`.""" + if uid == user.id: + raise HTTPException(400, "you can't remove yourself") + u = auth.get_account(db, uid) + if not u or u.get("removed_at"): + raise HTTPException(404, "not found") + if ((cfg.get("bridge") or {}).get("account") or "").strip().lower() == u["email"]: + raise HTTPException(409, "Matterbridge answers as this account: choose another one in Settings first") + try: + auth.remove_account(db, uid, lose_vaults) + except ValueError as e: + raise HTTPException(409, str(e)) from None + auth.audit(db, user.as_audit(), "user.remove", f"account:{uid}", {"email": u["email"]}) + return Ok() + + @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).""" diff --git a/fastapi_backend/app/domain/ai_tools.py b/fastapi_backend/app/domain/ai_tools.py index c41b2f824..c45a53c86 100644 --- a/fastapi_backend/app/domain/ai_tools.py +++ b/fastapi_backend/app/domain/ai_tools.py @@ -1088,7 +1088,7 @@ def _carry_out(db, cfg, a, user, editable, decision, base, admin, readable): result = run_extension(db, cfg, args, user, admin, box.readable, box) elif a["tool"] in ("save_extension", "switch_extension"): result = author_extension(db, a["tool"], args, user, admin, readable if readable is not None else editable, editable) - elif a["tool"] in ("change_settings", "create_namespace", "import_files"): + elif a["tool"] in ("change_settings", "create_namespace", "import_files", "invite_person", "change_person"): result = ops_tools.apply(db, cfg, base or cfg, a["tool"], args, user, editable, admin) elif a["tool"] == "forget_memory": sid = {v: k for k, v in store.space_names(db).items()}.get(args["namespace"]) diff --git a/fastapi_backend/app/domain/auth.py b/fastapi_backend/app/domain/auth.py index 93f486d23..b2660ad59 100644 --- a/fastapi_backend/app/domain/auth.py +++ b/fastapi_backend/app/domain/auth.py @@ -107,7 +107,9 @@ def public(u): def get_account(db, uid): - return db.one("SELECT record::id(id) AS id, email, name, admin, disabled, created_at, last_login_at, pw FROM $r", r=R("account", uid)) + return db.one( + "SELECT record::id(id) AS id, email, name, admin, disabled, created_at, last_login_at, pw, removed_at FROM $r", r=R("account", uid) + ) def find_account(db, email): @@ -154,6 +156,58 @@ def update_account(db, uid, name=None, admin=None, disabled=None, password=None) db.q("DELETE signin_link WHERE account = $a", a=uid) +def remove_account(db, uid, lose_vaults=False): + """Remove someone for good: every way they sign in (sessions, passkeys, sign-in links, connected accounts, API + tokens, apps they gave access to), every role and permission they had, and what only they could see (their chats, + their own notes, highlights, saved views and collections, unfinished uploads). What they shared stays (notes and + views for everyone, comments), under their name: the account is kept as a marker without an email, so their + address can be invited again. Refused (ValueError) when their passkeys are the only way into a vault, unless + `lose_vaults`.""" + from . import passkeys + + u = get_account(db, uid) + if not u or u.get("removed_at"): + raise KeyError(uid) + passkeys.remove_all(db, uid, lose_vaults) + for g in db.values("SELECT VALUE record::id(id) FROM oauth_grant WHERE account = $a", a=uid): + db.run(["DELETE oauth_token WHERE gid = $g", "DELETE $r"], g=g, r=R("oauth_grant", g)) + chats = db.values("SELECT VALUE record::id(id) FROM chat WHERE account = $a", a=uid) + db.run( + [ + "DELETE chat_message WHERE chat IN $chats", + "DELETE chat WHERE account = $a", + *( + f"DELETE {t} WHERE account = $a" + for t in ( + "membership", + "collection_role", + "permission", + "access_request", + "login_session", + "password_reset", + "signin_link", + "login_ticket", + "external_identity", + "api_token", + "iiif_token", + "iiif_cookie", + "highlight", + ) + ), + "DELETE note WHERE account = $a AND (shared ?? false) = false", + "DELETE saved_view WHERE account = $a AND (shared ?? false) = false", + "DELETE saved_collection WHERE account = $a AND (shared ?? false) = false", + "DELETE upload WHERE account = $a AND state = 'receiving'", + "UPDATE $r SET email = $gone, admin = false, disabled = true, removed_at = $t, pw = NONE", + ], + a=uid, + chats=chats, + r=R("account", uid), + gone=f"removed-{uid}@removed.invalid", + t=store.now(), + ) + + def change_password(db, uid, current, new, keep_sid=None, key=""): """Someone changes their own password: the current one first. Their other sessions end (this one, keep_sid, stays) and so do reset links they asked for. Wrong current passwords count towards the sign-in throttle (key).""" diff --git a/fastapi_backend/app/domain/ops_tools.py b/fastapi_backend/app/domain/ops_tools.py index 8b494c627..501053d82 100644 --- a/fastapi_backend/app/domain/ops_tools.py +++ b/fastapi_backend/app/domain/ops_tools.py @@ -41,6 +41,7 @@ "sensors", ) ALWAYS_ASK = {"telemetry", "sensors", "files"} # sensors open ports on the network; files moves where new files go +ASK_TOOLS = {"invite_person", "change_person"} # who gets in always waits for the admin's approval ADMIN_TOOLS = [ ( @@ -91,6 +92,35 @@ ["name"], True, ), + ( + "list_people", + "The people with an account here: email, name, admin, disabled, whether they have signed in yet, and their role in each namespace.", + {}, + [], + False, + ), + ( + "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"], + True, + ), + ( + "change_person", + "Change someone's access: their role in one namespace (role none takes it away), or disable or enable their " + "account (disabling signs them out everywhere and can be undone). Removing an account for good is for the web " + "app or the API.", + { + "email": _S, + "namespace": _S, + "role": {"type": "string", "enum": ["viewer", "editor", "owner", "none"]}, + "disabled": {"type": "boolean"}, + }, + ["email"], + True, + ), ] FILE_TOOLS = [ ( @@ -176,9 +206,86 @@ def apply(db, cfg, base, tool, args, user, editable, admin): auth.audit(db, user, "upload", f"recording:{up['recording']}", {"file": up["filename"], "namespace": ns, "assistant": True}) placed.append({"file": up["filename"], "recording": up["recording"], "duplicate": bool(up.get("duplicate"))}) return {"namespace": ns, "imported": placed} + if tool in ("invite_person", "change_person"): + if not admin: + raise PermissionError("only admins manage people") + return _people(db, cfg, tool, args, user) raise ValueError(f"no tool {tool}") +def people(db): + """Everyone with an account, for the assistant.""" + names = store.space_names(db) + roles = {} + for m in db.rows("SELECT account, space, role FROM membership"): + roles.setdefault(m["account"], {})[names.get(m["space"], str(m["space"]))] = m["role"] + rows = db.rows( + "SELECT record::id(id) AS id, email, name, admin, disabled, last_login_at FROM account WHERE removed_at = NONE ORDER BY id" + ) + return [ + { + "email": r["email"], + "name": r.get("name"), + "admin": bool(r.get("admin")), + "disabled": bool(r.get("disabled")), + "signed_in_yet": bool(r.get("last_login_at")), + "roles": roles.get(r["id"], {}), + } + for r in rows + ] + + +def _space(db, ns): + try: + return store.ns_id(db, (ns or "").strip().lower(), create=False) + except KeyError: + raise ValueError(f"there's no namespace {ns}") from None + + +def _people(db, cfg, tool, args, user): + """Invite someone or change their access (approved).""" + from app import email + from . import passkeys + + out = {} + if tool == "invite_person": + sid = _space(db, args["namespace"]) if args.get("namespace") else None + uid = auth.create_account(db, args["email"], None, args.get("name")) + auth.audit(db, user, "user.create", f"account:{uid}", ["assistant"]) + out = {"invited": args["email"].strip().lower()} + if sid is not None and args.get("role"): + auth.set_role(db, uid, sid, args["role"]) + auth.audit(db, user, "member.set", f"space:{sid}", {"account": uid, "role": args["role"], "assistant": True}) + if email.mail_enabled(cfg): + raw = passkeys.create_link(db, uid, by=user["email"]) + link = passkeys.link_url(raw, email.app_url(cfg)) + email.send_soon( + email.send_invite_email, cfg, out["invited"], args.get("name"), user.get("name") or user["email"], link, passkeys.LINK_HOURS + ) + auth.audit(db, user, "user.signin_link", f"account:{uid}", ["assistant", "emailed"]) + out["emailed"] = True + else: + out["emailed"] = False + out["note"] = "Email isn't set up: send them a sign-in link from Admin → People." + return out + u = auth.find_account(db, args["email"]) + if not u or u.get("removed_at"): + raise ValueError(f"there's no account {args['email']}") + if u["id"] == user["id"] and args.get("disabled"): + raise ValueError("you can't disable yourself") + if args.get("namespace") and args.get("role"): + sid = _space(db, args["namespace"]) + role = None if args["role"] == "none" else args["role"] + auth.set_role(db, u["id"], sid, role) + auth.audit(db, user, "member.set", f"space:{sid}", {"account": u["id"], "role": role, "assistant": True}) + out["role"] = {args["namespace"]: role} + if args.get("disabled") is not None: + auth.update_account(db, u["id"], disabled=bool(args["disabled"])) + auth.audit(db, user, "user.update", f"account:{u['id']}", {"disabled": bool(args["disabled"]), "assistant": True}) + out["disabled"] = bool(args["disabled"]) + return out + + def describe_namespace(db, sid, name): """A line about a namespace for choosing between them: its description, and what's in it lately.""" meta = metadata.namespace(db, sid)["meta"] @@ -195,7 +302,7 @@ class OpsTools: """Mixed into the chat Toolbox: needs db, cfg, base, user, editable, admin, act and _approval.""" def _change(self, tool, args, summary): - if self.act and not (tool == "change_settings" and args.get("section") in ALWAYS_ASK): + if self.act and tool not in ASK_TOOLS and not (tool == "change_settings" and args.get("section") in ALWAYS_ASK): out = apply(self.db, self.cfg, self.base, tool, args, self.user, self.editable, self.admin) return {"status": "done", **out}, f"{summary}: done" return self._approval(tool, args, summary) @@ -245,6 +352,36 @@ def t_create_namespace(self, name, graph="shared"): raise ValueError(f"there's already a namespace called {name}") return self._change("create_namespace", {"name": name, "graph": graph}, f"Create the namespace {name} ({graph} graph)") + def t_list_people(self): + found = people(self.db) + return {"people": found}, f"Listed {len(found)} people" + + def t_invite_person(self, email, name=None, namespace=None, role=None): + email = (email or "").strip().lower() + if not auth.EMAIL.match(email): + raise ValueError("that isn't an email address") + if auth.find_account(self.db, email): + raise ValueError(f"{email} already has an account: change_person gives them a role") + if namespace: + _space(self.db, namespace) + 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}") + + def t_change_person(self, email, namespace=None, role=None, disabled=None): + u = auth.find_account(self.db, email) + if not u: + raise ValueError(f"there's no account {email}") + if (namespace is None) != (role is None) and disabled is None: + raise ValueError("give a namespace and a role, or disabled") + if namespace: + _space(self.db, namespace) + 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") + args = store.clean({"email": u["email"], "namespace": namespace, "role": role, "disabled": disabled}) + return self._change("change_person", args, f"{u['email']}: {', '.join(parts)}") + def _where_to(self, files): """The namespace these files go in, chosen for the person, or (None, why) when it's for them to say.""" names = store.space_names(self.db) diff --git a/fastapi_backend/app/email.py b/fastapi_backend/app/email.py index c3cee8dc7..c66fda832 100644 --- a/fastapi_backend/app/email.py +++ b/fastapi_backend/app/email.py @@ -14,6 +14,20 @@ log = logging.getLogger("lens.email") +def send_soon(send: Any, *args: Any) -> None: + """Send an email from code that isn't async (an approved assistant action), on a thread of its own.""" + import asyncio + import threading + + def run() -> None: + try: + asyncio.run(send(*args)) + except Exception: # noqa: BLE001 - the mail server failed; the link can still be sent from Admin → People + log.exception("couldn't send the email") + + threading.Thread(target=run, daemon=True, name="lens-email").start() + + def mail_enabled(cfg: dict[str, Any]) -> bool: m = cfg.get("mail") or {} return bool(m.get("server") and m.get("from_address")) @@ -102,6 +116,23 @@ async def send_signin_link_email(cfg: dict[str, Any], email: str, name: str | No await _mailer(cfg).send_message(message, template_name="signin_link.html") +async def send_invite_email(cfg: dict[str, Any], email: str, name: str | None, inviter: str, link: str, hours: int) -> None: + """An admin's sign-in link for someone they added (or who lost their passkey): it adds a passkey and signs them in.""" + if not mail_enabled(cfg): + log.warning("no email server is set up (Settings → Email); sign-in link for %s: %s", email, link) + return + from fastapi_mail import MessageSchema, MessageType + from pydantic import NameEmail + + message = MessageSchema( + subject="You're invited to Lens", + recipients=[NameEmail(name or email, email)], + template_body={"username": name or email, "inviter": inviter, "link": link, "days": max(1, hours // 24)}, + subtype=MessageType.html, + ) + await _mailer(cfg).send_message(message, template_name="invite.html") + + async def send_access_request_email( cfg: dict[str, Any], owners: list[str], who: str, rid: int, title: str | None, namespace: str | None, message: str | None ) -> None: diff --git a/fastapi_backend/app/email_templates/invite.html b/fastapi_backend/app/email_templates/invite.html new file mode 100644 index 000000000..dc238f56f --- /dev/null +++ b/fastapi_backend/app/email_templates/invite.html @@ -0,0 +1,14 @@ + + +

Hello {{ username }},

+ +

{{ inviter }} added you to Lens. Open the link below on the device you want to sign in with: it signs you in and + adds a passkey (your fingerprint, face or device PIN) where the device can make one. There is no password.

+ +

Join Lens

+ +

The link works once, for {{ days }} days. If you weren't expecting it, ignore this email.

+ +

Lens

+ + diff --git a/fastapi_backend/app/schemas/auth.py b/fastapi_backend/app/schemas/auth.py index 49845b8a6..1a648e9d6 100644 --- a/fastapi_backend/app/schemas/auth.py +++ b/fastapi_backend/app/schemas/auth.py @@ -157,6 +157,7 @@ class SigninLinkInfo(ResponseModel): class SigninLink(ResponseModel): url: str = Field(description="open it on the device to sign in with; it works once") expires_at: str + emailed: bool = Field(False, description="whether Lens emailed it to them (email=true, with mail set up)") class LoginTicket(ResponseModel): diff --git a/fastapi_backend/tests/api/test_setup_assistant.py b/fastapi_backend/tests/api/test_setup_assistant.py index 2a100c8ee..9a698b443 100644 --- a/fastapi_backend/tests/api/test_setup_assistant.py +++ b/fastapi_backend/tests/api/test_setup_assistant.py @@ -147,3 +147,38 @@ def test_a_held_upload_stays_out_until_placed(app, db, cfg, folder, new_client, uploads.place( db, cfg, up["id"], "pods", db.values("SELECT VALUE record::id(id) FROM account WHERE email = 'ed@x.io'")[0], collection=12345 ) + + +def test_the_assistant_manages_people_with_approval(app, db, cfg, folder, new_client, llm): + from app.domain import auth + + s = Assist(app, db, cfg, folder, new_client) + c, h = s.cl["admin"] + llm.tool_script = [ + {"content": "", "tool_calls": [call(1, "list_people", {})]}, + {"content": "", "tool_calls": [call(2, "invite_person", {"email": "Sam@x.io", "namespace": "pods", "role": "editor"})]}, + {"content": "I asked to invite Sam."}, + ] + cid = c.post("/api/v1/chats", headers=h, json={"kind": "setup"}).json()["id"] # even in setup, people wait for approval + ev = sse(c.post(f"/api/v1/chats/{cid}/messages", headers=h, json={"content": "invite sam@x.io to pods as an editor"}).text) + listed = json.loads(llm.seen[-2]["messages"][-1]["content"])["people"] + assert any(p["admin"] for p in listed) and all("roles" in p and "signed_in_yet" in p for p in listed) + appr = ev["approval"][0] + assert appr["summary"] == "Invite sam@x.io as editor of pods" and not auth.find_account(db, "sam@x.io") + r = c.post(f"/api/v1/approvals/{appr['id']}", headers=h, json={"decision": "approve"}).json() + assert r["status"] == "done" and r["invited"] == "sam@x.io" and r["emailed"] is False + sam = auth.find_account(db, "sam@x.io") + assert auth.roles(db, sam) == {store.ns_id(db, "pods"): "editor"} + + llm.tool_script = [ + { + "content": "", + "tool_calls": [call(3, "change_person", {"email": "sam@x.io", "namespace": "pods", "role": "none", "disabled": True})], + }, + {"content": "Asked."}, + ] + ev = sse(c.post(f"/api/v1/chats/{cid}/messages", headers=h, json={"content": "take sam out"}).text) + appr = ev["approval"][0] + assert appr["summary"] == "sam@x.io: no role in pods, disable the account" + assert c.post(f"/api/v1/approvals/{appr['id']}", headers=h, json={"decision": "approve"}).json()["status"] == "done" + assert auth.roles(db, sam) == {} and auth.get_account(db, sam["id"])["disabled"] diff --git a/fastapi_backend/tests/api/test_users.py b/fastapi_backend/tests/api/test_users.py index 55b19a20c..7f5d8aa09 100644 --- a/fastapi_backend/tests/api/test_users.py +++ b/fastapi_backend/tests/api/test_users.py @@ -75,3 +75,81 @@ def test_members_changes_need_write_access(client, db): body = {"account": vi, "role": "viewer"} assert client.put("/api/v1/namespaces/calls/members", json=body, headers=bearer).status_code == 403 # read-only token assert client.put("/api/v1/namespaces/calls/members", json=body, headers=h).status_code == 200 + + +def test_admins_remove_people_for_good(client, new_client, db): + from app.domain import auth, chat, notes, store + + root = make_user(db, "root@x.io", "root password 1", admin=True) + gone = make_user(db, "gone@x.io", "gone password 12", roles={"pods": "editor"}) + h = login(client, "root@x.io", "root password 1") + hg = login(new_client(), "gone@x.io", "gone password 12") + tok = client.post("/api/v1/tokens", json={"name": "ci", "scope": "read"}, headers=hg).json()["token"] + space = store.ns_id(db, "pods") + mine = notes.create(db, 1, space, gone, "only mine") + shared = notes.create(db, 1, space, gone, "for everyone", shared=True) + cid = chat.create(db, gone, title="private") + + assert client.delete(f"/api/v1/users/{root}", headers=h).status_code == 400 # not yourself + assert client.delete("/api/v1/users/9999", headers=h).status_code == 404 + assert client.delete(f"/api/v1/users/{gone}", headers=hg).status_code == 403 # admins only + assert client.delete(f"/api/v1/users/{gone}", headers=h).status_code == 200 + + # every way in stops at once + assert client.get("/api/v1/auth/me", headers=hg).status_code == 401 + assert client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {tok}"}).status_code == 401 + assert client.post("/api/v1/auth/login", json={"email": "gone@x.io", "password": "gone password 12"}).status_code == 401 + assert client.post(f"/api/v1/users/{gone}/signin-link", headers=h).status_code == 404 + assert client.patch(f"/api/v1/users/{gone}", json={"name": "back"}, headers=h).status_code == 404 + assert client.delete(f"/api/v1/users/{gone}", headers=h).status_code == 404 # once + # off the list and out of the namespace; private things go, shared ones stay under their name + assert "gone@x.io" not in {p["email"] for p in client.get("/api/v1/users", headers=h).json()} + assert not db.values("SELECT VALUE id FROM membership WHERE account = $a", a=gone) + assert not db.values("SELECT VALUE id FROM api_token WHERE account = $a", a=gone) + assert not db.values("SELECT VALUE id FROM chat WHERE account = $a", a=gone) and cid + assert notes.get(db, shared)["text"] == "for everyone" + with __import__("pytest").raises(KeyError): + notes.get(db, mine) + left = auth.get_account(db, gone) + assert left["removed_at"] and left["disabled"] and not left["admin"] and left["email"] != "gone@x.io" + audit = client.get("/api/v1/audit", headers=h).json() + assert any(a["action"] == "user.remove" and a["target"] == f"account:{gone}" for a in audit) + + # the address can be invited again + assert client.post("/api/v1/users", json={"email": "gone@x.io"}, headers=h).status_code == 200 + + +def test_matterbridge_account_stays(client, db): + make_user(db, "root@x.io", "root password 1", admin=True) + bot = make_user(db, "bot@x.io", "bot password 12") + h = login(client, "root@x.io", "root password 1") + assert client.put("/api/v1/settings/bridge", json={"account": "bot@x.io"}, headers=h).status_code == 200 + r = client.delete(f"/api/v1/users/{bot}", headers=h) + assert r.status_code == 409 and "Matterbridge" in r.json()["detail"] + + +def test_invites_are_emailed_when_mail_is_set_up(client, db, monkeypatch): + from app import email + + sent = [] + + class Mailer: + def __init__(self, cfg): + pass + + async def send_message(self, message, template_name=None): + sent.append(([r.email for r in message.recipients], message.subject, template_name, message.template_body)) + + monkeypatch.setattr(email, "_mailer", Mailer) + make_user(db, "root@x.io", "root password 1", admin=True) + h = login(client, "root@x.io", "root password 1") + uid = client.post("/api/v1/users", json={"email": "new@x.io", "name": "New"}, headers=h).json()["id"] + r = client.post(f"/api/v1/users/{uid}/signin-link?email=true", headers=h).json() + assert r["emailed"] is False and not sent # no mail server yet: the link is still there to share + mail = {"server": "smtp.example.org", "port": 465, "from_address": "lens@example.org", "security": "ssl"} + assert client.put("/api/v1/settings/mail", json=mail, headers=h).status_code == 200 + assert client.post(f"/api/v1/users/{uid}/signin-link", headers=h).json()["emailed"] is False # only when asked + r = client.post(f"/api/v1/users/{uid}/signin-link?email=true", headers=h).json() + assert r["emailed"] is True + assert sent[-1][:3] == (["new@x.io"], "You're invited to Lens", "invite.html") + assert sent[-1][3]["link"].split("#")[1] == r["url"].split("#")[1] and sent[-1][3]["days"] == 3 diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index 32ab2f424..d3acf5635 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -2096,6 +2096,11 @@ export type { RemoveRecordingPermissionErrors, RemoveRecordingPermissionResponse, RemoveRecordingPermissionResponses, + RemoveUserData, + RemoveUserError, + RemoveUserErrors, + RemoveUserResponse, + RemoveUserResponses, RemoveVaultPasskeyData, RemoveVaultPasskeyError, RemoveVaultPasskeyErrors, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index 6e5801f34..cfa72be3f 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -1023,6 +1023,9 @@ import type { RemoveRecordingPermissionData, RemoveRecordingPermissionErrors, RemoveRecordingPermissionResponses, + RemoveUserData, + RemoveUserErrors, + RemoveUserResponses, RemoveVaultPasskeyData, RemoveVaultPasskeyErrors, RemoveVaultPasskeyResponses, @@ -2088,7 +2091,8 @@ export class Users { * Make Signin Link * * A one-time link for this person to add a passkey and sign in (a new person, or one who lost theirs). It lasts - * three days; making another stops the last one. Share it privately. Audited as `user.signin_link`. + * three days; making another stops the last one. Share it privately, or with email=true Lens emails it to them + * when mail is set up (`emailed` says whether it did). Audited as `user.signin_link`. */ public static makeSigninLink( options: Options, @@ -2148,6 +2152,23 @@ export class Users { }); } + /** + * Remove User + * + * Remove someone for good (docs/authentication.md#removing-someone): their sign-ins, roles, permissions and + * private things go; what they shared stays under their name, and their email can be invited again. Disabling + * (PATCH) is the reversible way. Refused (409) for the account Matterbridge answers as, and when their passkeys are + * the only way into a vault, unless lose_vaults=true. Audited as `user.remove`. + */ + public static removeUser( + options: Options, + ): RequestResult { + return (options.client ?? client).delete({ + url: "/api/v1/users/{uid}", + ...options, + }); + } + /** * Update User * diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index fd83bbb05..fb74aa113 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -14163,6 +14163,12 @@ export type SigninLink = { * Expires At */ expires_at: string; + /** + * Emailed + * + * whether Lens emailed it to them (email=true, with mail set up) + */ + emailed?: boolean; [key: string]: unknown; }; @@ -18390,7 +18396,12 @@ export type MakeSigninLinkData = { */ uid: number; }; - query?: never; + query?: { + /** + * Email + */ + email?: boolean; + }; url: "/api/v1/users/{uid}/signin-link"; }; @@ -18704,6 +18715,41 @@ export type CreateUserResponses = { export type CreateUserResponse = CreateUserResponses[keyof CreateUserResponses]; +export type RemoveUserData = { + body?: never; + path: { + /** + * Uid + */ + uid: number; + }; + query?: { + /** + * Lose Vaults + */ + lose_vaults?: boolean; + }; + url: "/api/v1/users/{uid}"; +}; + +export type RemoveUserErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type RemoveUserError = RemoveUserErrors[keyof RemoveUserErrors]; + +export type RemoveUserResponses = { + /** + * Successful Response + */ + 200: Ok; +}; + +export type RemoveUserResponse = RemoveUserResponses[keyof RemoveUserResponses]; + export type UpdateUserData = { body: UserUpdate; path: { diff --git a/nextjs-frontend/components/admin/people.tsx b/nextjs-frontend/components/admin/people.tsx index 466409359..a5888677d 100644 --- a/nextjs-frontend/components/admin/people.tsx +++ b/nextjs-frontend/components/admin/people.tsx @@ -37,7 +37,8 @@ type Dialogs = | { kind: "reset"; person: Person } | { kind: "rename"; person: Person } | { kind: "link"; person: Person } - | { kind: "passkeys"; person: Person }; + | { kind: "passkeys"; person: Person } + | { kind: "remove"; person: Person }; /** People: accounts with their role in every namespace (Admin AD1); create, reset, disable (AD2). */ export function PeoplePage() { @@ -205,11 +206,12 @@ export function PeoplePage() { {dialog?.kind === "passkeys" && setDialog(null)} />} {dialog?.kind === "reset" && setDialog(null)} />} {dialog?.kind === "rename" && setDialog(null)} />} + {dialog?.kind === "remove" && setDialog(null)} />} ); } -type Action = "reset" | "disable" | "enable" | "rename" | "link" | "passkeys"; +type Action = "reset" | "disable" | "enable" | "rename" | "link" | "passkeys" | "remove"; /** The role matrix, an ARIA grid: arrows move between cells, Enter opens the cell's control, Escape comes back. */ function RoleGrid({ @@ -458,6 +460,11 @@ function RoleGrid({ {me ? "You can’t disable yourself" : "Disable account"} )} + {!me && ( + onAction("remove", p)}> + Remove for good… + + )} @@ -549,13 +556,16 @@ function Done({ title, password }: { title: string; password: string }) { } /** A one-time sign-in link to share privately: it adds a passkey on the device it's opened on. */ -function LinkDone({ title, url }: { title: string; url: string }) { +function LinkDone({ title, url, emailed }: { title: string; url: string; emailed?: boolean }) { return (
{title} - Send them this sign-in link privately. It works once, for three days, and isn’t shown again. Opening it adds a - passkey (fingerprint, face or device PIN) on their device. + {emailed + ? "We emailed them this sign-in link. You can also send it yourself; it" + : "Send them this sign-in link privately. It"}{" "} + works once, for three days, and isn’t shown again. Opening it adds a passkey (fingerprint, face or device PIN) + on their device.
@@ -591,7 +601,10 @@ function CreateDialog({ passwords, onClose }: { passwords: boolean; onClose: () // a role in a namespace in the same step, so nobody is sent to the role matrix afterwards if (!admin && ns && role !== "none") await data(Users.setMember({ client, path: { name: ns }, body: { account: made.id, role } })); - return usePassword ? null : await data(Users.makeSigninLink({ client, path: { uid: made.id } })); + // emailed to them when mail is set up, and shown here either way + return usePassword + ? null + : await data(Users.makeSigninLink({ client, path: { uid: made.id }, query: { email: true } })); }, onSuccess: () => { void qc.invalidateQueries({ queryKey: ["users"] }); @@ -632,7 +645,11 @@ function CreateDialog({ passwords, onClose }: { passwords: boolean; onClose: () > {create.isSuccess ? ( create.data ? ( - + ) : ( ) @@ -808,7 +825,9 @@ function RenameDialog({ person, onClose }: { person: Person; onClose: () => void function LinkDialog({ person, onClose }: { person: Person; onClose: () => void }) { const client = useApiClient(); const who = person.name || person.email; - const make = useMutation({ mutationFn: () => data(Users.makeSigninLink({ client, path: { uid: person.id } })) }); + const make = useMutation({ + mutationFn: () => data(Users.makeSigninLink({ client, path: { uid: person.id }, query: { email: true } })), + }); return ( void } ) } > - {make.isSuccess && } + {make.isSuccess && ( + + )} {make.isError && {make.error.message}} ); @@ -876,3 +897,69 @@ function PasskeysDialog({ person, onClose }: { person: Person; onClose: () => vo ); } + +/** Removing can't be undone, so unlike disabling it asks first, and offers disabling instead. */ +function RemoveDialog({ person, onClose }: { person: Person; onClose: () => void }) { + const client = useApiClient(); + const qc = useQueryClient(); + const toast = useToast(); + const who = person.name || person.email; + const [loseVaults, setLoseVaults] = useState(false); + const remove = useMutation({ + mutationFn: () => + data( + Users.removeUser({ client, path: { uid: person.id }, query: loseVaults ? { lose_vaults: true } : undefined }), + ), + onSuccess: () => { + void qc.invalidateQueries({ queryKey: ["users"] }); + void qc.invalidateQueries({ queryKey: ["members"] }); + toast({ title: `Removed ${who}`, body: "What they shared stays under their name.", tone: "green" }); + onClose(); + }, + }); + const disable = useMutation({ + mutationFn: () => data(Users.updateUser({ client, path: { uid: person.id }, body: { disabled: true } })), + onSuccess: () => { + void qc.invalidateQueries({ queryKey: ["users"] }); + toast({ title: `Disabled ${who}`, body: "Roles, notes and edits are kept.", tone: "green" }); + onClose(); + }, + }); + const vault = remove.error instanceof ApiError && /vault|lost for good/i.test(remove.error.message); + return ( + !o && onClose()} + title={`Remove ${who} for good?`} + description="They can't sign in again, and their roles, permissions, API tokens and apps go. So do their chats, private notes, highlights and saved views. Notes, views and comments they shared stay under their name. You can invite the same email again later. This can't be undone; disabling can." + actions={ + <> + + {!person.disabled && ( + + )} + + + } + > + {remove.isError && {remove.error.message}} + {vault && ( + + )} + + ); +} diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index cfe128052..14a3878c8 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -1510,7 +1510,7 @@ "users" ], "summary": "Make Signin Link", - "description": "A one-time link for this person to add a passkey and sign in (a new person, or one who lost theirs). It lasts\nthree days; making another stops the last one. Share it privately. Audited as `user.signin_link`.", + "description": "A one-time link for this person to add a passkey and sign in (a new person, or one who lost theirs). It lasts\nthree days; making another stops the last one. Share it privately, or with email=true Lens emails it to them\nwhen mail is set up (`emailed` says whether it did). Audited as `user.signin_link`.", "operationId": "make_signin_link", "parameters": [ { @@ -1521,6 +1521,16 @@ "type": "integer", "title": "Uid" } + }, + { + "name": "email", + "in": "query", + "required": false, + "schema": { + "type": "boolean", + "default": false, + "title": "Email" + } } ], "responses": { @@ -2062,6 +2072,57 @@ } } } + }, + "delete": { + "tags": [ + "users" + ], + "summary": "Remove User", + "description": "Remove someone for good (docs/authentication.md#removing-someone): their sign-ins, roles, permissions and\nprivate things go; what they shared stays under their name, and their email can be invited again. Disabling\n(PATCH) is the reversible way. Refused (409) for the account Matterbridge answers as, and when their passkeys are\nthe only way into a vault, unless lose_vaults=true. Audited as `user.remove`.", + "operationId": "remove_user", + "parameters": [ + { + "name": "uid", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "title": "Uid" + } + }, + { + "name": "lose_vaults", + "in": "query", + "required": false, + "schema": { + "type": "boolean", + "default": false, + "title": "Lose Vaults" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Ok" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } } }, "/api/v1/namespaces/{name}/members": { @@ -48827,6 +48888,12 @@ "expires_at": { "type": "string", "title": "Expires At" + }, + "emailed": { + "type": "boolean", + "title": "Emailed", + "description": "whether Lens emailed it to them (email=true, with mail set up)", + "default": false } }, "additionalProperties": true, diff --git a/threat-model.json b/threat-model.json index bbc99cbd5..9820d1585 100644 --- a/threat-model.json +++ b/threat-model.json @@ -758,6 +758,14 @@ "provenance": "documented", "source": "docs/authentication.md \"Every request checks that the account is still active\"" }, + { + "property": "P-REMOVE", + "violation_symptom": "integrity-bypass", + "severity_tier": "security", + "conditions": "removing an account ends every way it signs in at once and takes every role, collection role and recording permission; its email can make a new account, which inherits nothing; admins only, never yourself, never the Matterbridge account, never the last passkey into a vault unless the admin agrees to lose its files", + "provenance": "documented", + "source": "docs/authentication.md \"Removing someone\"" + }, { "property": "P-BEARER-ONLY", "violation_symptom": "integrity-bypass", diff --git a/threat-model.md b/threat-model.md index 01f0272e9..56ed5b7a2 100644 --- a/threat-model.md +++ b/threat-model.md @@ -468,6 +468,7 @@ Paths in the Voided by column are relative to `fastapi_backend/app/`. Searches c | P-MEDIA-LINK | Media, frames, documents and reports open without a session only through a link the server signed for that path, or a live share link. Text people or models write is never signed. | info-leak | security-critical | *(documented, docs/architecture.md "is never signed")* | Voided by: Knowing `ACCESS_SECRET_KEY` signs any path — `core/security.py:43`; dev compose key — `docker-compose.yml:24`. Lifetime `MEDIA_URL_EXPIRE_SECONDS` — `config.py:30`. Report pages sign every recording of the namespace — `api/pages.py:140-141`. Signing is limited to allow-listed fields — `api/media.py:25-30`. | | P-SHARE | A share link opens one recording, read-only. It expires and can be revoked. Only hashes are stored. A dead link answers the same 410 whatever went wrong. | integrity-bypass | security-critical | *(documented, docs/authentication.md "give read-only access to one recording's player and embed")* | Voided by: Liveness plus recording match only — `domain/auth.py:441-444`; `?s=` routes — `api/deps.py:252` (Q7). | | P-AUTH-REQ | A request is authenticated only if its bearer verifies and the account and session are live. Sign-out and disabling take effect at once, for every token kind. Revoking an app grant or API token ends its tokens at once. | integrity-bypass | security-critical | *(documented, docs/authentication.md "Every request checks that the account is still active")* | Voided by: Liveness checked per request — `api/deps.py:92`; JWT algorithm from `ALGORITHM` — `config.py:27`; dev secrets — `docker-compose.yml:24`. No bypass flag: `grep -rniE "disable_auth\|skip_auth\|no_auth\|auth_bypass\|AUTH_DISABLED\|ALLOW_ANON\|DEV_MODE" fastapi_backend/app nextjs-frontend/lib nextjs-frontend/auth.ts nextjs-frontend/proxy.ts docker-compose*.yml install.sh` — 0 hits. | +| P-REMOVE | Removing an account ends every way it signs in at once (sessions, passkeys, sign-in links, connected accounts, API tokens, app grants, IIIF tokens) and takes every role, collection role and recording permission. Its email can make a new account, which inherits nothing. Admins only; never yourself, never the Matterbridge account, never the last passkey into a vault unless the admin says its files may be lost. | integrity-bypass | security-critical | *(documented, docs/authentication.md "Removing someone")* | Voided by: the account row stays as a marker with an `.invalid` email — `domain/auth.py` `remove_account`; shared notes, views and comments keep its id. | | P-BEARER-ONLY | `/api/v1` takes bearer tokens only, never cookies. The IIIF authorization flow and the web app's NextAuth handlers are the cookie surfaces. | integrity-bypass | security-critical | *(documented, docs/architecture.md "so there is no CSRF surface")* | Voided by: IIIF auth cookies — `api/iiif.py:232`, `api/iiif.py:333`; external-login state cookie — `api/v1/routes/external.py:34`. | | P-SETUP-ONCE | No public sign-up. Only the one-time setup code makes the first admin, and it dies once an account exists. | integrity-bypass | security-critical | *(documented, docs/configuration.md "so a stranger who finds a new")* | Voided by: `LENS_ADMIN_EMAIL` makes an admin with no code — `domain/setup.py:75-77`; `LENS_SETUP_CODE` fixes the code — `core/runtime.py:62`; the code is logged — `core/runtime.py:64-68`; plain HTTP (§1.6). | | P-ONCE | Sign-in links, WebAuthn flows, sign-in tickets, OAuth codes and external-login states work once. A refused or failed attempt consumes nothing. | integrity-bypass | security-critical | *(documented, docs/authentication.md "works once")* | Voided by: nothing. Search: `grep -rnE 'RETURN BEFORE' fastapi_backend/app/domain/passkeys.py fastapi_backend/app/domain/oauth.py fastapi_backend/app/domain/external_login.py` — every consumer deletes the row before trusting it. A new admin-issued sign-in link replaces older ones by design. | @@ -486,7 +487,7 @@ Paths in the Voided by column are relative to `fastapi_backend/app/`. Searches c | P-NO-FETCH | SPARQL refuses SERVICE and FROM and never loads a named graph. RDF import fetches nothing, refuses remote JSON-LD contexts and does not read RDF/XML. | info-leak | security-critical | *(documented, rdf_import.py docstring "Nothing is fetched while reading")* | Voided by: Process-global rdflib flag, set per call — `domain/rdf.py:576`; SERVICE refused — `domain/rdf.py:551`; remote contexts — `domain/rdf_import.py:54-56`. | | P-QUERY | Cypher is read-only and runs on the caller's readable namespaces. A query stops within 3 million steps or 8 seconds; paths run up to 8 hops. Threshold: running past the budget is a bug; slow within it is not. | integrity-bypass (writes, scope); hang (budget) | security-critical (scope, writes); correctness-only (budget) | *(documented, docs/graph.md "3 million steps")* | Voided by: Admins see every namespace; write refusals — `domain/cypher.py:39`; budgets — `domain/cypher.py:35-38`. | | P-RETRIEVAL | Chat, assistant tools and MCP return only what the person can read, within the conversation's scope, and the tool loop stops at `ai.max_steps` and `ai.max_transcript_reads`. | info-leak (scope); hang (caps) | security-critical (scope); correctness-only (caps) | *(documented, docs/assistant.md "limited to what the person can read")* | Voided by: Admins read everything; an admin setup conversation adds server tools and the `act` flag — `domain/ai_tools.py:287-289`; `ai.extensions: false` turns extensions off. | -| P-APPROVAL | Assistant tools that change data wait for the person's approval, except notes and an admin's setup conversation. | integrity-bypass | security-critical | *(documented, docs/assistant.md "Approvals")* | Voided by: Admins read everything; an admin setup conversation adds server tools and the `act` flag — `domain/ai_tools.py:287-289`; `ai.extensions: false` turns extensions off. | +| P-APPROVAL | Assistant tools that change data wait for the person's approval, except notes and an admin's setup conversation. Inviting people and changing their access always wait, even there, and the assistant cannot remove an account. | integrity-bypass | security-critical | *(documented, docs/assistant.md "Approvals")* | Voided by: Admins read everything; an admin setup conversation adds server tools and the `act` flag — `domain/ai_tools.py:287-289`; `ai.extensions: false` turns extensions off. | | P-EXT-SCOPE | Your own hooks run in your conversations; another person's hooks run only when an admin shared them. | integrity-bypass | security-critical | *(documented, docs/assistant.md "other people's run only when an admin shared them")* | Voided by: An admin sharing the extension — `domain/extensions.py:595-598`. | | P-NO-CODE | No non-admin can run code on the host. This covers owners, editors, viewers, API tokens, MCP agents, OAuth apps and model tool calls acting for one. Python tools are written by admins only and run only while an admin owns them. | integrity-bypass | security-critical | *(maintainer, 2026-10)* | Voided by: Making someone admin; authoring gate — `domain/extensions.py:129-130`; run gate — `domain/extensions.py:600-601`. `grep -rnE "eval\(\|exec\(\|pickle\|yaml\.load\(\|__import__" fastapi_backend/app` — one `exec`, inside the code-tool child. | | P-UPLOAD | Uploads accept only the types in `uploads.extensions` and are size-capped. Nothing uploaded is executed. Files are served as audio, video or a download, and names carry no folders. | bad-data-accepted | security-critical | *(documented, docs/configuration.md "Uploads accept only the types")* | Voided by: Admin-added types; check — `domain/uploads.py:157-158`. The `attachments` role takes any type (never executed). Bytes are not checked against the extension. | diff --git a/threat-model.yaml b/threat-model.yaml index 872a1a204..4555e84b7 100644 --- a/threat-model.yaml +++ b/threat-model.yaml @@ -2,7 +2,7 @@ # Authority order: prose > yaml > json. Regenerate whenever the prose changes. schema: threat-model-sidecar/v2 project: lens -prose_version: "threat-model.md@sha256:c7c945e760490e73dbb947e89beff868a218b89b839b4172f9d928d4853e992a" +prose_version: "threat-model.md@sha256:0c97e93afad64c2944d863b8cbedca90776050ffbc0f54b83cc95bcd302a2851" model_status: under-review triage_policy: strict confidence: {documented: 201, maintainer: 46, inferred: 91, assumption: 8} @@ -1136,6 +1136,14 @@ properties_claimed: violation_symptoms: [integrity-bypass] x-voided-by: "liveness checked per request (api/deps.py:92); JWT algorithm from ALGORITHM (config.py:27); dev secrets (docker-compose.yml:24); no bypass flag found" provenance: {kind: documented, source: 'docs/authentication.md "Every request checks that the account is still active"'} + - id: P-REMOVE + kind: authentication + components: [identity, authz] + tier: security-critical + conditions: "removing an account ends every way it signs in at once and takes every role, collection role and recording permission; its email can make a new account, which inherits nothing; admins only, never yourself, never the Matterbridge account, never the last passkey into a vault unless the admin agrees to lose its files" + violation_symptoms: [integrity-bypass] + x-voided-by: "the account row stays as a marker with an .invalid email (domain/auth.py remove_account); shared notes, views and comments keep its id" + provenance: {kind: documented, source: 'docs/authentication.md "Removing someone"'} - id: P-BEARER-ONLY kind: authentication components: [identity]