Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version
`lens.sources`, streamed or not. Its owners pick the read tools the model may use there (none by default: one search,
one model call). Calls count for the namespace's budget. Off by default; turned on under Admin → Namespaces → the
namespace → Connect apps ([Chat completions for any app](docs/api.md#chat-completions-for-any-app)).
- **API keys for one namespace.** A new API key can be made for one namespace (Opens, on the API tokens page, which
Connect apps fills in). It works on that namespace's own MCP server and chat completions, with your role there, and is
refused everywhere else in Lens, so an app given it sees nothing more ([API tokens](docs/authentication.md#api-tokens)).

## 0.11.0 <small>October 15, 2026</small> {id="0.11.0"}

Expand Down
7 changes: 5 additions & 2 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ GET /api/v1/admin/tokens
DELETE /api/v1/admin/tokens/{token_id}
```

`POST /tokens {name, scope, days?}` makes an API key (while signed in). `days` defaults to `tokens.default_days`; more
`POST /tokens {name, scope, days?, namespace?}` makes an API key (while signed in); with `namespace` (one you can read)
it opens that namespace's own MCP server and chat completions alone, and the list shows it as `namespace`
([API tokens](authentication.md#api-tokens)). `days` defaults to `tokens.default_days`; more
than `tokens.max_days`, or `0` (never expires) when `tokens.never_expire` is off, is a 400. `GET /tokens/limits` says
`{default_days, max_days, never_expire}`. `PATCH /tokens/{token_id} {name}` renames one of your keys (audited as
`token.rename`). `/admin/tokens` lists everyone's keys with their owner's `email` (admins), and
Expand Down Expand Up @@ -328,7 +330,8 @@ A namespace can answer OpenAI's chat completions API, so any app that speaks it
library's OpenAI client) gets answers from the configured model, grounded in that namespace and citing it. Give the app:

- **Base URL**: `https://lens.example.org/api/v1/namespaces/<namespace>` (the app adds `/chat/completions`);
- **API key**: a Lens [API token](authentication.md) (`la_…`; read-only is enough) or an app's OAuth token;
- **API key**: a Lens [API token](authentication.md#api-tokens) (`la_…`; read-only is enough), best one made for
this namespace alone (Connect apps links to it), or an app's OAuth token;
- **Model**: `lens`, the configured model. One of the models people may pick in Lens's chat works too
(`GET …/models` lists them); any other name answers with the configured model.

Expand Down
6 changes: 6 additions & 0 deletions docs/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,12 @@ For scripts and integrations: `POST /api/v1/tokens` (while signed in) returns `l
(`/api/v1/admin/tokens`); both are audited as `token.revoke`. The web app names a new token after its scope ("Read only
token") unless you type a name, and the pencil in the list renames it (`PATCH /api/v1/tokens/{token_id}`).

A token can also be made for **one namespace** (`namespace` on `POST /api/v1/tokens`, or **Opens** in the web app,
which Admin → Namespaces → the namespace → Connect apps fills in). It opens that namespace's own
[MCP server](mcp.md#one-namespaces-mcp-server) and [chat completions](api.md#chat-completions-for-any-app), with your
role there, and nothing else: anywhere else in Lens it is refused (401), so an app given it can't read your other
namespaces or make keys. It stops opening anything if you lose your role there or the namespace is deleted.

```bash
curl -H "Authorization: Bearer la_…" https://lens.example.org/api/v1/resources
```
Expand Down
3 changes: 2 additions & 1 deletion docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ Signing in works as above, from the namespace's own metadata
(`/.well-known/oauth-protected-resource/mcp/<namespace>`, which names `…/mcp/<namespace>` as the resource). A token an
app was given for a namespace's server opens that server and nothing else: not another namespace's, not `/mcp`, not
the API. A token for Lens or for `/mcp` (and an API token) works on every namespace's own server, seeing only that
namespace there.
namespace there. An [API token made for one namespace](authentication.md#api-tokens) works on that namespace's server
(and its chat completions) alone.

For an app that speaks OpenAI's API rather than MCP, the namespace can also answer
[chat completions](api.md#chat-completions-for-any-app), turned on in the same place (Connect apps).
Expand Down
37 changes: 33 additions & 4 deletions fastapi_backend/app/api/deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ class Principal:
perms: dict[int, frozenset[str]] = field(default_factory=dict) # what each namespace role allows (roles.py)
collections: dict[int, dict[int, str]] = field(default_factory=dict) # roles on collections: {space: {collection: role}}
resource: str | None = None # an app's token: the server it was given for (RFC 8707), when the app named one
space: int | None = None # an API key made for one namespace: it opens that namespace's own servers alone (serves)

@property
def can_write(self) -> bool:
Expand Down Expand Up @@ -89,6 +90,17 @@ def bound_to(resource: str | None) -> str | None:
return m.group(1) if m else None


# a namespace's own servers: its MCP server and its chat completions (completions.py)
SERVED = re.compile(r"^/(?:mcp/([a-z0-9_-]+)|api/v1/namespaces/([a-z0-9_-]+)/(?:chat/completions|models))/?$")


def serves(path: str) -> str | None:
"""The namespace whose own server a path is (/mcp/<namespace>, /api/v1/namespaces/<namespace>/chat/completions or
…/models), the only places an API key made for one namespace opens."""
m = SERVED.match(path)
return (m.group(1) or m.group(2)) if m else None


def _principal(request: Request, db: DB) -> Principal | None:
p = _resolve(request, db)
if p: # graph changes made in this request are recorded as theirs (graph_history.py)
Expand All @@ -108,13 +120,15 @@ def _resolve(request: Request, db: DB) -> Principal | None:
p = Principal(
u["id"], u["email"], u.get("name"), bool(u.get("admin")), "token", "write" if u.get("scope") == "write" else "read"
)
p.space = u.get("space")
elif raw.startswith("lo_"):
# with OAuth turned off, apps' tokens stop working at once (their grants stay, so turning it back on restores them)
u = oauth.token_account(db, raw) if oauth.enabled(request.app.state.settings.current()) else None
ns = bound_to(u.get("resource")) if u else None
if ns is not None: # given for one namespace's MCP server: it opens that, and not the rest of Lens
here = MCP_RESOURCE.match(request.url.path)
if not here or here.group(1) != ns:
request.state.refused = f"this app was given {ns}'s MCP server alone"
u = None
if u:
p = Principal(u["id"], u["email"], u.get("name"), bool(u.get("admin")), "oauth", u["scope"], resource=u.get("resource"))
Expand All @@ -127,6 +141,14 @@ def _resolve(request: Request, db: DB) -> Principal | None:
p.perms = auth.permissions(db, {"id": p.id, "admin": p.admin})
p.roles = {sid: rl.rank(perms) for sid, perms in p.perms.items()}
p.collections = {} if p.admin else hierarchy.roles_of(db, p.id)
space = p.space if p else None
if p and space is not None: # a key made for one namespace: its own servers, and nothing else in Lens
ns = store.space_names(db).get(space)
if ns is None or serves(request.url.path) != ns:
request.state.refused = f"this API key opens {ns}'s MCP server and chat completions alone" if ns else None
p = None
else:
p = within(p, space)
request.state.principal = p
return p

Expand All @@ -135,10 +157,17 @@ def optional_user(request: Request, db: Db) -> Principal | None:
return _principal(request, db)


def signed_out(request: Request) -> HTTPException:
"""The 401 for a request without a principal: sign in, or why the key or app given one namespace's servers alone
doesn't open this."""
why = getattr(request.state, "refused", None)
return HTTPException(401, why or "sign in first", headers={"WWW-Authenticate": "Bearer"})


def current_user(request: Request, db: Db) -> Principal:
p = _principal(request, db)
if not p:
raise HTTPException(401, "sign in first", headers={"WWW-Authenticate": "Bearer"})
raise signed_out(request)
return p


Expand Down Expand Up @@ -201,7 +230,7 @@ def can(self, sid: int, perm: str) -> bool:
def need(self, sid: int, role: str = "viewer") -> None:
"""A role (viewer, editor, owner: at least that rank) or a permission (roles.PERMISSIONS) in namespace `sid`."""
if not self.user:
raise HTTPException(401, "sign in first", headers={"WWW-Authenticate": "Bearer"})
raise signed_out(self.request)
if not auth.allows(self.roles, sid, "viewer"):
raise HTTPException(404, "not found")
if role in rl.PERMISSIONS:
Expand Down Expand Up @@ -229,7 +258,7 @@ def role_in(self, sid: int, cid: int | None) -> str | None:
def need_in(self, sid: int, cid: int | None, role: str = "viewer") -> None:
"""Like need, for a recording of collection `cid`: a namespace role or a role on the collection will do."""
if not self.user:
raise HTTPException(401, "sign in first", headers={"WWW-Authenticate": "Bearer"})
raise signed_out(self.request)
have = self.rank_in(sid, cid)
if not have:
raise HTTPException(404, "not found")
Expand All @@ -255,7 +284,7 @@ def scope(self, ns: str | None = None) -> tuple[list[int], dict[int, list[int]]]
return self.spaces(), self.partial()
sid = self.nsid(ns)
if not self.user:
raise HTTPException(401, "sign in first", headers={"WWW-Authenticate": "Bearer"})
raise signed_out(self.request)
if auth.allows(self.roles, sid):
return [sid], {}
part = self.partial().get(sid)
Expand Down
6 changes: 3 additions & 3 deletions fastapi_backend/app/api/mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
from starlette.concurrency import run_in_threadpool

from app.api import mcp_tools
from app.api.deps import Access, Db, Principal, optional_user, within
from app.api.deps import Access, Db, Principal, optional_user, signed_out, within
from app.api.v1.routes.oauth import MCP, public_base, web_app_base
from app.config import settings
from app.domain import __version__, integrations, store
Expand Down Expand Up @@ -302,8 +302,8 @@ async def _serve(request: Request, db: Db, ns: str | None = None) -> Response:
if accept and not any(t in accept for t in ("application/json", "application/*", "*/*")):
return Response(status_code=406) # every answer here is JSON
user = await run_in_threadpool(optional_user, request, db) # the database blocks
if not user:
raise HTTPException(401, "sign in first", headers={"WWW-Authenticate": "Bearer"})
if not user: # (or a key or app given one namespace's servers alone, used elsewhere: deps.serves)
raise signed_out(request)
if not _audience_ok(request, user.resource, ns):
# a token an app was given for another server (RFC 8707) isn't one to use here; the app asks again for this one
raise HTTPException(401, "this token was given for another server", headers={"WWW-Authenticate": "Bearer"})
Expand Down
13 changes: 8 additions & 5 deletions fastapi_backend/app/api/v1/routes/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from fastapi import APIRouter, BackgroundTasks, HTTPException, Request

from app.api.deps import Cfg, CurrentUser, Db, Writer, client_ip, domain_errors
from app.api.deps import Acl, Cfg, CurrentUser, Db, Writer, client_ip, domain_errors
from app.config import settings
from app.core.security import create_access_token
from app.domain import auth, store
Expand Down Expand Up @@ -193,14 +193,17 @@ def token_limits(user: CurrentUser, cfg: Cfg) -> TokenLimits:


@tokens.post("")
def create_token(body: ApiTokenCreate, user: Writer, db: Db, cfg: Cfg) -> ApiTokenCreated:
def create_token(body: ApiTokenCreate, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> ApiTokenCreated:
"""A key that acts as you, with your roles (read only, or read and write). It lasts `days` (default
tokens.default_days, at most tokens.max_days; 0 never expires when tokens.never_expire allows), else 400."""
tokens.default_days, at most tokens.max_days; 0 never expires when tokens.never_expire allows), else 400. With a
`namespace` you can read, it opens that namespace's own MCP server and chat completions alone (docs/api.md, "Chat
completions for any app"), with your role there; anywhere else it is refused (401)."""
if user.via != "access":
raise HTTPException(403, "create tokens while signed in")
space = acl.namespace(body.namespace) if body.namespace else None
with domain_errors():
tid, raw = auth.create_token(db, user.id, body.name, body.scope, auth.token_days(cfg, body.days))
auth.audit(db, user.as_audit(), "token.create", f"api_token:{tid}")
tid, raw = auth.create_token(db, user.id, body.name, body.scope, auth.token_days(cfg, body.days), space)
auth.audit(db, user.as_audit(), "token.create", f"api_token:{tid}", {"namespace": body.namespace} if body.namespace else None)
return ApiTokenCreated(id=tid, token=raw)


Expand Down
3 changes: 2 additions & 1 deletion fastapi_backend/app/api/v1/routes/completions.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ def _open(request: Request, db: Db, name: str) -> tuple[Principal, int]:
"""Who asks, and the namespace they ask about, when its chat completions are on and theirs to read."""
user = optional_user(request, db)
if not user:
raise Refused(401, "give a Lens token as the API key (Authorization: Bearer …)", "invalid_api_key")
why = getattr(request.state, "refused", None) # a key or app given another namespace's servers alone
raise Refused(401, why or "give a Lens API key as the key (Authorization: Bearer …)", "invalid_api_key")
try:
sid = store.ns_id(db, name, create=False)
except KeyError:
Expand Down
31 changes: 25 additions & 6 deletions fastapi_backend/app/domain/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,9 @@ def token_days(cfg, days):
return days


def create_token(db, uid, name, scope="read", days=90):
def create_token(db, uid, name, scope="read", days=90, space=None):
"""A new API key for this person: `space` makes it open one namespace alone (its own MCP server and chat
completions, deps.serves), else it opens whatever they can reach."""
if scope not in ("read", "write"):
raise ValueError("scope is read or write")
raw = "la_" + secrets.token_urlsafe(32)
Expand All @@ -394,6 +396,7 @@ def create_token(db, uid, name, scope="read", days=90):
"prefix": raw[:9],
"created_at": store.now(),
"expires_at": _later(24 * days) if days else None,
"space": int(space) if space is not None else None,
}
),
)
Expand All @@ -403,19 +406,33 @@ def create_token(db, uid, name, scope="read", days=90):
def token_account(db, raw):
if not raw or not raw.startswith("la_"):
return None
t = db.one("SELECT record::id(id) AS id, account, scope, expires_at FROM api_token WHERE hash = $h LIMIT 1", h=sha(raw))
t = db.one("SELECT record::id(id) AS id, account, scope, expires_at, space FROM api_token WHERE hash = $h LIMIT 1", h=sha(raw))
if not t or (t.get("expires_at") and t["expires_at"] < store.now()):
return None
u = get_account(db, t["account"])
if not _active(u):
return None
db.q("UPDATE $r SET last_used_at = $n", r=R("api_token", t["id"]), n=store.now())
return {**public(u), "via": "token", "scope": t["scope"]}
return {**public(u), "via": "token", "scope": t["scope"], "space": t.get("space")}


def _named(db, rows):
"""Keys with the namespace each was made for, by name ("" once that namespace is gone: the key opens nothing)."""
names = store.space_names(db)
out = []
for r in rows:
sid = r.pop("space", None)
out.append({**r, "namespace": None if sid is None else names.get(sid, "")})
return out


def list_tokens(db, uid):
return db.rows(
"SELECT record::id(id) AS id, name, scope, prefix, created_at, expires_at, last_used_at FROM api_token WHERE account = $a", a=uid
return _named(
db,
db.rows(
"SELECT record::id(id) AS id, name, scope, prefix, created_at, expires_at, last_used_at, space FROM api_token WHERE account = $a",
a=uid,
),
)


Expand All @@ -434,7 +451,9 @@ def revoke_token(db, uid, tid):
def all_tokens(db):
"""Everyone's keys (admins): the key's fields with its owner's email, the latest made first."""
people = {a["id"]: a["email"] for a in db.rows("SELECT record::id(id) AS id, email FROM account")}
rows = db.rows("SELECT record::id(id) AS id, account, name, scope, prefix, created_at, expires_at, last_used_at FROM api_token")
rows = _named(
db, db.rows("SELECT record::id(id) AS id, account, name, scope, prefix, created_at, expires_at, last_used_at, space FROM api_token")
)
return sorted(
({**r, "email": people.get(r["account"])} for r in rows), key=lambda r: (r.get("created_at") or "", r["id"]), reverse=True
)
Expand Down
6 changes: 6 additions & 0 deletions fastapi_backend/app/schemas/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@ class MeUpdate(RequestModel):
class ApiTokenCreate(RequestModel):
name: str = "token"
scope: Literal["read", "write"] = "read"
namespace: str | None = Field(
None,
description="a namespace you can read: the key opens that namespace's own MCP server and chat completions alone, "
"and nothing else in Lens; none: whatever you can reach",
)
days: int | None = Field(
None,
ge=0,
Expand Down Expand Up @@ -114,6 +119,7 @@ class ApiToken(ResponseModel):
created_at: str
expires_at: str | None = None
last_used_at: str | None = None
namespace: str | None = Field(None, description="the one namespace it opens (its own servers alone), when it was made for one")


class AccountToken(ApiToken):
Expand Down
Loading
Loading