From 83c522321e79fe2d68fbccc617843917ba618a70 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sat, 3 Oct 2026 11:43:35 +0000 Subject: [PATCH 1/3] wip(security): passkey vaults, parked (backend and tests; no web app yet) Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01R1moYBoaoY4cZFbhBWqzEJ --- fastapi_backend/app/api/v1/router.py | 2 + fastapi_backend/app/api/v1/routes/vaults.py | 108 +++++++++++ fastapi_backend/app/domain/jobs.py | 6 +- fastapi_backend/app/domain/keyring.py | 50 ++++- fastapi_backend/app/domain/passkeys.py | 29 ++- fastapi_backend/app/domain/store.py | 2 +- fastapi_backend/app/domain/vaults.py | 202 ++++++++++++++++++++ fastapi_backend/app/schemas/namespaces.py | 31 ++- fastapi_backend/tests/api/test_vaults.py | 133 +++++++++++++ fastapi_backend/tests/fake_authenticator.py | 18 +- 10 files changed, 564 insertions(+), 17 deletions(-) create mode 100644 fastapi_backend/app/api/v1/routes/vaults.py create mode 100644 fastapi_backend/app/domain/vaults.py create mode 100644 fastapi_backend/tests/api/test_vaults.py diff --git a/fastapi_backend/app/api/v1/router.py b/fastapi_backend/app/api/v1/router.py index 47e4cd5eb..e34d5f706 100644 --- a/fastapi_backend/app/api/v1/router.py +++ b/fastapi_backend/app/api/v1/router.py @@ -43,6 +43,7 @@ templates, uploads, users, + vaults, video, views, voice, @@ -97,5 +98,6 @@ routines, sensors, voice, + vaults, ): api_router.include_router(module.router) diff --git a/fastapi_backend/app/api/v1/routes/vaults.py b/fastapi_backend/app/api/v1/routes/vaults.py new file mode 100644 index 000000000..fbed24247 --- /dev/null +++ b/fastapi_backend/app/api/v1/routes/vaults.py @@ -0,0 +1,108 @@ +"""Vaults: namespaces only their people's passkeys open (app/domain/vaults.py, docs/encryption.md#vaults). + +Owners make a namespace a vault, add and remove the passkeys that open it, and turn it back; anyone whose passkey opens +it can unlock it for a while, or lock it now. Every step that needs a passkey is two calls, like signing in: options +for the browser (asking for the PRF extension's secret for this vault), then its answer. +""" + +from __future__ import annotations + +from fastapi import APIRouter, HTTPException, Request + +from app.api.deps import Acl, Cfg, CurrentUser, Db, Writer, web_origin +from app.domain import auth, keyring, passkeys, vaults +from app.schemas.auth import PasskeyOptions +from app.schemas.namespaces import VaultAnswer, VaultStart, VaultStatus + +router = APIRouter(prefix="/namespaces", tags=["vaults"]) + + +def _signed_in(user: CurrentUser) -> None: + if user.via != "access": + raise HTTPException(403, "sign in with a passkey for this; API tokens and apps can't") + + +def _space(acl: Acl, name: str, kind: str) -> int: + return acl.namespace(name, "owner") if kind in ("seal", "add") else acl.namespace(name) + + +def _run(fn, *args): + try: + return fn(*args) + except keyring.Locked: + raise HTTPException(423, "this vault is locked; unlock it with one of its passkeys first") from None + except (passkeys.PasskeyError, vaults.VaultError, ValueError) as e: + raise HTTPException(400, str(e)) from None + except KeyError: + raise HTTPException(404, "not found") from None + + +@router.get("/{name}/vault") +def get_vault(name: str, acl: Acl, db: Db) -> VaultStatus: + """Whether the namespace is a vault, whether it's open now, and which passkeys open it.""" + return VaultStatus(**vaults.status(db, acl.namespace(name))) + + +@router.post("/{name}/vault/options") +def vault_options(name: str, body: VaultStart, user: Writer, acl: Acl, request: Request, db: Db) -> PasskeyOptions: + """Start making the namespace a vault (owners), unlocking it, or adding a passkey to it (owners): options for the + browser, which ask the passkey for this vault's PRF secret.""" + _signed_in(user) + sid = _space(acl, name, body.kind) + return PasskeyOptions(**_run(vaults.options, db, web_origin(request), user.id, sid, body.kind)) + + +def _answer(kind: str, name: str, body: VaultAnswer, user: Writer, acl: Acl, db: Db, cfg: dict) -> VaultStatus: + _signed_in(user) + sid = _space(acl, name, kind) + fn = {"seal": vaults.seal, "unlock": vaults.unlock, "add": vaults.add}[kind] + out = _run(fn, db, cfg, user.id, sid, body.flow, body.credential, body.prf) + auth.audit(db, user.as_audit(), f"vault.{kind}", f"space:{sid}") + return VaultStatus(**out) + + +@router.post("/{name}/vault") +def seal_vault(name: str, body: VaultAnswer, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> VaultStatus: + """Make the namespace a vault opened by the passkey that answered. From then on only its passkeys open its files; + lose every one and they're gone. Audited as `vault.seal`.""" + return _answer("seal", name, body, user, acl, db, cfg) + + +@router.post("/{name}/vault/unlock") +def unlock_vault(name: str, body: VaultAnswer, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> VaultStatus: + """Open the vault on this server for encryption.vault_minutes; its waiting work runs. Audited as `vault.unlock`.""" + return _answer("unlock", name, body, user, acl, db, cfg) + + +@router.post("/{name}/vault/passkeys") +def add_vault_passkey(name: str, body: VaultAnswer, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> VaultStatus: + """Let the passkey that answered open the vault too (it must be open). Audited as `vault.add`.""" + return _answer("add", name, body, user, acl, db, cfg) + + +@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") + out = _run(vaults.remove, db, sid, pid) + auth.audit(db, user.as_audit(), "vault.remove", f"space:{sid}", [pid]) + return VaultStatus(**out) + + +@router.post("/{name}/vault/lock") +def lock_vault(name: str, user: Writer, acl: Acl, db: Db) -> VaultStatus: + """Close the vault on this server now. Audited as `vault.lock`.""" + sid = acl.namespace(name) + out = _run(vaults.lock, db, sid) + auth.audit(db, user.as_audit(), "vault.lock", f"space:{sid}") + return VaultStatus(**out) + + +@router.delete("/{name}/vault") +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") + 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/domain/jobs.py b/fastapi_backend/app/domain/jobs.py index 4e358ca8d..af33d0fce 100644 --- a/fastapi_backend/app/domain/jobs.py +++ b/fastapi_backend/app/domain/jobs.py @@ -253,10 +253,12 @@ def enqueue_pending(db, space=None, by=None): def claim(db, worker, can): + locked = keyring.locked_vaults(db) # a vault's work waits until someone unlocks it here for r in db.rows( - "SELECT record::id(id) AS id, priority, created_at, started_at FROM job WHERE status = 'queued' AND next_step IN $can " - "ORDER BY priority DESC, created_at ASC LIMIT 10", + "SELECT record::id(id) AS id, space, priority, created_at, started_at FROM job WHERE status = 'queued' AND next_step IN $can " + "AND space NOTINSIDE $locked ORDER BY priority DESC, created_at ASC LIMIT 10", can=sorted(can), + locked=sorted(locked), ): t = store.now() try: diff --git a/fastapi_backend/app/domain/keyring.py b/fastapi_backend/app/domain/keyring.py index c5446e02d..b500b3a5d 100644 --- a/fastapi_backend/app/domain/keyring.py +++ b/fastapi_backend/app/domain/keyring.py @@ -30,6 +30,7 @@ import struct import tempfile import threading +import time from . import settings, store @@ -111,10 +112,11 @@ def _save(db, sid, row, keys, current=None): """Write the keys back only if nobody changed them since row was read (another process rotating, say).""" cur = row["current"] if current is None else current done = db.values( - "UPDATE $r SET keys = $k, current = $n, rev = $rev + 1 WHERE (rev ?? 0) = $rev RETURN VALUE rev", + "UPDATE $r SET keys = $k, current = $n, vault = $v, rev = $rev + 1 WHERE (rev ?? 0) = $rev RETURN VALUE rev", r=R("data_key", int(sid)), k=keys, n=cur, + v=SERVER not in keys[str(cur)]["wrapped"], rev=int(row.get("rev") or 0), ) if not done: @@ -141,6 +143,7 @@ def status(db, sid): def data_key(db, cfg, sid, version=None, create=True): """The namespace's data key (the current version unless one is named), as (version, key).""" sid = int(sid) + _expire(db, sid) cache = _cache(db) if version is not None and (sid, int(version)) in cache: return int(version), cache[(sid, int(version))] @@ -193,8 +196,39 @@ def remove_wrapper(db, sid, name): _save(db, sid, row, keys) -def unlock(db, sid, name, kek): - """Open a namespace with one of its wrappers for this process; raises if that key doesn't open it.""" +def _until(db): + u = getattr(db, "_vault_until", None) + if u is None: + u = db._vault_until = {} + return u + + +def _expire(db, sid): + """A vault opened for a while closes again once that time is up.""" + t = _until(db).get(sid) + if t is not None and t < time.time(): + lock(db, sid) + + +def unlocked_until(db, sid): + """When a vault opened in this process closes again (a Unix time), or None.""" + _expire(db, int(sid)) + return _until(db).get(int(sid)) + + +def locked_vaults(db): + """The vault namespaces nobody has unlocked in this process: their work waits.""" + out = set() + for sid in db.values("SELECT VALUE space FROM data_key WHERE vault = true"): + _expire(db, int(sid)) + if not any(k[0] == int(sid) for k in _cache(db)): + out.add(int(sid)) + return out + + +def unlock(db, sid, name, kek, minutes=None): + """Open a namespace with one of its wrappers for this process (for `minutes`, else until locked); raises Locked if + that key doesn't open it.""" sid = int(sid) row = _row(db, sid) if not row: @@ -208,12 +242,22 @@ def unlock(db, sid, name, kek): except Exception: # noqa: BLE001 - wrong key raise Locked(sid) from None _cache(db).update(opened) + keep_open(db, sid, minutes) + + +def keep_open(db, sid, minutes): + """An open vault stays open for `minutes` more (None: until locked).""" + if minutes: + _until(db)[int(sid)] = time.time() + 60 * minutes + else: + _until(db).pop(int(sid), None) def lock(db, sid): """Forget a namespace's keys in this process (a vault then needs unlocking again).""" for k in [k for k in _cache(db) if k[0] == int(sid)]: del _cache(db)[k] + _until(db).pop(int(sid), None) def rotate(db, cfg, sid, keks=None): diff --git a/fastapi_backend/app/domain/passkeys.py b/fastapi_backend/app/domain/passkeys.py index f70251f06..6d1d31f3d 100644 --- a/fastapi_backend/app/domain/passkeys.py +++ b/fastapi_backend/app/domain/passkeys.py @@ -138,7 +138,9 @@ def _creation(db, cfg, kind, origin, uid, email, name, data=None): if not uid: data = {**(data or {}), "user": bytes_to_base64url(opts.user.id)} flow = _start(db, kind, origin, rp_id, opts.challenge, uid, data) - return {"flow": flow, "options": json.loads(options_to_json(opts))} + options = json.loads(options_to_json(opts)) + options["extensions"] = {"prf": {}} # so a security key turns on what vaults need (app/domain/vaults.py) + return {"flow": flow, "options": options} def _verify_creation(db, row, credential): @@ -300,6 +302,17 @@ def login_options(db, origin): def login_finish(db, flow, credential): """The account the passkey belongs to (active), after checking the browser's signature. PasskeyError otherwise.""" row = _claim(db, flow, "login") + pk = verified(db, row, credential) + u = auth.active_account(db, pk["account"]) + if not u: + raise PasskeyError("this account is disabled") + db.q("UPDATE $r SET last_login_at = $t", r=R("account", u["id"]), t=store.now()) + return u + + +def verified(db, row, credential): + """The passkey that signed the browser's answer to a flow (`row`, claimed), with its use recorded; PasskeyError + when it isn't one of this site's or the signature doesn't check out.""" cred_id = credential.get("id") if isinstance(credential, dict) else None pk = db.one("SELECT * FROM $r", r=R("passkey", auth.sha(cred_id))) if isinstance(cred_id, str) and cred_id else None if not pk or pk.get("rp_id") != row["rp_id"]: @@ -320,9 +333,6 @@ def login_finish(db, flow, credential): ) except (WebAuthnException, ValueError, KeyError, TypeError) as e: raise PasskeyError(f"the passkey couldn't be checked: {e}") from None - u = auth.active_account(db, pk["account"]) - if not u: - raise PasskeyError("this account is disabled") db.q( "UPDATE $r SET sign_count = $c, last_used_at = $t, backed_up = $b", r=R("passkey", auth.sha(cred_id)), @@ -330,8 +340,7 @@ def login_finish(db, flow, credential): t=store.now(), b=bool(v.credential_backed_up), ) - db.q("UPDATE $r SET last_login_at = $t", r=R("account", u["id"]), t=store.now()) - return u + return pk # ---------- login tickets ---------- @@ -391,6 +400,14 @@ def remove(db, uid, pid, passwords_on=False, here=None): r = _find(db, uid, pid) if not r: return False + from . import vaults + + if only := vaults.guards(db, pid): + names = store.space_names(db) + raise ValueError( + f"this passkey is the only one that opens {', '.join(names.get(s, str(s)) for s in only)}: add another passkey to " + "the vault first, or its files are lost" + ) if not (passwords_on and has_password(db, uid)): if count(db, uid) <= 1: raise ValueError("this is your last passkey: add another one first, or you couldn't sign in") diff --git a/fastapi_backend/app/domain/store.py b/fastapi_backend/app/domain/store.py index 8f1991eba..5daac4409 100644 --- a/fastapi_backend/app/domain/store.py +++ b/fastapi_backend/app/domain/store.py @@ -340,7 +340,7 @@ def labels(): # endpoint's auth. prices: {model: {input, output}} in USD per million tokens, for cost estimates. # encryption at rest (docs/encryption.md): files Lens keeps under data_dir, encrypted with their namespace's key; # work_minutes: how long a plain working copy for ffmpeg and the other tools is kept after its last use - "encryption": {"files": False, "work_minutes": 30}, + "encryption": {"files": False, "work_minutes": 30, "vault_minutes": 60}, "telemetry": { "enabled": False, "endpoint": None, diff --git a/fastapi_backend/app/domain/vaults.py b/fastapi_backend/app/domain/vaults.py new file mode 100644 index 000000000..9cc4b2795 --- /dev/null +++ b/fastapi_backend/app/domain/vaults.py @@ -0,0 +1,202 @@ +"""Vaults: namespaces only their people's passkeys open (docs/encryption.md#vaults). + +A namespace's data key (keyring.py) is normally also wrapped by the server's key, so background work can read it +whenever. Turning a namespace into a vault wraps the key for one of your passkeys, then removes the server's wrapper. +From then on, the server holds nothing that opens it: someone with one of its passkeys has to unlock it, and it stays +open in this process for encryption.vault_minutes (or until locked). While it's locked its files don't open and its +queued work waits. + +A passkey opens a vault through the WebAuthn PRF extension: signing in with the passkey and a salt made for the vault +makes the authenticator compute 32 secret bytes that only it can make again. The browser hands them over with the +signed answer; the key-encryption key is HKDF-SHA-256 of them, and neither is kept. A vault has as many passkeys as +its admins add while it's open, and there is no other way in: lose every one of them and its files are gone for good. +Turning it back into an ordinary namespace wraps the key for the server again. +""" + +from __future__ import annotations + +import base64 +import hashlib +import json + +from webauthn import generate_authentication_options, options_to_json +from webauthn.helpers import base64url_to_bytes +from webauthn.helpers.structs import AuthenticatorTransport, PublicKeyCredentialDescriptor, UserVerificationRequirement + +from . import keyring, passkeys, store + +R = store.R +PREFIX = "passkey:" +KINDS = ("seal", "unlock", "add") + + +class VaultError(ValueError): + """What was asked doesn't fit the vault's state, or the passkey can't open vaults.""" + + +def salt(sid): + """The PRF salt for a namespace: the same every time, so a passkey always makes the same secret for it.""" + return hashlib.sha256(f"lens-vault:{int(sid)}".encode()).digest() + + +def _b64url(b): + return base64.urlsafe_b64encode(b).rstrip(b"=").decode() + + +def _minutes(cfg): + return int((cfg.get("encryption") or {}).get("vault_minutes") or 60) + + +def wrapper_of(pk): + """The keyring wrapper name for a passkey.""" + return PREFIX + passkeys._pid(pk["cred_id"]) + + +def status(db, sid): + """{vault, unlocked, unlocked_until, passkeys: [{id, name, account, email}]} for a namespace.""" + until = keyring.unlocked_until(db, sid) # first: one whose time is up closes + st = keyring.status(db, sid) + names = [w[len(PREFIX) :] for w in st["wrappers"] if w.startswith(PREFIX)] + people = {} + for pk in db.rows("SELECT cred_id, name, account FROM passkey"): + pid = passkeys._pid(pk["cred_id"]) + if pid in names: + people[pid] = pk + emails = {a["id"]: a.get("email") for a in db.rows("SELECT record::id(id) AS id, email FROM account")} if people else {} + return { + "vault": st["vault"], + "unlocked": st["vault"] and bool(st.get("unlocked")), + "unlocked_until": until, + "passkeys": [ + { + "id": pid, + "name": (people.get(pid) or {}).get("name"), + "account": (people.get(pid) or {}).get("account"), + "email": emails.get((people.get(pid) or {}).get("account")), + } + for pid in names + ], + } + + +def options(db, origin, uid, sid, kind): + """Options for signing with one of your passkeys on this site, asking it for the vault's PRF secret.""" + if kind not in KINDS: + raise VaultError(f"kind is one of {', '.join(KINDS)}") + origin, rp_id = passkeys.site(origin) + mine = db.rows("SELECT cred_id, transports FROM passkey WHERE account = $a AND rp_id = $p", a=uid, p=rp_id) + if kind == "unlock": # only the passkeys that open it + opens = set(keyring.status(db, sid)["wrappers"]) + mine = [p for p in mine if wrapper_of(p) in opens] + if not mine: + raise VaultError( + "none of your passkeys opens this namespace" if kind == "unlock" else "add a passkey to your account on this site first" + ) + opts = generate_authentication_options( + rp_id=rp_id, + user_verification=UserVerificationRequirement.REQUIRED, + allow_credentials=[ + PublicKeyCredentialDescriptor( + id=base64url_to_bytes(p["cred_id"]), + transports=[AuthenticatorTransport(t) for t in p.get("transports") or [] if t in passkeys.TRANSPORTS], + ) + for p in mine + ], + ) + out = json.loads(options_to_json(opts)) + out["extensions"] = {"prf": {"eval": {"first": _b64url(salt(sid))}}} + flow = passkeys._start(db, "vault", origin, rp_id, opts.challenge, uid, {"space": int(sid), "kind": kind}) + return {"flow": flow, "options": out} + + +def _answer(db, uid, sid, kind, flow, credential, prf): + """(the passkey, its key-encryption key) once the browser's answer checks out for this vault and purpose.""" + row = passkeys._claim(db, flow, "vault") + data = row.get("data") or {} + if row.get("account") != uid or data.get("space") != int(sid) or data.get("kind") != kind: + raise passkeys.PasskeyError("that answer was for something else; try again") + pk = passkeys.verified(db, row, credential) + if pk["account"] != uid: + raise passkeys.PasskeyError("use one of your own passkeys") + try: + secret = base64.urlsafe_b64decode((prf or "") + "=" * (-len(prf or "") % 4)) + except (ValueError, TypeError): + secret = b"" + if len(secret) != 32: + raise VaultError( + "this passkey can't open vaults (it doesn't support the PRF extension); use a newer phone, computer or security key" + ) + return pk, keyring.derive(secret, "lens/vault/v1", salt=salt(sid)) + + +def seal(db, cfg, uid, sid, flow, credential, prf): + """Make the namespace a vault opened by this passkey. It stays open here for encryption.vault_minutes.""" + if keyring.status(db, sid)["vault"]: + raise VaultError("this namespace is a vault already") + pk, kek = _answer(db, uid, sid, "seal", flow, credential, prf) + keyring.add_wrapper(db, cfg, sid, wrapper_of(pk), kek) + keyring.remove_wrapper(db, sid, keyring.SERVER) + keyring.keep_open(db, sid, _minutes(cfg)) + return status(db, sid) + + +def unlock(db, cfg, uid, sid, flow, credential, prf): + """Open the vault with one of its passkeys, for encryption.vault_minutes.""" + pk, kek = _answer(db, uid, sid, "unlock", flow, credential, prf) + keyring.unlock(db, sid, wrapper_of(pk), kek, _minutes(cfg)) + return status(db, sid) + + +def add(db, cfg, uid, sid, flow, credential, prf): + """Let another passkey (yours, or another admin's) open the vault; it must be open.""" + _open(db, sid) + pk, kek = _answer(db, uid, sid, "add", flow, credential, prf) + keyring.add_wrapper(db, cfg, sid, wrapper_of(pk), kek) + return status(db, sid) + + +def remove(db, sid, pid): + """Stop a passkey opening the vault; never the last one.""" + name = PREFIX + pid + if name not in keyring.status(db, sid)["wrappers"]: + raise KeyError(pid) + try: + keyring.remove_wrapper(db, sid, name) + except ValueError: + raise VaultError("this is the only passkey that opens this vault; add another first") from None + return status(db, sid) + + +def unseal(db, cfg, sid): + """Make the vault an ordinary namespace again (the server can open it); it must be open.""" + _open(db, sid) + keyring.add_wrapper(db, cfg, sid, keyring.SERVER, keyring.server_kek(cfg)) + keyring.keep_open(db, sid, None) + for pid in [p["id"] for p in status(db, sid)["passkeys"]]: + keyring.remove_wrapper(db, sid, PREFIX + pid) + return status(db, sid) + + +def lock(db, sid): + keyring.lock(db, sid) + return status(db, sid) + + +def _open(db, sid): + st = keyring.status(db, sid) + if not st["vault"]: + raise VaultError("this namespace isn't a vault") + keyring.unlocked_until(db, sid) # a vault whose time is up closes first + if not keyring.status(db, sid).get("unlocked"): + raise keyring.Locked(sid) + + +def guards(db, pid): + """The vaults a passkey is the only way into (removing it would lose them).""" + name = PREFIX + pid + out = [] + for row in db.rows("SELECT space, keys, current FROM data_key WHERE vault = true"): + w = row["keys"][str(row["current"])]["wrapped"] + if name in w and len([k for k in w if k.startswith(PREFIX)]) == 1: + out.append(row["space"]) + return out diff --git a/fastapi_backend/app/schemas/namespaces.py b/fastapi_backend/app/schemas/namespaces.py index f99859497..16156ef87 100644 --- a/fastapi_backend/app/schemas/namespaces.py +++ b/fastapi_backend/app/schemas/namespaces.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import Literal +from typing import Any, Literal from pydantic import Field @@ -100,3 +100,32 @@ class IpGroupUpdate(RequestModel): name: str | None = Field(None, min_length=1, max_length=80) ranges: list[str] | None = Field(None, min_length=1, max_length=100) everything: bool | None = None + + +class VaultPasskey(ResponseModel): + """A passkey that opens a vault.""" + + id: str + name: str | None = None + account: int | None = None + email: str | None = None + + +class VaultStatus(ResponseModel): + """Whether a namespace is a vault, whether it's open on this server (until when, a Unix time), and the passkeys that + open it.""" + + vault: bool + unlocked: bool + unlocked_until: float | None = None + passkeys: list[VaultPasskey] = [] + + +class VaultStart(RequestModel): + kind: Literal["seal", "unlock", "add"] = Field(description="seal: make it a vault; unlock: open it; add: let another passkey open it") + + +class VaultAnswer(RequestModel): + flow: str + credential: dict[str, Any] = Field(description="the browser's PublicKeyCredential, as JSON, without its PRF results") + prf: str = Field(description="the PRF extension's first result for the salt in the options, base64url") diff --git a/fastapi_backend/tests/api/test_vaults.py b/fastapi_backend/tests/api/test_vaults.py new file mode 100644 index 000000000..af9edaa00 --- /dev/null +++ b/fastapi_backend/tests/api/test_vaults.py @@ -0,0 +1,133 @@ +"""Vaults: namespaces only their people's passkeys open (app/domain/vaults.py).""" + +from __future__ import annotations + +import time + +from app.domain import jobs, keyring, store +from tests.api.test_passkeys import ORIGIN, WEB, _session, _setup +from tests.fake_authenticator import Authenticator +from tests.helpers import write_wav + +R = store.R + + +def _upload(client, h, data, name="talk.wav"): + r = client.post("/api/v1/uploads", headers=h, json={"namespace": "pods", "filename": name, "size": len(data)}) + assert r.status_code == 201, r.text + return client.put(f"/api/v1/uploads/{r.json()['id']}?offset=0", headers={**h, "Content-Type": "application/octet-stream"}, content=data) + + +def _ask(client, h, device, kind, path, cred_id=None, prf=True): + """A vault step done with a passkey: options, the device's answer, and the PRF secret sent beside it.""" + o = client.post("/api/v1/namespaces/pods/vault/options", json={"kind": kind}, headers={**h, **WEB}) + assert o.status_code == 200, o.text + o = o.json() + cred = device.get(o["options"], ORIGIN, cred_id) + secret = cred.pop("clientExtensionResults").get("prf", {}).get("results", {}).get("first", "") if prf else "" + return client.post(path, json={"flow": o["flow"], "credential": cred, "prf": secret}, headers=h) + + +def test_a_vault_opens_only_with_its_passkeys(app, client, db, folder): + laptop, phone = Authenticator(), Authenticator() + h = _session(client, _setup(app, client, laptop)) + wav = folder / "talk.wav" + write_wav(wav, seconds=1.0) + data = wav.read_bytes() + rid = _upload(client, h, data).json()["recording"] + sid = store.ns_id(db, "pods") + assert client.get("/api/v1/namespaces/pods/vault", headers=h).json() == { + "vault": False, + "unlocked": False, + "unlocked_until": None, + "passkeys": [], + } + + # sealed with the laptop's passkey: the server's own key no longer opens it + o = client.post("/api/v1/namespaces/pods/vault/options", json={"kind": "seal"}, headers={**h, **WEB}).json() + assert o["options"]["extensions"]["prf"]["eval"]["first"] + r = _ask(client, h, laptop, "seal", "/api/v1/namespaces/pods/vault") + assert r.status_code == 200, r.text + st = r.json() + assert st["vault"] and st["unlocked"] and st["unlocked_until"] > time.time() and len(st["passkeys"]) == 1 + row = db.one("SELECT * FROM $r", r=R("data_key", sid)) + assert row["vault"] and "server" not in row["keys"]["1"]["wrapped"] + assert client.get(f"/api/v1/recordings/{rid}/audio", headers=h).content == data # open for now + + # locked: its files don't open, and its work waits + assert client.post("/api/v1/namespaces/pods/vault/lock", headers=h).json()["unlocked"] is False + assert client.get(f"/api/v1/recordings/{rid}/audio", headers=h).status_code == 423 + db._data_keys.clear() # nor in a fresh process: nothing the server keeps opens it + assert client.get(f"/api/v1/recordings/{rid}/audio", headers=h).status_code == 423 + assert db.values("SELECT VALUE id FROM job WHERE status = 'queued' AND space = $s", s=sid) # the upload's pipeline + assert sid in keyring.locked_vaults(db) and jobs.claim(db, "w", set(jobs.STEPS)) is None + + # unlocked with its passkey: it plays, and the work goes on + r = _ask(client, h, laptop, "unlock", "/api/v1/namespaces/pods/vault/unlock") + assert r.status_code == 200 and r.json()["unlocked"], r.text + assert client.get(f"/api/v1/recordings/{rid}/audio", headers=h).content == data + assert jobs.claim(db, "w", set(jobs.STEPS)) is not None + + # a second passkey opens it too; then the first can be let go + o = client.post("/api/v1/auth/passkeys/options", headers={**h, **WEB}).json() + client.post("/api/v1/auth/passkeys", json={"flow": o["flow"], "credential": phone.create(o["options"], ORIGIN), "name": "Phone"}, headers=h) + phone_id = next(iter(phone.keys)) + r = _ask(client, h, phone, "add", "/api/v1/namespaces/pods/vault/passkeys", cred_id=phone_id) + assert r.status_code == 200 and len(r.json()["passkeys"]) == 2, r.text + keyring.lock(db, sid) + assert _ask(client, h, phone, "unlock", "/api/v1/namespaces/pods/vault/unlock", cred_id=phone_id).status_code == 200 + + # the only passkey that opens a vault can't be removed, from the vault or from the account + mine = {k["name"]: k["id"] for k in client.get("/api/v1/auth/passkeys", headers=h).json()} + assert client.delete(f"/api/v1/namespaces/pods/vault/passkeys/{mine['Laptop']}", headers=h).status_code == 200 + last = client.delete(f"/api/v1/namespaces/pods/vault/passkeys/{mine['Phone']}", headers=h) + assert last.status_code == 400 and "only passkey" in last.json()["detail"] + gone = client.delete(f"/api/v1/auth/passkeys/{mine['Phone']}", headers={**h, **WEB}) + assert gone.status_code == 400 and "pods" in gone.json()["detail"] + keyring.lock(db, sid) + laptop_id = next(iter(laptop.keys)) + assert client.post("/api/v1/namespaces/pods/vault/options", json={"kind": "unlock"}, headers={**h, **WEB}).json()["options"][ + "allowCredentials" + ] == [{"id": phone_id, "type": "public-key", "transports": ["internal", "hybrid"]}] # only the passkeys that open it + assert laptop_id not in str(keyring.status(db, sid)["wrappers"]) + + # an ordinary namespace again: the server opens it whenever + assert client.delete("/api/v1/namespaces/pods/vault", headers=h).status_code == 423 # it must be open for that + _ask(client, h, phone, "unlock", "/api/v1/namespaces/pods/vault/unlock", cred_id=phone_id) + r = client.delete("/api/v1/namespaces/pods/vault", headers=h) + assert r.status_code == 200 and r.json()["vault"] is False and r.json()["passkeys"] == [] + db._data_keys.clear() + assert client.get(f"/api/v1/recordings/{rid}/audio", headers=h).content == data + log = db.values("SELECT VALUE action FROM audit_log") + assert {"vault.seal", "vault.unlock", "vault.add", "vault.remove", "vault.lock", "vault.unseal"} <= set(log) + + +def test_a_vault_closes_once_its_time_is_up(app, client, db): + laptop = Authenticator() + h = _session(client, _setup(app, client, laptop)) + assert _ask(client, h, laptop, "seal", "/api/v1/namespaces/pods/vault").status_code == 200 + sid = store.ns_id(db, "pods") + db._vault_until[sid] = time.time() - 1 + assert client.get("/api/v1/namespaces/pods/vault", headers=h).json()["unlocked"] is False + assert sid in keyring.locked_vaults(db) + + +def test_a_passkey_without_prf_or_the_wrong_answer_is_refused(app, client, db): + laptop = Authenticator() + h = _session(client, _setup(app, client, laptop)) + r = _ask(client, h, laptop, "seal", "/api/v1/namespaces/pods/vault", prf=False) + assert r.status_code == 400 and "PRF" in r.json()["detail"] + assert client.get("/api/v1/namespaces/pods/vault", headers=h).json()["vault"] is False + assert _ask(client, h, laptop, "seal", "/api/v1/namespaces/pods/vault").status_code == 200 + client.post("/api/v1/namespaces/pods/vault/lock", headers=h) + o = client.post("/api/v1/namespaces/pods/vault/options", json={"kind": "unlock"}, headers={**h, **WEB}).json() + cred = laptop.get(o["options"], ORIGIN) + cred.pop("clientExtensionResults") + wrong = client.post( + "/api/v1/namespaces/pods/vault/unlock", json={"flow": o["flow"], "credential": cred, "prf": "A" * 43}, headers=h + ) + assert wrong.status_code == 423 + # an answer for unlocking can't seal, and API tokens can't do either + raw = client.post("/api/v1/tokens", json={"name": "t", "scope": "write"}, headers=h).json()["token"] + t = {"Authorization": f"Bearer {raw}"} + assert client.post("/api/v1/namespaces/pods/vault/options", json={"kind": "unlock"}, headers={**t, **WEB}).status_code == 403 diff --git a/fastapi_backend/tests/fake_authenticator.py b/fastapi_backend/tests/fake_authenticator.py index d57a4ad2d..f870b64ea 100644 --- a/fastapi_backend/tests/fake_authenticator.py +++ b/fastapi_backend/tests/fake_authenticator.py @@ -3,6 +3,7 @@ from __future__ import annotations import hashlib +import hmac import json import os import struct @@ -17,9 +18,9 @@ class Authenticator: """Keeps its passkeys: {credential id: (key, rp id, user handle, counter)}.""" - def __init__(self, counter: bool = True): + def __init__(self, counter: bool = True, prf: bool = True): self.keys: dict[str, dict] = {} - self.counter = counter + self.counter, self.prf = counter, prf def _client_data(self, kind, challenge, origin): return json.dumps({"type": kind, "challenge": challenge, "origin": origin, "crossOrigin": False}).encode() @@ -34,7 +35,7 @@ def create(self, options: dict, origin: str, rp_id: str | None = None, uv: bool flags = UP | AT | (UV if uv else 0) auth_data = hashlib.sha256(rp_id.encode()).digest() + bytes([flags]) + struct.pack(">I", 0) + attested cid = bytes_to_base64url(cred_id) - self.keys[cid] = {"key": key, "rp_id": rp_id, "user": options["user"]["id"], "count": 0} + self.keys[cid] = {"key": key, "rp_id": rp_id, "user": options["user"]["id"], "count": 0, "secret": os.urandom(32)} return { "id": cid, "rawId": cid, @@ -65,9 +66,18 @@ def get(self, options: dict, origin: str, cred_id: str | None = None, uv: bool = "signature": bytes_to_base64url(sig), "userHandle": k["user"], }, - "clientExtensionResults": {}, + "clientExtensionResults": self._prf(k, options), } + def _prf(self, k, options): + """The PRF extension's result for the salt asked for, as a browser's toJSON() gives it: secret to the passkey, + the same every time for the same salt.""" + first = ((options.get("extensions") or {}).get("prf") or {}).get("eval", {}).get("first") + if not (self.prf and first): + return {} + out = hmac.new(k["secret"], base64url_to_bytes(first), "sha256").digest() + return {"prf": {"results": {"first": bytes_to_base64url(out)}}} + def user_handle(credential: dict) -> bytes: return base64url_to_bytes(credential["response"]["userHandle"]) From 580b1af98ec655ec30a13aa6311e9b552dfc5c0a Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 4 Oct 2026 02:39:29 +0000 Subject: [PATCH 2/3] feat(security): lock a namespace to your passkeys Vault panel on each namespace's page (seal, unlock, lock, add and remove passkeys, make ordinary again), a PRF signing helper, a vault encrypting its files even with encryption.files off, vault_minutes validation, docs and changelog. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01R1moYBoaoY4cZFbhBWqzEJ --- CHANGELOG.md | 5 + docs/encryption.md | 33 +- fastapi_backend/app/api/streaming.py | 4 +- fastapi_backend/app/domain/keyring.py | 16 +- fastapi_backend/app/domain/settings.py | 4 + fastapi_backend/app/domain/vaults.py | 13 +- fastapi_backend/tests/api/test_vaults.py | 21 + .../__tests__/vault-section.test.tsx | 123 ++++ nextjs-frontend/__tests__/webauthn.test.ts | 44 ++ nextjs-frontend/app/openapi-client/index.ts | 45 ++ nextjs-frontend/app/openapi-client/sdk.gen.ts | 157 ++++++ .../app/openapi-client/types.gen.ts | 331 +++++++++++ .../components/admin/namespaces.tsx | 2 + .../components/vaults/vault-section.tsx | 261 +++++++++ nextjs-frontend/lib/auth/webauthn.ts | 34 ++ nextjs-frontend/openapi.json | 523 ++++++++++++++++++ 16 files changed, 1603 insertions(+), 13 deletions(-) create mode 100644 nextjs-frontend/__tests__/vault-section.test.tsx create mode 100644 nextjs-frontend/components/vaults/vault-section.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 53ff8da9b..56f10f8cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version ## Unreleased +- **Lock a namespace to your passkeys.** An owner turns a namespace into a vault (Admin › Namespaces › Vault): its + files open only after one of its passkeys unlocks it, for an hour by default (`encryption.vault_minutes`), and its + queued work waits while it's locked. The passkey's WebAuthn PRF secret makes the key; the server keeps nothing that + opens it, and there is no recovery code, so add a second passkey. Owners add and remove passkeys while it's open + (never the last one) and can make it ordinary again. See docs/encryption.md#vaults. - **Hardening.** Sign-in throttles count each visitor behind the web app (Docker) instead of one bucket for everyone, so one person's wrong tries can't lock others out and nobody gets unlimited tries. The web app's pages send nosniff, referrer, permissions and frame policies, and HSTS when reached through Cloudflare. The containers run with diff --git a/docs/encryption.md b/docs/encryption.md index 76a209477..77226be44 100644 --- a/docs/encryption.md +++ b/docs/encryption.md @@ -6,11 +6,9 @@ Lens encrypts with AES-256-GCM. Each namespace has its own random data key, and | Wrapper | Where its key comes from | What it allows | | --- | --- | --- | | `server` | HKDF-SHA-256 of the server's secret (`ARCHIVE_SECRET_KEY`, or `data_dir/secret.key`) | Background work (transcription, embeddings, search, routines, the assistant) reads the namespace without anyone signed in | -| `passkey:` | The passkey's WebAuthn PRF output (coming with passkey vaults) | The namespace opens when its owner signs in with that passkey | +| `passkey:` | HKDF-SHA-256 of the passkey's WebAuthn PRF output for the namespace | A vault opens when one of its owners unlocks it with that passkey | -A namespace whose `server` wrapper is removed is a **vault**. Only one of its passkeys can open it, and its contents -are processed only while it is unlocked. Register more than one passkey for a vault: if every passkey that opens it -is lost, its data can't be recovered by anyone. +A namespace whose `server` wrapper is removed is a **vault** (see [Vaults](#vaults)). Encrypted files are written in 64 KiB chunks, so audio and video can still seek. The last chunk is marked, so a file that has been cut short, edited or reordered fails to open instead of reading as something else. Key rotation adds a @@ -45,5 +43,32 @@ What isn't encrypted by Lens: the SurrealDB database itself, including transcrip and semantic search need, and your own folders that Lens scans (it only reads them). Put the data volume on an encrypted disk (LUKS, FileVault, BitLocker or an encrypted ZFS dataset) to cover these. +## Vaults + +A vault is a namespace only its owners' passkeys open: the server keeps nothing that opens its files on its own. +Owners turn one on in Admin › Namespaces › the namespace › **Vault** with "Lock to my passkey". + +* **How a passkey opens it.** Unlocking is a passkey prompt that also asks the passkey, through the WebAuthn PRF + extension, for a secret made from a salt for that namespace (`sha256("lens-vault:")`). Only that passkey can + make the same secret again. The browser sends it beside the signed answer, Lens derives the key-encryption key from + it with HKDF-SHA-256, unwraps the data key, and keeps neither. Recent phones, computers, password managers and + security keys support PRF; a passkey that doesn't is refused with a message saying so. +* **Unlocked for a while.** A vault stays open in the API process for `encryption.vault_minutes` (60 by default) + after each unlock, or until someone presses "Lock now". Locked, its files don't play or download (the API answers + 423), and its queued work waits; it runs once the vault is unlocked again. Workers running in a separate process + never get the key, so they skip vault jobs. +* **More than one passkey.** While it's open, owners add their passkeys with "Add one of my passkeys". The last + passkey that opens a vault can't be removed, from the vault or from the account. +* **No other way in.** There is no recovery code, password or admin override. If every passkey that opens a vault is + lost, its files can't be recovered by anyone. Add a second passkey (a phone or a security key) right away. +* **Its files are always encrypted.** Turning a namespace into a vault encrypts its files that aren't yet (when + `encryption.files` is off), in the background, and new ones are encrypted as they're stored. Files in folders Lens + scans stay as they are. +* **Turning it back.** "Make it ordinary again" (while it's open) wraps the key for the server again and drops the + passkey wrappers. Its files stay encrypted, now with a key the server can open. + +A vault covers its files. Its transcripts, search indexes and other details are in the database like every other +namespace's (see above). + Keep `ARCHIVE_SECRET_KEY` (or `secret.key`) safe and backed up separately from the data. Without it, nothing encrypted with the server key can be read. diff --git a/fastapi_backend/app/api/streaming.py b/fastapi_backend/app/api/streaming.py index ef807e6b8..47baa1b33 100644 --- a/fastapi_backend/app/api/streaming.py +++ b/fastapi_backend/app/api/streaming.py @@ -54,7 +54,9 @@ def _plain_size(db: Any, cfg: dict[str, Any] | None, path: str | os.PathLike[str try: return keyring.plain_size(db, cfg, path) except keyring.Locked: - raise HTTPException(423, "this namespace is locked; unlock it with your passkey") from None + raise HTTPException( + 423, "this namespace is a locked vault: its owners unlock it with a passkey, on its page in Admin, Namespaces" + ) from None except keyring.Damaged: raise HTTPException(500, "this file is damaged on the server and can't be opened") from None diff --git a/fastapi_backend/app/domain/keyring.py b/fastapi_backend/app/domain/keyring.py index b500b3a5d..8a22c8e25 100644 --- a/fastapi_backend/app/domain/keyring.py +++ b/fastapi_backend/app/domain/keyring.py @@ -531,10 +531,10 @@ def owned(cfg, path) -> bool: def protect(db, cfg, sid, path) -> bool: - """Encrypt a file Lens has just stored (so it is plain, whatever its first bytes), when encryption.files is on; its - modification time is kept. Returns whether it was encrypted. A vault nobody has unlocked here raises Locked: its - files are never stored plain.""" - if not (enabled(cfg) and owned(cfg, path)): + """Encrypt a file Lens has just stored (so it is plain, whatever its first bytes), when encryption.files is on or + the namespace is a vault; its modification time is kept. Returns whether it was encrypted. A vault nobody has + unlocked here raises Locked: its files are never stored plain.""" + if not owned(cfg, path) or not (enabled(cfg) or status(db, sid)["vault"]): return False st = os.stat(path) encrypt_file(db, cfg, sid, path, force=True) @@ -704,11 +704,13 @@ def stored_files(db, cfg): yield f["space"], str(p) -def encrypt_all(db, cfg, decrypt=False, log=print): - """Encrypt (or, with decrypt, turn back) every file Lens keeps; files already that way are skipped, so it can run - again after stopping half way. Returns how many changed.""" +def encrypt_all(db, cfg, decrypt=False, log=print, space=None): + """Encrypt (or, with decrypt, turn back) every file Lens keeps, or one namespace's (`space`); files already that + way are skipped, so it can run again after stopping half way. Returns how many changed.""" changed = 0 for sid, p in stored_files(db, cfg): + if space is not None and sid != int(space): + continue try: st = os.stat(p) done = decrypt_file(db, cfg, p) if decrypt else encrypt_file(db, cfg, sid, p) diff --git a/fastapi_backend/app/domain/settings.py b/fastapi_backend/app/domain/settings.py index 754cc53bc..44a249726 100644 --- a/fastapi_backend/app/domain/settings.py +++ b/fastapi_backend/app/domain/settings.py @@ -342,6 +342,10 @@ def _check(section, key, value, default): if not (isinstance(value, int) and not isinstance(value, bool) and 5 <= value <= 1440): raise ValueError("encryption.work_minutes is a whole number of minutes from 5 to 1440") return value + if (section, key) == ("encryption", "vault_minutes"): + if not (isinstance(value, int) and not isinstance(value, bool) and 1 <= value <= 1440): + raise ValueError("encryption.vault_minutes is a whole number of minutes from 1 to 1440") + return value if section == "embeddings": return _embed_setting(key, value) if section == "uploads": diff --git a/fastapi_backend/app/domain/vaults.py b/fastapi_backend/app/domain/vaults.py index 9cc4b2795..20aa7c0d8 100644 --- a/fastapi_backend/app/domain/vaults.py +++ b/fastapi_backend/app/domain/vaults.py @@ -18,6 +18,8 @@ import base64 import hashlib import json +import logging +import threading from webauthn import generate_authentication_options, options_to_json from webauthn.helpers import base64url_to_bytes @@ -26,6 +28,7 @@ from . import keyring, passkeys, store R = store.R +log = logging.getLogger(__name__) PREFIX = "passkey:" KINDS = ("seal", "unlock", "add") @@ -130,16 +133,24 @@ def _answer(db, uid, sid, kind, flow, credential, prf): def seal(db, cfg, uid, sid, flow, credential, prf): - """Make the namespace a vault opened by this passkey. It stays open here for encryption.vault_minutes.""" + """Make the namespace a vault opened by this passkey. It stays open here for encryption.vault_minutes, and its + files not encrypted yet (encryption.files was off) are encrypted in the background.""" if keyring.status(db, sid)["vault"]: raise VaultError("this namespace is a vault already") pk, kek = _answer(db, uid, sid, "seal", flow, credential, prf) keyring.add_wrapper(db, cfg, sid, wrapper_of(pk), kek) keyring.remove_wrapper(db, sid, keyring.SERVER) keyring.keep_open(db, sid, _minutes(cfg)) + encrypting[int(sid)] = th = threading.Thread( + target=keyring.encrypt_all, args=(db, cfg), kwargs={"space": sid, "log": log.info}, daemon=True, name=f"vault-{sid}" + ) + th.start() # its files stored plain so far (encryption.files was off): new ones are encrypted as they're stored return status(db, sid) +encrypting: dict[int, threading.Thread] = {} + + def unlock(db, cfg, uid, sid, flow, credential, prf): """Open the vault with one of its passkeys, for encryption.vault_minutes.""" pk, kek = _answer(db, uid, sid, "unlock", flow, credential, prf) diff --git a/fastapi_backend/tests/api/test_vaults.py b/fastapi_backend/tests/api/test_vaults.py index af9edaa00..f34280641 100644 --- a/fastapi_backend/tests/api/test_vaults.py +++ b/fastapi_backend/tests/api/test_vaults.py @@ -131,3 +131,24 @@ def test_a_passkey_without_prf_or_the_wrong_answer_is_refused(app, client, db): raw = client.post("/api/v1/tokens", json={"name": "t", "scope": "write"}, headers=h).json()["token"] t = {"Authorization": f"Bearer {raw}"} assert client.post("/api/v1/namespaces/pods/vault/options", json={"kind": "unlock"}, headers={**t, **WEB}).status_code == 403 + + +def test_a_vault_encrypts_its_files_even_with_encryption_off(app, client, db, cfg, folder): + from app.domain import settings, vaults + + settings.save(db, cfg, "encryption", {"files": False}) + laptop = Authenticator() + h = _session(client, _setup(app, client, laptop)) + wav = folder / "talk.wav" + write_wav(wav, seconds=1.0) + data = wav.read_bytes() + rid = _upload(client, h, data).json()["recording"] + old = db.one("SELECT path FROM $r", r=R("recording", rid))["path"] + assert not keyring.is_encrypted(old) + assert _ask(client, h, laptop, "seal", "/api/v1/namespaces/pods/vault").status_code == 200 + vaults.encrypting[store.ns_id(db, "pods")].join(10) + assert keyring.is_encrypted(old) # what it held already + write_wav(wav, seconds=2.0) + new = _upload(client, h, wav.read_bytes(), "new.wav").json()["recording"] + assert keyring.is_encrypted(db.one("SELECT path FROM $r", r=R("recording", new))["path"]) # and what comes in + assert client.get(f"/api/v1/recordings/{rid}/audio", headers=h).content == data diff --git a/nextjs-frontend/__tests__/vault-section.test.tsx b/nextjs-frontend/__tests__/vault-section.test.tsx new file mode 100644 index 000000000..872498e82 --- /dev/null +++ b/nextjs-frontend/__tests__/vault-section.test.tsx @@ -0,0 +1,123 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import "@testing-library/jest-dom"; + +import type { VaultStatus } from "@/app/openapi-client/types.gen"; +import { TooltipProvider } from "@/components/ui/tooltip"; +import { VaultSection } from "@/components/vaults/vault-section"; + +const ok = (data: unknown) => Promise.resolve({ data, response: { ok: true, status: 200 } }); +const fail = (status: number, detail: string) => + Promise.resolve({ error: { detail }, response: { ok: false, status } }); +type Fn = jest.Mock, [unknown]>; +const api: Record = { + getVault: jest.fn(), + vaultOptions: jest.fn(), + sealVault: jest.fn(), + unlockVault: jest.fn(), + addVaultPasskey: jest.fn(), + removeVaultPasskey: jest.fn(), + lockVault: jest.fn(), + unsealVault: jest.fn(), +}; +jest.mock("@/app/openapi-client", () => ({ + Vaults: new Proxy({}, { get: (_t, k: string) => (a: unknown) => api[k](a) }), +})); +const sign = jest.fn(); +jest.mock("@/lib/auth/webauthn", () => ({ + ...jest.requireActual("@/lib/auth/webauthn"), + passkeysUnavailableReason: () => null, + signWithPasskeyPrf: (o: unknown) => sign(o), +})); +jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); +const toast = jest.fn(); +jest.mock("@/components/ui/toast", () => ({ useToast: () => toast })); + +const plain: VaultStatus = { vault: false, unlocked: false, unlocked_until: null, passkeys: [] }; +const laptop = { id: "p1", name: "Laptop", account: 1, email: "ada@x.io" }; +const open = (passkeys = [laptop]): VaultStatus => ({ + vault: true, + unlocked: true, + unlocked_until: Date.now() / 1000 + 3600, + passkeys, +}); + +function show(isOwner = true) { + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + + + + , + ); +} + +beforeEach(() => { + jest.clearAllMocks(); + api.vaultOptions.mockImplementation(() => ok({ flow: "f1", options: { challenge: "AA" } })); + sign.mockResolvedValue({ credential: { id: "c" }, prf: "secret" }); +}); + +describe("a namespace's vault", () => { + it("locks to your passkey after saying what that means", async () => { + api.getVault.mockImplementation(() => ok(plain)); + api.sealVault.mockImplementation(() => ok(open())); + show(); + fireEvent.click(await screen.findByRole("button", { name: "Lock to my passkey" })); + const dialog = await screen.findByRole("dialog"); + expect(within(dialog).getByText(/its files are gone/)).toBeInTheDocument(); + fireEvent.click(within(dialog).getByRole("button", { name: "Lock it" })); + await waitFor(() => expect(api.sealVault).toHaveBeenCalled()); + expect(api.vaultOptions.mock.calls[0][0]).toMatchObject({ path: { name: "pods" }, body: { kind: "seal" } }); + expect(api.sealVault.mock.calls[0][0]).toMatchObject({ + body: { flow: "f1", credential: { id: "c" }, prf: "secret" }, + }); + expect(await screen.findByText(/Unlocked until/)).toBeInTheDocument(); + expect(screen.getByText(/losing this one loses its files/)).toBeInTheDocument(); + }); + + it("unlocks a locked vault, and members who aren't owners can too", async () => { + api.getVault.mockImplementation(() => ok({ ...open(), unlocked: false, unlocked_until: null })); + api.unlockVault.mockImplementation(() => ok(open())); + show(false); + expect(await screen.findByText("Locked")).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Add one of my passkeys" })).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Unlock with my passkey" })); + expect(await screen.findByRole("button", { name: "Lock now" })).toBeInTheDocument(); + expect(api.vaultOptions.mock.calls[0][0]).toMatchObject({ body: { kind: "unlock" } }); + }); + + it("says why a passkey couldn't open it", async () => { + api.getVault.mockImplementation(() => ok({ ...open(), unlocked: false })); + api.unlockVault.mockImplementation(() => + fail(400, "this passkey can't open vaults (it doesn't support the PRF extension)"), + ); + show(); + fireEvent.click(await screen.findByRole("button", { name: "Unlock with my passkey" })); + expect(await screen.findByText(/doesn't support the PRF extension/)).toBeInTheDocument(); + }); + + it("never lets the only passkey go, and adds another while it's open", async () => { + api.getVault.mockImplementation(() => ok(open())); + const phone = { id: "p2", name: "Phone", account: 1, email: "ada@x.io" }; + api.addVaultPasskey.mockImplementation(() => ok(open([laptop, phone]))); + api.removeVaultPasskey.mockImplementation(() => ok(open([phone]))); + show(); + expect(await screen.findByRole("button", { name: /The only passkey that opens it/ })).toBeDisabled(); + fireEvent.click(screen.getByRole("button", { name: "Add one of my passkeys" })); + expect(await screen.findByText("Phone")).toBeInTheDocument(); + fireEvent.click(screen.getAllByRole("button", { name: "Stop this passkey opening the vault" })[0]); + await waitFor(() => expect(screen.queryByText("Laptop")).not.toBeInTheDocument()); + expect(api.removeVaultPasskey.mock.calls[0][0]).toMatchObject({ path: { name: "pods", pid: "p1" } }); + }); + + it("turns back into an ordinary namespace", async () => { + api.getVault.mockImplementation(() => ok(open())); + api.unsealVault.mockImplementation(() => ok(plain)); + show(); + fireEvent.click(await screen.findByRole("button", { name: "Make it ordinary again" })); + fireEvent.click(within(await screen.findByRole("dialog")).getByRole("button", { name: "Make it ordinary" })); + expect(await screen.findByRole("button", { name: "Lock to my passkey" })).toBeInTheDocument(); + }); +}); diff --git a/nextjs-frontend/__tests__/webauthn.test.ts b/nextjs-frontend/__tests__/webauthn.test.ts index 550eee64b..bac9dc8c9 100644 --- a/nextjs-frontend/__tests__/webauthn.test.ts +++ b/nextjs-frontend/__tests__/webauthn.test.ts @@ -3,7 +3,9 @@ import { deviceName, fromB64url, passkeyErrorMessage, + prfRequestOptions, requestOptions, + signWithPasskeyPrf, toB64url, } from "@/lib/auth/webauthn"; @@ -46,3 +48,45 @@ describe("passkey helpers", () => { expect(deviceName("Mozilla/5.0 (Linux; Android 15)")).toBe("Android phone"); }); }); + +describe("vault passkeys (PRF)", () => { + const options = { challenge: "BAUG", rpId: "localhost", extensions: { prf: { eval: { first: "AQID" } } } }; + + it("asks the passkey for the vault's secret with the salt as bytes", () => { + const o = prfRequestOptions(options); + const prf = (o.extensions as { prf: { eval: { first: ArrayBuffer } } }).prf; + expect(new Uint8Array(prf.eval.first)).toEqual(new Uint8Array([1, 2, 3])); + }); + + it("sends the secret beside the answer, never inside it", async () => { + const secret = new Uint8Array(32).fill(7); + const cred = { + id: "abc", + rawId: new Uint8Array([1]).buffer, + type: "public-key", + response: { clientDataJSON: new Uint8Array([2]).buffer, authenticatorData: new Uint8Array([3]).buffer }, + authenticatorAttachment: "platform", + getClientExtensionResults: () => ({ prf: { results: { first: secret.buffer } } }), + }; + const get = jest.fn().mockResolvedValue(cred); + Object.defineProperty(navigator, "credentials", { value: { get }, configurable: true }); + const { credential, prf } = await signWithPasskeyPrf(options); + expect(prf).toBe(toB64url(secret)); + expect(credential.clientExtensionResults).toEqual({}); + expect(JSON.stringify(credential)).not.toContain(prf); + const asked = get.mock.calls[0][0].publicKey; + expect(new Uint8Array(asked.extensions.prf.eval.first)).toEqual(new Uint8Array([1, 2, 3])); + }); + + it("says so when the passkey makes no secret", async () => { + const get = jest.fn().mockResolvedValue({ + id: "abc", + rawId: new Uint8Array([1]).buffer, + type: "public-key", + response: { clientDataJSON: new Uint8Array([2]).buffer, authenticatorData: new Uint8Array([3]).buffer }, + getClientExtensionResults: () => ({}), + }); + Object.defineProperty(navigator, "credentials", { value: { get }, configurable: true }); + expect((await signWithPasskeyPrf(options)).prf).toBe(""); + }); +}); diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index 40f561eb3..ba960ff0f 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -38,6 +38,7 @@ export { Tokens, Uploads, Users, + Vaults, Video, Views, Voice, @@ -74,6 +75,11 @@ export type { AddRecordingPermissionErrors, AddRecordingPermissionResponse, AddRecordingPermissionResponses, + AddVaultPasskeyData, + AddVaultPasskeyError, + AddVaultPasskeyErrors, + AddVaultPasskeyResponse, + AddVaultPasskeyResponses, AnswerCheck, AnswerData, AnswerError, @@ -955,6 +961,11 @@ export type { GetUploadErrors, GetUploadResponse, GetUploadResponses, + GetVaultData, + GetVaultError, + GetVaultErrors, + GetVaultResponse, + GetVaultResponses, GetWorkflowData, GetWorkflowError, GetWorkflowErrors, @@ -1340,6 +1351,11 @@ export type { LlmEstimate, LlmTestResult, LocalModelServer, + LockVaultData, + LockVaultError, + LockVaultErrors, + LockVaultResponse, + LockVaultResponses, LoginData, LoginError, LoginErrors, @@ -1638,6 +1654,11 @@ export type { RemoveRecordingPermissionErrors, RemoveRecordingPermissionResponse, RemoveRecordingPermissionResponses, + RemoveVaultPasskeyData, + RemoveVaultPasskeyError, + RemoveVaultPasskeyErrors, + RemoveVaultPasskeyResponse, + RemoveVaultPasskeyResponses, RenameEntityData, RenameEntityError, RenameEntityErrors, @@ -1806,6 +1827,11 @@ export type { ScanWatchResponse, ScanWatchResponses, SchedulePreview, + SealVaultData, + SealVaultError, + SealVaultErrors, + SealVaultResponse, + SealVaultResponses, SearchCreate, SearchFacets, SearchHit, @@ -2092,6 +2118,16 @@ export type { UnlinkSpeakerErrors, UnlinkSpeakerResponse, UnlinkSpeakerResponses, + UnlockVaultData, + UnlockVaultError, + UnlockVaultErrors, + UnlockVaultResponse, + UnlockVaultResponses, + UnsealVaultData, + UnsealVaultError, + UnsealVaultErrors, + UnsealVaultResponse, + UnsealVaultResponses, UpdateChatData, UpdateChatError, UpdateChatErrors, @@ -2258,6 +2294,15 @@ export type { UserUpdate, UserWithRoles, ValidationError, + VaultAnswer, + VaultOptionsData, + VaultOptionsError, + VaultOptionsErrors, + VaultOptionsResponse, + VaultOptionsResponses, + VaultPasskey, + VaultStart, + VaultStatus, VersionSaved, ViewCreate, ViewerLink, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index bca43a7f5..eeb9627c3 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -28,6 +28,9 @@ import type { AddRecordingPermissionData, AddRecordingPermissionErrors, AddRecordingPermissionResponses, + AddVaultPasskeyData, + AddVaultPasskeyErrors, + AddVaultPasskeyResponses, AnswerData, AnswerErrors, AnswerResponses, @@ -480,6 +483,9 @@ import type { GetUploadData, GetUploadErrors, GetUploadResponses, + GetVaultData, + GetVaultErrors, + GetVaultResponses, GetWorkflowData, GetWorkflowErrors, GetWorkflowResponses, @@ -689,6 +695,9 @@ import type { ListWorkersResponses, ListWorkflowsData, ListWorkflowsResponses, + LockVaultData, + LockVaultErrors, + LockVaultResponses, LoginData, LoginErrors, LoginResponses, @@ -799,6 +808,9 @@ import type { RemoveRecordingPermissionData, RemoveRecordingPermissionErrors, RemoveRecordingPermissionResponses, + RemoveVaultPasskeyData, + RemoveVaultPasskeyErrors, + RemoveVaultPasskeyResponses, RenameEntityData, RenameEntityErrors, RenameEntityResponses, @@ -891,6 +903,9 @@ import type { ScanWatchData, ScanWatchErrors, ScanWatchResponses, + SealVaultData, + SealVaultErrors, + SealVaultResponses, SearchPublicData, SearchPublicErrors, SearchPublicResponses, @@ -1011,6 +1026,12 @@ import type { UnlinkSpeakerData, UnlinkSpeakerErrors, UnlinkSpeakerResponses, + UnlockVaultData, + UnlockVaultErrors, + UnlockVaultResponses, + UnsealVaultData, + UnsealVaultErrors, + UnsealVaultResponses, UpdateChatData, UpdateChatErrors, UpdateChatResponses, @@ -1106,6 +1127,9 @@ import type { UpdateWorkflowResponses, UploadLimitsData, UploadLimitsResponses, + VaultOptionsData, + VaultOptionsErrors, + VaultOptionsResponses, VoiceInfoData, VoiceInfoResponses, } from "./types.gen"; @@ -7313,3 +7337,136 @@ export class Voice { }); } } + +export class Vaults { + /** + * Unseal Vault + * + * Make the vault an ordinary namespace again, which the server can open (it must be unlocked). Audited as + * `vault.unseal`. + */ + public static unsealVault( + options: Options, + ): RequestResult { + return (options.client ?? client).delete({ + url: "/api/v1/namespaces/{name}/vault", + ...options, + }); + } + + /** + * Get Vault + * + * Whether the namespace is a vault, whether it's open now, and which passkeys open it. + */ + public static getVault( + options: Options, + ): RequestResult { + return (options.client ?? client).get({ + url: "/api/v1/namespaces/{name}/vault", + ...options, + }); + } + + /** + * Seal Vault + * + * Make the namespace a vault opened by the passkey that answered. From then on only its passkeys open its files; + * lose every one and they're gone. Audited as `vault.seal`. + */ + public static sealVault( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/namespaces/{name}/vault", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } + + /** + * Vault Options + * + * Start making the namespace a vault (owners), unlocking it, or adding a passkey to it (owners): options for the + * browser, which ask the passkey for this vault's PRF secret. + */ + public static vaultOptions( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/namespaces/{name}/vault/options", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } + + /** + * Unlock Vault + * + * Open the vault on this server for encryption.vault_minutes; its waiting work runs. Audited as `vault.unlock`. + */ + public static unlockVault( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/namespaces/{name}/vault/unlock", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } + + /** + * Add Vault Passkey + * + * Let the passkey that answered open the vault too (it must be open). Audited as `vault.add`. + */ + public static addVaultPasskey( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/namespaces/{name}/vault/passkeys", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } + + /** + * Remove Vault Passkey + * + * Stop a passkey opening the vault; never the last one. Audited as `vault.remove`. + */ + public static removeVaultPasskey( + options: Options, + ): RequestResult { + return (options.client ?? client).delete({ + url: "/api/v1/namespaces/{name}/vault/passkeys/{pid}", + ...options, + }); + } + + /** + * Lock Vault + * + * Close the vault on this server now. Audited as `vault.lock`. + */ + public static lockVault( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/namespaces/{name}/vault/lock", + ...options, + }); + } +} diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index 08fa013bd..e3a4f2cc2 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -12930,6 +12930,93 @@ export type ValidationError = { }; }; +/** + * VaultAnswer + */ +export type VaultAnswer = { + /** + * Flow + */ + flow: string; + /** + * Credential + * + * the browser's PublicKeyCredential, as JSON, without its PRF results + */ + credential: { + [key: string]: unknown; + }; + /** + * Prf + * + * the PRF extension's first result for the salt in the options, base64url + */ + prf: string; +}; + +/** + * VaultPasskey + * + * A passkey that opens a vault. + */ +export type VaultPasskey = { + /** + * Id + */ + id: string; + /** + * Name + */ + name?: string | null; + /** + * Account + */ + account?: number | null; + /** + * Email + */ + email?: string | null; + [key: string]: unknown; +}; + +/** + * VaultStart + */ +export type VaultStart = { + /** + * Kind + * + * seal: make it a vault; unlock: open it; add: let another passkey open it + */ + kind: "seal" | "unlock" | "add"; +}; + +/** + * VaultStatus + * + * Whether a namespace is a vault, whether it's open on this server (until when, a Unix time), and the passkeys that + * open it. + */ +export type VaultStatus = { + /** + * Vault + */ + vault: boolean; + /** + * Unlocked + */ + unlocked: boolean; + /** + * Unlocked Until + */ + unlocked_until?: number | null; + /** + * Passkeys + */ + passkeys?: Array; + [key: string]: unknown; +}; + /** * VersionSaved */ @@ -25333,3 +25420,247 @@ export type SpeakTextResponses = { }; export type SpeakTextResponse = SpeakTextResponses[keyof SpeakTextResponses]; + +export type UnsealVaultData = { + body?: never; + path: { + /** + * Name + */ + name: string; + }; + query?: never; + url: "/api/v1/namespaces/{name}/vault"; +}; + +export type UnsealVaultErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type UnsealVaultError = UnsealVaultErrors[keyof UnsealVaultErrors]; + +export type UnsealVaultResponses = { + /** + * Successful Response + */ + 200: VaultStatus; +}; + +export type UnsealVaultResponse = UnsealVaultResponses[keyof UnsealVaultResponses]; + +export type GetVaultData = { + body?: never; + path: { + /** + * Name + */ + name: string; + }; + query?: never; + url: "/api/v1/namespaces/{name}/vault"; +}; + +export type GetVaultErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type GetVaultError = GetVaultErrors[keyof GetVaultErrors]; + +export type GetVaultResponses = { + /** + * Successful Response + */ + 200: VaultStatus; +}; + +export type GetVaultResponse = GetVaultResponses[keyof GetVaultResponses]; + +export type SealVaultData = { + body: VaultAnswer; + path: { + /** + * Name + */ + name: string; + }; + query?: never; + url: "/api/v1/namespaces/{name}/vault"; +}; + +export type SealVaultErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type SealVaultError = SealVaultErrors[keyof SealVaultErrors]; + +export type SealVaultResponses = { + /** + * Successful Response + */ + 200: VaultStatus; +}; + +export type SealVaultResponse = SealVaultResponses[keyof SealVaultResponses]; + +export type VaultOptionsData = { + body: VaultStart; + path: { + /** + * Name + */ + name: string; + }; + query?: never; + url: "/api/v1/namespaces/{name}/vault/options"; +}; + +export type VaultOptionsErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type VaultOptionsError = VaultOptionsErrors[keyof VaultOptionsErrors]; + +export type VaultOptionsResponses = { + /** + * Successful Response + */ + 200: PasskeyOptions; +}; + +export type VaultOptionsResponse = VaultOptionsResponses[keyof VaultOptionsResponses]; + +export type UnlockVaultData = { + body: VaultAnswer; + path: { + /** + * Name + */ + name: string; + }; + query?: never; + url: "/api/v1/namespaces/{name}/vault/unlock"; +}; + +export type UnlockVaultErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type UnlockVaultError = UnlockVaultErrors[keyof UnlockVaultErrors]; + +export type UnlockVaultResponses = { + /** + * Successful Response + */ + 200: VaultStatus; +}; + +export type UnlockVaultResponse = UnlockVaultResponses[keyof UnlockVaultResponses]; + +export type AddVaultPasskeyData = { + body: VaultAnswer; + path: { + /** + * Name + */ + name: string; + }; + query?: never; + url: "/api/v1/namespaces/{name}/vault/passkeys"; +}; + +export type AddVaultPasskeyErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type AddVaultPasskeyError = AddVaultPasskeyErrors[keyof AddVaultPasskeyErrors]; + +export type AddVaultPasskeyResponses = { + /** + * Successful Response + */ + 200: VaultStatus; +}; + +export type AddVaultPasskeyResponse = AddVaultPasskeyResponses[keyof AddVaultPasskeyResponses]; + +export type RemoveVaultPasskeyData = { + body?: never; + path: { + /** + * Name + */ + name: string; + /** + * Pid + */ + pid: string; + }; + query?: never; + url: "/api/v1/namespaces/{name}/vault/passkeys/{pid}"; +}; + +export type RemoveVaultPasskeyErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type RemoveVaultPasskeyError = RemoveVaultPasskeyErrors[keyof RemoveVaultPasskeyErrors]; + +export type RemoveVaultPasskeyResponses = { + /** + * Successful Response + */ + 200: VaultStatus; +}; + +export type RemoveVaultPasskeyResponse = RemoveVaultPasskeyResponses[keyof RemoveVaultPasskeyResponses]; + +export type LockVaultData = { + body?: never; + path: { + /** + * Name + */ + name: string; + }; + query?: never; + url: "/api/v1/namespaces/{name}/vault/lock"; +}; + +export type LockVaultErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type LockVaultError = LockVaultErrors[keyof LockVaultErrors]; + +export type LockVaultResponses = { + /** + * Successful Response + */ + 200: VaultStatus; +}; + +export type LockVaultResponse = LockVaultResponses[keyof LockVaultResponses]; diff --git a/nextjs-frontend/components/admin/namespaces.tsx b/nextjs-frontend/components/admin/namespaces.tsx index aa3a16779..4466f2b55 100644 --- a/nextjs-frontend/components/admin/namespaces.tsx +++ b/nextjs-frontend/components/admin/namespaces.tsx @@ -13,6 +13,7 @@ import { isUnreachable } from "@/components/errors/error-states"; import { NotificationsSection } from "@/components/notifications/notifications-section"; import { runtime } from "@/components/iiif/iiif-model"; import { ChoiceCards } from "@/components/settings/controls"; +import { VaultSection } from "@/components/vaults/vault-section"; import { RoleChip } from "@/components/ui/badge"; import { Banner } from "@/components/ui/banner"; import { Button } from "@/components/ui/button"; @@ -466,6 +467,7 @@ export function NamespaceDetail({ ns }: { ns: string }) { + {known && }
diff --git a/nextjs-frontend/components/vaults/vault-section.tsx b/nextjs-frontend/components/vaults/vault-section.tsx new file mode 100644 index 000000000..2fac6b7f4 --- /dev/null +++ b/nextjs-frontend/components/vaults/vault-section.tsx @@ -0,0 +1,261 @@ +"use client"; + +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { Fingerprint, Lock, LockOpen, Trash2 } from "lucide-react"; +import { useEffect, useState } from "react"; + +import { Vaults, type VaultStatus } from "@/app/openapi-client"; +import { Badge } from "@/components/ui/badge"; +import { Banner } from "@/components/ui/banner"; +import { Button, IconButton } from "@/components/ui/button"; +import { Dialog } from "@/components/ui/dialog"; +import { Skeleton } from "@/components/ui/states"; +import { useToast } from "@/components/ui/toast"; +import { data, useApiClient } from "@/lib/api/browser"; +import { passkeyErrorMessage, passkeysUnavailableReason, signWithPasskeyPrf } from "@/lib/auth/webauthn"; +import { needRole } from "@/lib/hooks/session"; + +type Kind = "seal" | "unlock" | "add"; + +/** "until 14:05" for a Unix time. */ +export function openUntil(unix: number | null | undefined): string { + if (!unix) return ""; + return `until ${new Date(unix * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}`; +} + +/** + * A namespace's vault (docs/encryption.md#vaults), on its page: owners lock it to their passkeys so the server can't + * open its files alone, add and remove the passkeys that open it, or make it ordinary again. Anyone whose passkey + * opens it unlocks it for a while, or locks it now. + */ +export function VaultSection({ ns, isOwner }: { ns: string; isOwner: boolean }) { + const client = useApiClient(); + const qc = useQueryClient(); + const toast = useToast(); + const [error, setError] = useState(null); + const [confirm, setConfirm] = useState<"seal" | "unseal" | null>(null); + const [unavailable, setUnavailable] = useState(null); + useEffect(() => setUnavailable(passkeysUnavailableReason()), []); + const key = ["vault", ns]; + const q = useQuery({ queryKey: key, queryFn: () => data(Vaults.getVault({ client, path: { name: ns } })) }); + const done = (st: VaultStatus) => { + setError(null); + setConfirm(null); + qc.setQueryData(key, st); + }; + const fail = (e: unknown) => { + setConfirm(null); + setError(passkeyErrorMessage(e)); + }; + + // every step that needs a passkey: options, the passkey's answer and its secret for this vault, then the answer + const withPasskey = useMutation({ + mutationFn: async (kind: Kind) => { + const path = { name: ns }; + const start = await data(Vaults.vaultOptions({ client, path, body: { kind } })); + const body = { flow: start.flow, ...(await signWithPasskeyPrf(start.options)) }; + if (kind === "seal") return data(Vaults.sealVault({ client, path, body })); + if (kind === "unlock") return data(Vaults.unlockVault({ client, path, body })); + return data(Vaults.addVaultPasskey({ client, path, body })); + }, + onSuccess: (st, kind) => { + done(st); + toast({ + title: { seal: `${ns} is a vault now`, unlock: `${ns} is unlocked`, add: "Passkey added to the vault" }[kind], + body: kind === "seal" ? "Add a second passkey, so losing one device doesn't lose its files." : undefined, + tone: "green", + }); + }, + onError: fail, + }); + const lock = useMutation({ + mutationFn: () => data(Vaults.lockVault({ client, path: { name: ns } })), + onSuccess: done, + onError: fail, + }); + const unseal = useMutation({ + mutationFn: () => data(Vaults.unsealVault({ client, path: { name: ns } })), + onSuccess: (st) => { + done(st); + toast({ title: `${ns} is an ordinary namespace again`, tone: "green" }); + }, + onError: fail, + }); + const remove = useMutation({ + mutationFn: (pid: string) => data(Vaults.removeVaultPasskey({ client, path: { name: ns, pid } })), + onSuccess: done, + onError: fail, + }); + + const st = q.data; + const keys = st?.passkeys ?? []; + const busy = withPasskey.isPending || lock.isPending || unseal.isPending || remove.isPending; + const waiting = (kind: Kind) => withPasskey.isPending && withPasskey.variables === kind; + const ownerOnly = isOwner ? undefined : needRole("owner", ns); + + return ( +
+
+
+

+ Vault + {st?.vault && + (st.unlocked ? ( + + Unlocked {openUntil(st.unlocked_until)} + + ) : ( + + Locked + + ))} +

+

+ {st?.vault + ? `Only the passkeys below open ${ns}’s files. While it’s locked they don’t play or download, and its queued work waits.` + : `Lock ${ns}’s files to your passkey, so the server can’t open them without you. Background work runs only while it’s unlocked.`} +

+
+ {st && ( +
+ {!st.vault && ( + + )} + {st.vault && !st.unlocked && ( + + )} + {st.vault && st.unlocked && ( + + )} +
+ )} +
+ {error && {error}} + {q.isPending ? ( + + ) : q.isError ? ( + {q.error.message} + ) : st?.vault ? ( + <> +
    + {keys.map((p) => ( +
  • + +
    +
    {p.name || "A passkey"}
    + {p.email &&
    {p.email}
    } +
    + {isOwner && ( + remove.mutate(p.id)} + > + + + )} +
  • + ))} +
+ {isOwner && ( +
+ + +
+ )} + {keys.length === 1 && ( +

+ One passkey opens it. Add another (a phone or a security key), or losing this one loses its files. +

+ )} + + ) : null} + + !o && setConfirm(null)} + title={`Lock ${ns} to your passkey?`} + description="The server stops keeping a key that opens it. Your passkey (and others you add) become the only way in." + actions={ + <> + + + + } + > +
    +
  • There is no recovery code or password. If every passkey that opens it is lost, its files are gone.
  • +
  • It stays unlocked for a while after each unlock, and its queued work runs only then.
  • +
  • + Its files are encrypted now, if they aren’t already. Transcripts, search and other details stay in the + database, which the vault doesn’t cover, and files in folders Lens scans stay as they are. +
  • +
  • Your passkey needs the PRF extension: recent phones, computers and security keys have it.
  • +
+
+ !o && setConfirm(null)} + title={`Make ${ns} an ordinary namespace?`} + description="The server keeps a key that opens it again, so background work runs any time. Its files stay encrypted." + actions={ + <> + + + + } + /> +
+ ); +} diff --git a/nextjs-frontend/lib/auth/webauthn.ts b/nextjs-frontend/lib/auth/webauthn.ts index 8fe71cad7..7a6a64280 100644 --- a/nextjs-frontend/lib/auth/webauthn.ts +++ b/nextjs-frontend/lib/auth/webauthn.ts @@ -131,6 +131,40 @@ export async function signWithPasskey(options: Json, signal?: AbortSignal): Prom return credentialJson(cred); } +/** The options for signing with a passkey that also ask it for a PRF secret (the salt arrives base64url). */ +export function prfRequestOptions(o: Json): PublicKeyCredentialRequestOptions { + const out = requestOptions(o); + const first = ((o.extensions as Json | undefined)?.prf as { eval?: { first?: string } } | undefined)?.eval?.first; + if (first) { + out.extensions = { + ...(out.extensions ?? {}), + prf: { eval: { first: fromB64url(first) } }, + } as AuthenticationExtensionsClientInputs; + } + return out; +} + +type PrfResults = { prf?: { enabled?: boolean; results?: { first?: ArrayBuffer | ArrayBufferView | string } } }; + +/** + * Sign with a passkey and get the PRF secret it makes for the options' salt (vaults: docs/encryption.md#vaults). The + * secret travels beside the answer, never inside it: `prf` is base64url, or "" when the passkey can't make one. + */ +export async function signWithPasskeyPrf( + options: Json, + signal?: AbortSignal, +): Promise<{ credential: Json; prf: string }> { + const publicKey = prfRequestOptions(options); + const cred = (await navigator.credentials.get({ publicKey, signal })) as PublicKeyCredential | null; + if (!cred) throw new DOMException("No passkey was chosen.", "NotAllowedError"); + const first = (cred.getClientExtensionResults?.() as PrfResults | undefined)?.prf?.results?.first; + const prf = typeof first === "string" ? first : (toB64url(first) ?? ""); + const credential = credentialJson(cred); + const ext = { ...((credential.clientExtensionResults as Json | undefined) ?? {}) }; + delete ext.prf; + return { credential: { ...credential, clientExtensionResults: ext }, prf }; +} + /** What to tell someone when the browser's passkey prompt fails. */ export function passkeyErrorMessage(err: unknown, making = false): string { const name = err instanceof DOMException || err instanceof Error ? err.name : ""; diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index 1b5b43f9b..98f5ca6e5 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -18772,6 +18772,395 @@ } } } + }, + "/api/v1/namespaces/{name}/vault": { + "get": { + "tags": [ + "vaults" + ], + "summary": "Get Vault", + "description": "Whether the namespace is a vault, whether it's open now, and which passkeys open it.", + "operationId": "get_vault", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Name" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VaultStatus" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "post": { + "tags": [ + "vaults" + ], + "summary": "Seal Vault", + "description": "Make the namespace a vault opened by the passkey that answered. From then on only its passkeys open its files;\nlose every one and they're gone. Audited as `vault.seal`.", + "operationId": "seal_vault", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Name" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VaultAnswer" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VaultStatus" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "delete": { + "tags": [ + "vaults" + ], + "summary": "Unseal Vault", + "description": "Make the vault an ordinary namespace again, which the server can open (it must be unlocked). Audited as\n`vault.unseal`.", + "operationId": "unseal_vault", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Name" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VaultStatus" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/v1/namespaces/{name}/vault/options": { + "post": { + "tags": [ + "vaults" + ], + "summary": "Vault Options", + "description": "Start making the namespace a vault (owners), unlocking it, or adding a passkey to it (owners): options for the\nbrowser, which ask the passkey for this vault's PRF secret.", + "operationId": "vault_options", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Name" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VaultStart" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PasskeyOptions" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/v1/namespaces/{name}/vault/unlock": { + "post": { + "tags": [ + "vaults" + ], + "summary": "Unlock Vault", + "description": "Open the vault on this server for encryption.vault_minutes; its waiting work runs. Audited as `vault.unlock`.", + "operationId": "unlock_vault", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Name" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VaultAnswer" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VaultStatus" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/v1/namespaces/{name}/vault/passkeys": { + "post": { + "tags": [ + "vaults" + ], + "summary": "Add Vault Passkey", + "description": "Let the passkey that answered open the vault too (it must be open). Audited as `vault.add`.", + "operationId": "add_vault_passkey", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Name" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VaultAnswer" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VaultStatus" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/v1/namespaces/{name}/vault/passkeys/{pid}": { + "delete": { + "tags": [ + "vaults" + ], + "summary": "Remove Vault Passkey", + "description": "Stop a passkey opening the vault; never the last one. Audited as `vault.remove`.", + "operationId": "remove_vault_passkey", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Name" + } + }, + { + "name": "pid", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Pid" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VaultStatus" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/v1/namespaces/{name}/vault/lock": { + "post": { + "tags": [ + "vaults" + ], + "summary": "Lock Vault", + "description": "Close the vault on this server now. Audited as `vault.lock`.", + "operationId": "lock_vault", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Name" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VaultStatus" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } } }, "components": { @@ -41117,6 +41506,140 @@ ], "title": "ValidationError" }, + "VaultAnswer": { + "properties": { + "flow": { + "type": "string", + "title": "Flow" + }, + "credential": { + "additionalProperties": true, + "type": "object", + "title": "Credential", + "description": "the browser's PublicKeyCredential, as JSON, without its PRF results" + }, + "prf": { + "type": "string", + "title": "Prf", + "description": "the PRF extension's first result for the salt in the options, base64url" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "flow", + "credential", + "prf" + ], + "title": "VaultAnswer" + }, + "VaultPasskey": { + "properties": { + "id": { + "type": "string", + "title": "Id" + }, + "name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Name" + }, + "account": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Account" + }, + "email": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Email" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "id" + ], + "title": "VaultPasskey", + "description": "A passkey that opens a vault." + }, + "VaultStart": { + "properties": { + "kind": { + "type": "string", + "enum": [ + "seal", + "unlock", + "add" + ], + "title": "Kind", + "description": "seal: make it a vault; unlock: open it; add: let another passkey open it" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "kind" + ], + "title": "VaultStart" + }, + "VaultStatus": { + "properties": { + "vault": { + "type": "boolean", + "title": "Vault" + }, + "unlocked": { + "type": "boolean", + "title": "Unlocked" + }, + "unlocked_until": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Unlocked Until" + }, + "passkeys": { + "items": { + "$ref": "#/components/schemas/VaultPasskey" + }, + "type": "array", + "title": "Passkeys", + "default": [] + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "vault", + "unlocked" + ], + "title": "VaultStatus", + "description": "Whether a namespace is a vault, whether it's open on this server (until when, a Unix time), and the passkeys that\nopen it." + }, "VersionSaved": { "properties": { "ok": { From ff9485318ebec5b977fb44e14460ae9e07ba93a4 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 4 Oct 2026 02:47:51 +0000 Subject: [PATCH 3/3] fix(security): close the gaps review found in passkey vaults Encrypt a namespace's files before its server key goes, catch up on unlock, remove a locked vault's working copies, guard admin passkey removal, owners-only lock and passkey owners, 409 on a key race, and no double encryption when a file is swapped mid-check. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01R1moYBoaoY4cZFbhBWqzEJ --- docs/encryption.md | 8 +- fastapi_backend/app/api/v1/routes/passkeys.py | 10 ++- fastapi_backend/app/api/v1/routes/vaults.py | 16 +++- fastapi_backend/app/domain/keyring.py | 79 +++++++++++++++---- fastapi_backend/app/domain/passkeys.py | 16 +++- fastapi_backend/app/domain/vaults.py | 28 ++++--- fastapi_backend/tests/api/test_vaults.py | 64 +++++++++++++-- .../__tests__/vault-section.test.tsx | 3 +- nextjs-frontend/app/openapi-client/sdk.gen.ts | 7 +- .../app/openapi-client/types.gen.ts | 7 +- .../components/vaults/vault-section.tsx | 2 +- nextjs-frontend/openapi.json | 16 +++- 12 files changed, 201 insertions(+), 55 deletions(-) diff --git a/docs/encryption.md b/docs/encryption.md index 77226be44..33adcb56f 100644 --- a/docs/encryption.md +++ b/docs/encryption.md @@ -54,11 +54,13 @@ Owners turn one on in Admin › Namespaces › the namespace › **Vault** with it with HKDF-SHA-256, unwraps the data key, and keeps neither. Recent phones, computers, password managers and security keys support PRF; a passkey that doesn't is refused with a message saying so. * **Unlocked for a while.** A vault stays open in the API process for `encryption.vault_minutes` (60 by default) - after each unlock, or until someone presses "Lock now". Locked, its files don't play or download (the API answers - 423), and its queued work waits; it runs once the vault is unlocked again. Workers running in a separate process + after each unlock, or until an owner presses "Lock now". Locked, its files don't play or download (the API answers + 423), its queued work waits (it runs once the vault is unlocked again), and its plain working copies are removed + as soon as no job is using them. Workers running in a separate process never get the key, so they skip vault jobs. * **More than one passkey.** While it's open, owners add their passkeys with "Add one of my passkeys". The last - passkey that opens a vault can't be removed, from the vault or from the account. + passkey that opens a vault can't be removed, from the vault or from the account, and an admin removing someone's + passkeys (Admin › People) is refused while they are the only way into a vault. * **No other way in.** There is no recovery code, password or admin override. If every passkey that opens a vault is lost, its files can't be recovered by anyone. Add a second passkey (a phone or a security key) right away. * **Its files are always encrypted.** Turning a namespace into a vault encrypts its files that aren't yet (when diff --git a/fastapi_backend/app/api/v1/routes/passkeys.py b/fastapi_backend/app/api/v1/routes/passkeys.py index 49c8cfe7d..36c84f1eb 100644 --- a/fastapi_backend/app/api/v1/routes/passkeys.py +++ b/fastapi_backend/app/api/v1/routes/passkeys.py @@ -292,13 +292,17 @@ def make_signin_link(uid: int, user: AdminWriter, request: Request, db: Db) -> S @people.delete("/users/{uid}/passkeys") -def drop_passkeys(uid: int, user: AdminWriter, db: Db) -> Ok: +def drop_passkeys(uid: int, user: AdminWriter, db: Db, lose_vaults: bool = False) -> Ok: """Remove all of this person's passkeys and end their sessions (a lost or stolen device). Send them a sign-in link - to add a new one. Audited as `user.passkeys_remove`.""" + to add a new one. Refused (409) when they are the only way into a vault, unless lose_vaults=true. Audited as + `user.passkeys_remove`.""" if uid == user.id: raise HTTPException(400, "remove your own passkeys one by one in your account") if not auth.get_account(db, uid): raise HTTPException(404, "not found") - n = passkeys.remove_all(db, uid) + try: + n = passkeys.remove_all(db, uid, lose_vaults) + except ValueError as e: + raise HTTPException(409, str(e)) from None auth.audit(db, user.as_audit(), "user.passkeys_remove", f"account:{uid}", [str(n)]) return Ok() diff --git a/fastapi_backend/app/api/v1/routes/vaults.py b/fastapi_backend/app/api/v1/routes/vaults.py index fbed24247..ca3ccc1f6 100644 --- a/fastapi_backend/app/api/v1/routes/vaults.py +++ b/fastapi_backend/app/api/v1/routes/vaults.py @@ -31,6 +31,8 @@ def _run(fn, *args): return fn(*args) except keyring.Locked: raise HTTPException(423, "this vault is locked; unlock it with one of its passkeys first") from None + except RuntimeError: # its keys changed meanwhile (keyring._save) + raise HTTPException(409, "the vault changed just now; try again") from None except (passkeys.PasskeyError, vaults.VaultError, ValueError) as e: raise HTTPException(400, str(e)) from None except KeyError: @@ -39,8 +41,14 @@ def _run(fn, *args): @router.get("/{name}/vault") def get_vault(name: str, acl: Acl, db: Db) -> VaultStatus: - """Whether the namespace is a vault, whether it's open now, and which passkeys open it.""" - return VaultStatus(**vaults.status(db, acl.namespace(name))) + """Whether the namespace is a vault, whether it's open now, and which passkeys open it (whose, for owners).""" + sid = acl.namespace(name) + out = vaults.status(db, sid) + try: + acl.need(sid, "owner") + except HTTPException: + out["passkeys"] = [{**p, "account": None, "email": None} for p in out["passkeys"]] + return VaultStatus(**out) @router.post("/{name}/vault/options") @@ -91,8 +99,8 @@ 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. Audited as `vault.lock`.""" - sid = acl.namespace(name) + """Close the vault on this server now (owners). Audited as `vault.lock`.""" + sid = acl.namespace(name, "owner") out = _run(vaults.lock, db, sid) auth.audit(db, user.as_audit(), "vault.lock", f"space:{sid}") return VaultStatus(**out) diff --git a/fastapi_backend/app/domain/keyring.py b/fastapi_backend/app/domain/keyring.py index 8a22c8e25..f65d88315 100644 --- a/fastapi_backend/app/domain/keyring.py +++ b/fastapi_backend/app/domain/keyring.py @@ -205,9 +205,12 @@ def _until(db): def _expire(db, sid): """A vault opened for a while closes again once that time is up.""" - t = _until(db).get(sid) - if t is not None and t < time.time(): - lock(db, sid) + with _LOCK: # checked under the lock, so an unlock just now isn't undone + t = _until(db).get(sid) + if t is None or t >= time.time(): + return + _forget(db, sid) + _purge(db, sid) def unlocked_until(db, sid): @@ -241,8 +244,10 @@ def unlock(db, sid, name, kek, minutes=None): opened[(sid, int(v))] = unwrap(kek, entry["wrapped"][name], sid, int(v), name) except Exception: # noqa: BLE001 - wrong key raise Locked(sid) from None - _cache(db).update(opened) - keep_open(db, sid, minutes) + with _LOCK: + _cache(db).update(opened) + keep_open(db, sid, minutes) + _PURGE.discard(sid) def keep_open(db, sid, minutes): @@ -254,12 +259,29 @@ def keep_open(db, sid, minutes): def lock(db, sid): - """Forget a namespace's keys in this process (a vault then needs unlocking again).""" + """Forget a namespace's keys in this process (a vault then needs unlocking again). Its plain working copies go + too: now those nobody holds, the rest when the work holding them ends.""" + with _LOCK: + _forget(db, sid) + _purge(db, sid) + + +def _forget(db, sid): for k in [k for k in _cache(db) if k[0] == int(sid)]: del _cache(db)[k] _until(db).pop(int(sid), None) +def _purge(db, sid): + """A locked vault's working copies go now if nobody holds them, else when the work holding them ends. It doesn't + wait for _WORK: making a copy holds that while it takes _LOCK, which a caller here may hold.""" + if status(db, sid)["vault"]: + _PURGE.add(int(sid)) + for d in list(_WORK_DIRS): + with contextlib.suppress(OSError): + _sweep(d, 0, {int(sid)}, wait=False) + + def rotate(db, cfg, sid, keks=None): """Start a new key version, wrapped by the same keys as the current one; returns its number. A vault's own wrappers need their keys passed in keks ({name: key}), since the server can't wrap for them.""" @@ -463,11 +485,13 @@ def close(self): def encrypt_file(db, cfg, sid, path, chunk=CHUNK, force=False): """Encrypt a file in place (atomically); a file already encrypted is left alone, unless `force` says it's known to be plain (one that has just arrived and only happens to start like one). Returns whether it changed.""" - if not force and is_encrypted(path): - return False - with Writer(db, cfg, sid, path, chunk=chunk) as w, open(path, "rb") as src: - while part := src.read(1024 * 1024): - w.write(part) + with open(path, "rb") as src: # checked on the file read, so one swapped in meanwhile isn't encrypted twice + if not force and src.read(len(MAGIC)) == MAGIC: + return False + src.seek(0) + with Writer(db, cfg, sid, path, chunk=chunk) as w: + while part := src.read(1024 * 1024): + w.write(part) return True @@ -552,14 +576,23 @@ def plain_size(db, cfg, path) -> int: _HELD = threading.local() _WORK = threading.Lock() +_WORK_DIRS: set[pathlib.Path] = set() # where this process has made working copies +_PURGE: set[int] = set() # vaults locked since: their working copies go as soon as nobody holds them def _work_dir(cfg): d = pathlib.Path(cfg["data_dir"]) / "tmp" / "work" d.mkdir(parents=True, exist_ok=True, mode=0o700) + _WORK_DIRS.add(d) return d +def _space_of(path): + with open(path, "rb") as f: + head = f.read(HEADER.size) + return HEADER.unpack(head)[1] if len(head) == HEADER.size else 0 + + def _hold(path): """Keep a shared lock on a working copy until release(), so no sweep (in any process) removes it while in use.""" import fcntl @@ -598,6 +631,8 @@ def work(cfg): release() with contextlib.suppress(Exception): sweep(cfg) + if _PURGE: + _sweep(_work_dir(cfg), 0, set(_PURGE)) def _claim(folder): @@ -630,7 +665,7 @@ def working_copy(db, cfg, path): st = os.stat(path) key = hashlib.sha256(f"{os.path.abspath(path)}:{st.st_size}:{st.st_mtime_ns}".encode()).hexdigest()[:32] - folder = _work_dir(cfg) / key + folder = _work_dir(cfg) / f"{_space_of(path)}-{key}" # by namespace, so locking a vault removes its copies out = folder / pathlib.Path(path).name # its own name: readers go by the extension, and some show the name with _WORK: _make(db, cfg, path, folder, out) @@ -663,17 +698,25 @@ def _make(db, cfg, path, folder, out): def sweep(cfg, minutes=None): """Remove plain working copies nobody holds that have gone unused for encryption.work_minutes. Returns how many went.""" - import shutil - import time - d = pathlib.Path(cfg["data_dir"]) / "tmp" / "work" if not d.is_dir(): return 0 - limit = time.time() - 60 * (minutes if minutes is not None else (cfg.get("encryption") or {}).get("work_minutes") or 30) + return _sweep(d, minutes if minutes is not None else (cfg.get("encryption") or {}).get("work_minutes") or 30) + + +def _sweep(d, minutes, spaces=None, wait=True): + """Remove the working copies in `d` nobody holds, unused for `minutes` (of namespaces `spaces` only, if given).""" + import shutil + + limit = time.time() - 60 * minutes gone = 0 - with _WORK: # not while this process is making or taking one + if not _WORK.acquire(blocking=wait): # not while this process is making or taking one + return 0 + try: for p in d.iterdir(): with contextlib.suppress(OSError): + if spaces is not None and p.name.split("-", 1)[0] not in {str(s) for s in spaces}: + continue if p.stat().st_mtime >= limit: continue locks = _claim(p) @@ -685,6 +728,8 @@ def sweep(cfg, minutes=None): finally: for fd in locks: os.close(fd) + finally: + _WORK.release() return gone diff --git a/fastapi_backend/app/domain/passkeys.py b/fastapi_backend/app/domain/passkeys.py index 57b7eafde..2056b38a0 100644 --- a/fastapi_backend/app/domain/passkeys.py +++ b/fastapi_backend/app/domain/passkeys.py @@ -412,7 +412,7 @@ def remove(db, uid, pid, passwords_on=False, here=None, others=0): return False from . import vaults - if only := vaults.guards(db, pid): + if only := vaults.guards(db, [pid]): names = store.space_names(db) raise ValueError( f"this passkey is the only one that opens {', '.join(names.get(s, str(s)) for s in only)}: add another passkey to " @@ -436,8 +436,18 @@ def has_password(db, uid): return bool((db.one("SELECT pw FROM $r", r=R("account", uid)) or {}).get("pw")) -def remove_all(db, uid): - """An admin removes everyone's passkeys for an account (a lost or stolen device); their sessions end too.""" +def remove_all(db, uid, lose_vaults=False): + """An admin removes everyone's passkeys for an account (a lost or stolen device); their sessions end too. Refused + when they are the only way into a vault, unless `lose_vaults` says its files may be lost.""" + from . import vaults + + pids = [_pid(c) for c in db.values("SELECT VALUE cred_id FROM passkey WHERE account = $a", a=uid)] + if not lose_vaults and (only := vaults.guards(db, pids)): + names = store.space_names(db) + raise ValueError( + f"these passkeys are the only ones that open {', '.join(names.get(s, str(s)) for s in only)}: its files " + "would be lost for good. Have an owner unlock it and add another passkey (or make it ordinary) first" + ) n = len(db.rows("DELETE passkey WHERE account = $a RETURN BEFORE", a=uid)) db.q("DELETE login_session WHERE account = $a", a=uid) return n diff --git a/fastapi_backend/app/domain/vaults.py b/fastapi_backend/app/domain/vaults.py index 20aa7c0d8..1bcd6e7fb 100644 --- a/fastapi_backend/app/domain/vaults.py +++ b/fastapi_backend/app/domain/vaults.py @@ -133,19 +133,26 @@ def _answer(db, uid, sid, kind, flow, credential, prf): def seal(db, cfg, uid, sid, flow, credential, prf): - """Make the namespace a vault opened by this passkey. It stays open here for encryption.vault_minutes, and its - files not encrypted yet (encryption.files was off) are encrypted in the background.""" + """Make the namespace a vault opened by this passkey. Its files not encrypted yet (encryption.files was off) are + encrypted first, while the server's key still opens it, so none is left plain. It then stays open here for + encryption.vault_minutes.""" if keyring.status(db, sid)["vault"]: raise VaultError("this namespace is a vault already") pk, kek = _answer(db, uid, sid, "seal", flow, credential, prf) keyring.add_wrapper(db, cfg, sid, wrapper_of(pk), kek) + keyring.encrypt_all(db, cfg, space=sid, log=log.info) keyring.remove_wrapper(db, sid, keyring.SERVER) keyring.keep_open(db, sid, _minutes(cfg)) + keyring.encrypt_all(db, cfg, space=sid, log=log.info) # any stored while that ran + return status(db, sid) + + +def _catch_up(db, cfg, sid): + """Encrypt, in the background, a vault's files that arrived plain (while it was being made a vault).""" encrypting[int(sid)] = th = threading.Thread( target=keyring.encrypt_all, args=(db, cfg), kwargs={"space": sid, "log": log.info}, daemon=True, name=f"vault-{sid}" ) - th.start() # its files stored plain so far (encryption.files was off): new ones are encrypted as they're stored - return status(db, sid) + th.start() encrypting: dict[int, threading.Thread] = {} @@ -155,6 +162,7 @@ def unlock(db, cfg, uid, sid, flow, credential, prf): """Open the vault with one of its passkeys, for encryption.vault_minutes.""" pk, kek = _answer(db, uid, sid, "unlock", flow, credential, prf) keyring.unlock(db, sid, wrapper_of(pk), kek, _minutes(cfg)) + _catch_up(db, cfg, sid) return status(db, sid) @@ -202,12 +210,14 @@ def _open(db, sid): raise keyring.Locked(sid) -def guards(db, pid): - """The vaults a passkey is the only way into (removing it would lose them).""" - name = PREFIX + pid +def guards(db, pids): + """The vaults these passkeys (ids) are the only way into: removing them would lose them. Wrappers of passkeys + already gone don't count, since nothing can answer for them.""" + gone = {PREFIX + p for p in pids} + live = {PREFIX + passkeys._pid(c) for c in db.values("SELECT VALUE cred_id FROM passkey")} - gone out = [] for row in db.rows("SELECT space, keys, current FROM data_key WHERE vault = true"): - w = row["keys"][str(row["current"])]["wrapped"] - if name in w and len([k for k in w if k.startswith(PREFIX)]) == 1: + w = set(row["keys"][str(row["current"])]["wrapped"]) + if w & gone and not w & live: out.append(row["space"]) return out diff --git a/fastapi_backend/tests/api/test_vaults.py b/fastapi_backend/tests/api/test_vaults.py index f34280641..c5e773fe4 100644 --- a/fastapi_backend/tests/api/test_vaults.py +++ b/fastapi_backend/tests/api/test_vaults.py @@ -2,12 +2,13 @@ from __future__ import annotations +import os import time from app.domain import jobs, keyring, store from tests.api.test_passkeys import ORIGIN, WEB, _session, _setup from tests.fake_authenticator import Authenticator -from tests.helpers import write_wav +from tests.helpers import login, make_user, write_wav R = store.R @@ -70,7 +71,9 @@ def test_a_vault_opens_only_with_its_passkeys(app, client, db, folder): # a second passkey opens it too; then the first can be let go o = client.post("/api/v1/auth/passkeys/options", headers={**h, **WEB}).json() - client.post("/api/v1/auth/passkeys", json={"flow": o["flow"], "credential": phone.create(o["options"], ORIGIN), "name": "Phone"}, headers=h) + client.post( + "/api/v1/auth/passkeys", json={"flow": o["flow"], "credential": phone.create(o["options"], ORIGIN), "name": "Phone"}, headers=h + ) phone_id = next(iter(phone.keys)) r = _ask(client, h, phone, "add", "/api/v1/namespaces/pods/vault/passkeys", cred_id=phone_id) assert r.status_code == 200 and len(r.json()["passkeys"]) == 2, r.text @@ -123,9 +126,7 @@ def test_a_passkey_without_prf_or_the_wrong_answer_is_refused(app, client, db): o = client.post("/api/v1/namespaces/pods/vault/options", json={"kind": "unlock"}, headers={**h, **WEB}).json() cred = laptop.get(o["options"], ORIGIN) cred.pop("clientExtensionResults") - wrong = client.post( - "/api/v1/namespaces/pods/vault/unlock", json={"flow": o["flow"], "credential": cred, "prf": "A" * 43}, headers=h - ) + wrong = client.post("/api/v1/namespaces/pods/vault/unlock", json={"flow": o["flow"], "credential": cred, "prf": "A" * 43}, headers=h) assert wrong.status_code == 423 # an answer for unlocking can't seal, and API tokens can't do either raw = client.post("/api/v1/tokens", json={"name": "t", "scope": "write"}, headers=h).json()["token"] @@ -136,6 +137,7 @@ def test_a_passkey_without_prf_or_the_wrong_answer_is_refused(app, client, db): def test_a_vault_encrypts_its_files_even_with_encryption_off(app, client, db, cfg, folder): from app.domain import settings, vaults + vaults.encrypting.clear() settings.save(db, cfg, "encryption", {"files": False}) laptop = Authenticator() h = _session(client, _setup(app, client, laptop)) @@ -146,9 +148,57 @@ def test_a_vault_encrypts_its_files_even_with_encryption_off(app, client, db, cf old = db.one("SELECT path FROM $r", r=R("recording", rid))["path"] assert not keyring.is_encrypted(old) assert _ask(client, h, laptop, "seal", "/api/v1/namespaces/pods/vault").status_code == 200 - vaults.encrypting[store.ns_id(db, "pods")].join(10) - assert keyring.is_encrypted(old) # what it held already + assert keyring.is_encrypted(old) # what it held already, before the server's key went + assert not vaults.encrypting write_wav(wav, seconds=2.0) new = _upload(client, h, wav.read_bytes(), "new.wav").json()["recording"] assert keyring.is_encrypted(db.one("SELECT path FROM $r", r=R("recording", new))["path"]) # and what comes in assert client.get(f"/api/v1/recordings/{rid}/audio", headers=h).content == data + + +def test_locking_removes_its_plain_working_copies(app, client, db, cfg, folder): + laptop = Authenticator() + h = _session(client, _setup(app, client, laptop)) + wav = folder / "talk.wav" + write_wav(wav, seconds=1.0) + rid = _upload(client, h, wav.read_bytes()).json()["recording"] + path = db.one("SELECT path FROM $r", r=R("recording", rid))["path"] + assert _ask(client, h, laptop, "seal", "/api/v1/namespaces/pods/vault").status_code == 200 + held = keyring.working_copy(db, cfg, path) # a job using it + other = folder / "other.bin" + other.write_bytes(b"x") + keyring.encrypt_file(db, cfg, store.ns_id(db, "calls"), other) + elsewhere = keyring.working_copy(db, cfg, str(other)) # another namespace's + client.post("/api/v1/namespaces/pods/vault/lock", headers=h) + assert os.path.exists(held) # still in use + with keyring.work(cfg): + pass # the job ends + assert not os.path.exists(held) and os.path.exists(elsewhere) + + +def test_only_owners_lock_or_see_whose_passkeys(app, client, db): + laptop = Authenticator() + h = _session(client, _setup(app, client, laptop)) + assert _ask(client, h, laptop, "seal", "/api/v1/namespaces/pods/vault").status_code == 200 + make_user(db, "ed@x.io", "editor password 1", roles={"pods": "editor"}) + he = login(client, "ed@x.io", "editor password 1") + st = client.get("/api/v1/namespaces/pods/vault", headers=he).json() + assert st["vault"] and st["passkeys"][0]["email"] is None + assert client.get("/api/v1/namespaces/pods/vault", headers=h).json()["passkeys"][0]["email"] + assert client.post("/api/v1/namespaces/pods/vault/lock", headers=he).status_code == 403 + + +def test_an_admin_cannot_remove_the_passkeys_that_alone_open_a_vault(app, client, db): + laptop = Authenticator() + h = _session(client, _setup(app, client, laptop)) + assert _ask(client, h, laptop, "seal", "/api/v1/namespaces/pods/vault").status_code == 200 + owner = db.one("SELECT account FROM passkey")["account"] + make_user(db, "boss@x.io", "admin password 12", admin=True) + ha = login(client, "boss@x.io", "admin password 12") + r = client.delete(f"/api/v1/users/{owner}/passkeys", headers=ha) + assert r.status_code == 409 and "pods" in r.json()["detail"] + assert client.delete(f"/api/v1/users/{owner}/passkeys?lose_vaults=true", headers=ha).status_code == 200 + # a vault whose passkeys are all gone guards nothing more + from app.domain import vaults + + assert vaults.guards(db, ["whatever"]) == [] diff --git a/nextjs-frontend/__tests__/vault-section.test.tsx b/nextjs-frontend/__tests__/vault-section.test.tsx index 872498e82..699b7a2e9 100644 --- a/nextjs-frontend/__tests__/vault-section.test.tsx +++ b/nextjs-frontend/__tests__/vault-section.test.tsx @@ -84,7 +84,8 @@ describe("a namespace's vault", () => { expect(await screen.findByText("Locked")).toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Add one of my passkeys" })).not.toBeInTheDocument(); fireEvent.click(screen.getByRole("button", { name: "Unlock with my passkey" })); - expect(await screen.findByRole("button", { name: "Lock now" })).toBeInTheDocument(); + expect(await screen.findByText(/Unlocked until/)).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Lock now" })).not.toBeInTheDocument(); // owners lock it expect(api.vaultOptions.mock.calls[0][0]).toMatchObject({ body: { kind: "unlock" } }); }); diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index eeb9627c3..b12c7754d 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -1811,7 +1811,8 @@ export class Users { * Drop Passkeys * * Remove all of this person's passkeys and end their sessions (a lost or stolen device). Send them a sign-in link - * to add a new one. Audited as `user.passkeys_remove`. + * to add a new one. Refused (409) when they are the only way into a vault, unless lose_vaults=true. Audited as + * `user.passkeys_remove`. */ public static dropPasskeys( options: Options, @@ -7357,7 +7358,7 @@ export class Vaults { /** * Get Vault * - * Whether the namespace is a vault, whether it's open now, and which passkeys open it. + * Whether the namespace is a vault, whether it's open now, and which passkeys open it (whose, for owners). */ public static getVault( options: Options, @@ -7459,7 +7460,7 @@ export class Vaults { /** * Lock Vault * - * Close the vault on this server now. Audited as `vault.lock`. + * Close the vault on this server now (owners). Audited as `vault.lock`. */ public static lockVault( options: Options, diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index e3a4f2cc2..1cf65d144 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -14891,7 +14891,12 @@ export type DropPasskeysData = { */ uid: number; }; - query?: never; + query?: { + /** + * Lose Vaults + */ + lose_vaults?: boolean; + }; url: "/api/v1/users/{uid}/passkeys"; }; diff --git a/nextjs-frontend/components/vaults/vault-section.tsx b/nextjs-frontend/components/vaults/vault-section.tsx index 2fac6b7f4..12b54289c 100644 --- a/nextjs-frontend/components/vaults/vault-section.tsx +++ b/nextjs-frontend/components/vaults/vault-section.tsx @@ -145,7 +145,7 @@ export function VaultSection({ ns, isOwner }: { ns: string; isOwner: boolean }) {waiting("unlock") ? "Waiting for your passkey…" : "Unlock with my passkey"} )} - {st.vault && st.unlocked && ( + {st.vault && st.unlocked && isOwner && ( diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index 98f5ca6e5..c223e832f 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -1531,7 +1531,7 @@ "users" ], "summary": "Drop Passkeys", - "description": "Remove all of this person's passkeys and end their sessions (a lost or stolen device). Send them a sign-in link\nto add a new one. Audited as `user.passkeys_remove`.", + "description": "Remove all of this person's passkeys and end their sessions (a lost or stolen device). Send them a sign-in link\nto add a new one. Refused (409) when they are the only way into a vault, unless lose_vaults=true. Audited as\n`user.passkeys_remove`.", "operationId": "drop_passkeys", "parameters": [ { @@ -1542,6 +1542,16 @@ "type": "integer", "title": "Uid" } + }, + { + "name": "lose_vaults", + "in": "query", + "required": false, + "schema": { + "type": "boolean", + "default": false, + "title": "Lose Vaults" + } } ], "responses": { @@ -18779,7 +18789,7 @@ "vaults" ], "summary": "Get Vault", - "description": "Whether the namespace is a vault, whether it's open now, and which passkeys open it.", + "description": "Whether the namespace is a vault, whether it's open now, and which passkeys open it (whose, for owners).", "operationId": "get_vault", "parameters": [ { @@ -19125,7 +19135,7 @@ "vaults" ], "summary": "Lock Vault", - "description": "Close the vault on this server now. Audited as `vault.lock`.", + "description": "Close the vault on this server now (owners). Audited as `vault.lock`.", "operationId": "lock_vault", "parameters": [ {