From d2b145f124869f17890c643826b9d7cdf1f04c14 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Thu, 15 Oct 2026 11:47:51 +0000 Subject: [PATCH] feat(tokens): API keys that open one namespace alone An API key can be made for one namespace (namespace on POST /api/v1/tokens, or Opens on the API tokens page, which Connect apps fills in). It authenticates only on that namespace's own MCP server and chat completions, with its maker's role there, and is refused (401) everywhere else in Lens. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01LB2qrE7CENSd3G5h4FxFra --- CHANGELOG.md | 3 + docs/api.md | 7 +- docs/authentication.md | 6 ++ docs/mcp.md | 3 +- fastapi_backend/app/api/deps.py | 37 ++++++++- fastapi_backend/app/api/mcp.py | 6 +- fastapi_backend/app/api/v1/routes/auth.py | 13 ++-- .../app/api/v1/routes/completions.py | 3 +- fastapi_backend/app/domain/auth.py | 31 ++++++-- fastapi_backend/app/schemas/auth.py | 6 ++ .../tests/api/test_namespace_keys.py | 70 +++++++++++++++++ .../__tests__/connect-apps.test.tsx | 5 +- .../__tests__/tokens-page.test.tsx | 29 ++++++- nextjs-frontend/app/openapi-client/sdk.gen.ts | 4 +- .../app/openapi-client/types.gen.ts | 18 +++++ .../components/account/token-model.ts | 13 +++- nextjs-frontend/components/account/tokens.tsx | 77 ++++++++++++++++--- .../integrations/connect-apps-section.tsx | 20 ++++- nextjs-frontend/openapi.json | 38 ++++++++- threat-model.json | 2 +- threat-model.md | 4 +- threat-model.yaml | 4 +- 22 files changed, 351 insertions(+), 48 deletions(-) create mode 100644 fastapi_backend/tests/api/test_namespace_keys.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 64ffd0f69..aa1d26220 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 October 15, 2026 {id="0.11.0"} diff --git a/docs/api.md b/docs/api.md index 151bbe219..29f2ac9a2 100644 --- a/docs/api.md +++ b/docs/api.md @@ -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 @@ -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/` (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. diff --git a/docs/authentication.md b/docs/authentication.md index d687e9919..1431e7926 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -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 ``` diff --git a/docs/mcp.md b/docs/mcp.md index 60a77ba3b..951e3405d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -55,7 +55,8 @@ Signing in works as above, from the namespace's own metadata (`/.well-known/oauth-protected-resource/mcp/`, which names `…/mcp/` 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). diff --git a/fastapi_backend/app/api/deps.py b/fastapi_backend/app/api/deps.py index efc0cdb95..4815701fc 100644 --- a/fastapi_backend/app/api/deps.py +++ b/fastapi_backend/app/api/deps.py @@ -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: @@ -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/, /api/v1/namespaces//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) @@ -108,6 +120,7 @@ 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 @@ -115,6 +128,7 @@ def _resolve(request: Request, db: DB) -> Principal | 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")) @@ -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 @@ -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 @@ -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: @@ -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") @@ -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) diff --git a/fastapi_backend/app/api/mcp.py b/fastapi_backend/app/api/mcp.py index bea4b2cac..92a13754d 100644 --- a/fastapi_backend/app/api/mcp.py +++ b/fastapi_backend/app/api/mcp.py @@ -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 @@ -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"}) diff --git a/fastapi_backend/app/api/v1/routes/auth.py b/fastapi_backend/app/api/v1/routes/auth.py index 319dd8d0a..6cff09a56 100644 --- a/fastapi_backend/app/api/v1/routes/auth.py +++ b/fastapi_backend/app/api/v1/routes/auth.py @@ -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 @@ -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) diff --git a/fastapi_backend/app/api/v1/routes/completions.py b/fastapi_backend/app/api/v1/routes/completions.py index b88d2fceb..ef9a2b49c 100644 --- a/fastapi_backend/app/api/v1/routes/completions.py +++ b/fastapi_backend/app/api/v1/routes/completions.py @@ -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: diff --git a/fastapi_backend/app/domain/auth.py b/fastapi_backend/app/domain/auth.py index aedb3c7bf..0b328c7da 100644 --- a/fastapi_backend/app/domain/auth.py +++ b/fastapi_backend/app/domain/auth.py @@ -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) @@ -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, } ), ) @@ -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, + ), ) @@ -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 ) diff --git a/fastapi_backend/app/schemas/auth.py b/fastapi_backend/app/schemas/auth.py index 29ed6fcc2..50fd9be01 100644 --- a/fastapi_backend/app/schemas/auth.py +++ b/fastapi_backend/app/schemas/auth.py @@ -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, @@ -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): diff --git a/fastapi_backend/tests/api/test_namespace_keys.py b/fastapi_backend/tests/api/test_namespace_keys.py new file mode 100644 index 000000000..744fd9c7f --- /dev/null +++ b/fastapi_backend/tests/api/test_namespace_keys.py @@ -0,0 +1,70 @@ +"""API keys made for one namespace (POST /api/v1/tokens with a namespace): they open that namespace's own MCP server +and chat completions, with the person's role there, and nothing else in Lens.""" + +from __future__ import annotations + +from tests.api import test_completions as completions +from tests.api.test_completions import ask, turn_on +from tests.api.test_mcp_namespace import call, rpc + +llm, app, env = completions.llm, completions.app, completions.env # the same fixtures: a fake model, pods and calls + + +def key(client, h, **body) -> dict: + r = client.post("/api/v1/tokens", headers=h, json={"name": "family app", **body}) + assert r.status_code == 200, r.text + return {"Authorization": f"Bearer {r.json()['token']}"} + + +def test_a_key_for_one_namespace_opens_its_servers_alone(client, env, llm): + turn_on(client, env["own"], mcp=True) + k = key(client, env["own"], namespace="pods") + listed = {t["name"]: t for t in client.get("/api/v1/tokens", headers=env["own"]).json()} + assert listed["family app"]["namespace"] == "pods" and "space" not in listed["family app"] + everyone = {t["name"]: t for t in client.get("/api/v1/admin/tokens", headers=env["root"]).json()} + assert everyone["family app"]["namespace"] == "pods" + + # its namespace's own servers answer, seeing that namespace alone + got = ask(client, k) + assert got["choices"][0]["message"]["content"].startswith("The shipment") and got["lens"]["namespace"] == "pods" + assert client.get("/api/v1/namespaces/pods/models", headers=k).status_code == 200 + assert rpc(client, k, "ping")["result"] == {} + is_err, spaces = call(client, k, "list_namespaces") + assert not is_err and [s["name"] for s in spaces["namespaces"]] == ["pods"] + + # nowhere else: not Lens's own MCP server, not another namespace's, not the API + r = client.post("/mcp", headers=k, json={"jsonrpc": "2.0", "id": 1, "method": "ping"}) + assert r.status_code == 401 and "pods's MCP server and chat completions alone" in r.json()["detail"] + assert ask(client, k, ns="calls", status=401)["error"]["code"] == "invalid_api_key" + assert client.post("/mcp/calls", headers=k, json={"jsonrpc": "2.0", "id": 1, "method": "ping"}).status_code == 401 + for path in ("/api/v1/namespaces", "/api/v1/tokens", "/api/v1/namespaces/pods/stats", "/api/v1/namespaces/pods/integrations"): + r = client.get(path, headers=k) + assert r.status_code == 401 and "alone" in r.json()["detail"], path + assert client.post("/api/v1/tokens", headers=k, json={"name": "more"}).status_code == 401 # it makes no keys + + # only for a namespace you can read + r = client.post("/api/v1/tokens", headers=env["vi"], json={"name": "x", "namespace": "calls"}) + assert r.status_code == 404 + assert client.post("/api/v1/tokens", headers=env["vi"], json={"name": "x", "namespace": "nowhere"}).status_code == 404 + # with no namespace, a key opens whatever its person can read, as before + plain = key(client, env["own"]) + assert client.get("/api/v1/namespaces", headers=plain).status_code == 200 + assert ask(client, plain)["lens"]["namespace"] == "pods" + audit = [(a["action"], a.get("detail")) for a in client.get("/api/v1/audit", headers=env["root"]).json()] + assert ("token.create", {"namespace": "pods"}) in audit + + +def test_it_has_the_persons_role_there_and_no_more(client, env, llm): + turn_on(client, env["own"], mcp=True) + k = key(client, env["root"], namespace="pods", scope="write") # an admin: an owner of pods, and nothing else + assert "error" in rpc(client, k, "tools/call", {"name": "file_storage", "arguments": {}}) # no server tools there + is_err, got = call(client, k, "set_namespace_integrations", chat=False) + assert not is_err and got["namespace"] == "pods" and got["chat"] is False + # losing the role there closes it + vk = key(client, env["vi"], namespace="pods") + assert ask(client, vk, status=403)["error"]["code"] == "endpoint_off" + turn_on(client, env["own"]) + assert ask(client, vk)["lens"]["namespace"] == "pods" + r = client.put("/api/v1/namespaces/pods/members", headers=env["root"], json={"email": "vi@x.io", "role": None}) + assert r.status_code == 200, r.text + assert ask(client, vk, status=404)["error"]["code"] == "not_found" diff --git a/nextjs-frontend/__tests__/connect-apps.test.tsx b/nextjs-frontend/__tests__/connect-apps.test.tsx index 2bafb7005..990efebda 100644 --- a/nextjs-frontend/__tests__/connect-apps.test.tsx +++ b/nextjs-frontend/__tests__/connect-apps.test.tsx @@ -72,7 +72,10 @@ test("owners turn on chat completions, copy the base URL and pick the tools the ); expect(await screen.findByText(`${window.location.origin}/api/v1/namespaces/pods`)).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Copy Base URL" })).toBeInTheDocument(); - expect(screen.getByRole("link", { name: "API key" })).toHaveAttribute("href", "/account/tokens"); + expect(screen.getByRole("link", { name: "an API key that opens pods alone" })).toHaveAttribute( + "href", + "/account/tokens?new=1&namespace=pods", + ); const box = screen.getByRole("checkbox", { name: "list recordings" }); expect(box).not.toBeChecked(); // none by default: one search per question fireEvent.click(box); diff --git a/nextjs-frontend/__tests__/tokens-page.test.tsx b/nextjs-frontend/__tests__/tokens-page.test.tsx index 6d73375ab..f46e65673 100644 --- a/nextjs-frontend/__tests__/tokens-page.test.tsx +++ b/nextjs-frontend/__tests__/tokens-page.test.tsx @@ -2,15 +2,17 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import "@testing-library/jest-dom"; -import { Tokens } from "@/app/openapi-client"; +import { Namespaces, Tokens } from "@/app/openapi-client"; import { TokensPage } from "@/components/account/tokens"; import { TooltipProvider } from "@/components/ui/tooltip"; jest.mock("@/app/openapi-client", () => ({ Tokens: { listTokens: jest.fn(), tokenLimits: jest.fn(), createToken: jest.fn(), renameToken: jest.fn() }, + Namespaces: { listNamespaces: jest.fn() }, })); jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); -jest.mock("next/navigation", () => ({ useSearchParams: () => new URLSearchParams() })); +let params = new URLSearchParams(); +jest.mock("next/navigation", () => ({ useSearchParams: () => params })); jest.mock("@/components/ui/toast", () => ({ useToast: () => jest.fn() })); const ok = (data: unknown) => Promise.resolve({ data, response: { ok: true, status: 200 } }); @@ -35,6 +37,8 @@ const show = () => beforeEach(() => { jest.clearAllMocks(); + params = new URLSearchParams(); + (Namespaces.listNamespaces as jest.Mock).mockImplementation(() => ok([{ name: "pods" }, { name: "calls" }])); (Tokens.tokenLimits as jest.Mock).mockImplementation(() => ok({ default_days: 90, max_days: 365, never_expire: false }), ); @@ -75,4 +79,25 @@ describe("API tokens", () => { fireEvent.click(screen.getByRole("button", { name: "New token" })); expect(await screen.findByRole("textbox", { name: "Name" })).toHaveAttribute("placeholder", "Read only token 2"); }); + + it("makes a key that opens one namespace alone, from Connect apps' link", async () => { + params = new URLSearchParams("new=1&namespace=pods"); + (Tokens.listTokens as jest.Mock).mockImplementation(() => + ok([TOKEN, { ...TOKEN, id: 5, name: "Old", namespace: "calls" }]), + ); + show(); + expect(await screen.findByText("calls alone")).toBeInTheDocument(); // the list says what each key opens + const name = await screen.findByRole("textbox", { name: "Name" }); + expect(name).toHaveAttribute("placeholder", "pods app key"); + expect(await screen.findByRole("combobox", { name: "Opens" })).toHaveValue("pods"); + const create = screen.getByRole("button", { name: "Create token" }); + await waitFor(() => expect(create).toBeEnabled()); + fireEvent.click(create); + await waitFor(() => expect(Tokens.createToken).toHaveBeenCalled()); + expect((Tokens.createToken as jest.Mock).mock.calls[0][0].body).toMatchObject({ + name: "pods app key", + namespace: "pods", + }); + expect(await screen.findByText(/pods alone ·/)).toBeInTheDocument(); + }); }); diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index f08c7255f..a0ebbd72c 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -2265,7 +2265,9 @@ export class Tokens { * Create Token * * 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). */ public static createToken( options: Options, diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index bf641f001..3768d5bb6 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -91,6 +91,12 @@ export type AccountToken = { * Last Used At */ last_used_at?: string | null; + /** + * Namespace + * + * the one namespace it opens (its own servers alone), when it was made for one + */ + namespace?: string | null; /** * Account */ @@ -583,6 +589,12 @@ export type ApiToken = { * Last Used At */ last_used_at?: string | null; + /** + * Namespace + * + * the one namespace it opens (its own servers alone), when it was made for one + */ + namespace?: string | null; [key: string]: unknown; }; @@ -598,6 +610,12 @@ export type ApiTokenCreate = { * Scope */ scope?: "read" | "write"; + /** + * Namespace + * + * 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 + */ + namespace?: string | null; /** * Days * diff --git a/nextjs-frontend/components/account/token-model.ts b/nextjs-frontend/components/account/token-model.ts index 94bee2fae..227b0c296 100644 --- a/nextjs-frontend/components/account/token-model.ts +++ b/nextjs-frontend/components/account/token-model.ts @@ -38,9 +38,16 @@ export const SCOPE_LABEL: Record = { write: "Read & write", }; -/** A name for a token nobody named, from its scope ("Read only token", then "Read only token 2"). */ -export function suggestedTokenName(scope: string, taken: Iterable): string { - return uniqueName(`${SCOPE_LABEL[scope] ?? "API"} token`, taken); +/** A name for a token nobody named, from its scope ("Read only token", then "Read only token 2"), or the one + * namespace it opens ("pods app key"). */ +export function suggestedTokenName(scope: string, taken: Iterable, namespace?: string | null): string { + return uniqueName(namespace ? `${namespace} app key` : `${SCOPE_LABEL[scope] ?? "API"} token`, taken); +} + +/** What a key opens, in words: everything its person can read, or one namespace's own servers. */ +export function opensLabel(namespace: string | null | undefined): string | null { + if (namespace == null) return null; + return namespace ? `${namespace} alone` : "a deleted namespace"; } /** How long keys may last (GET /tokens/limits; admins set them). */ diff --git a/nextjs-frontend/components/account/tokens.tsx b/nextjs-frontend/components/account/tokens.tsx index 5cd55ea5f..9bea73b1e 100644 --- a/nextjs-frontend/components/account/tokens.tsx +++ b/nextjs-frontend/components/account/tokens.tsx @@ -5,16 +5,23 @@ import { Check, Copy, KeyRound, Plus } from "lucide-react"; import { useSearchParams } from "next/navigation"; import { useEffect, useRef, useState } from "react"; -import { Tokens } from "@/app/openapi-client"; +import { Namespaces, Tokens } from "@/app/openapi-client"; import type { ApiToken } from "@/app/openapi-client/types.gen"; import { S3Keys } from "@/components/account/s3-keys"; -import { daysError, expiresOn, SCOPE_LABEL, suggestedTokenName, tokenExpiry } from "@/components/account/token-model"; +import { + daysError, + expiresOn, + opensLabel, + SCOPE_LABEL, + suggestedTokenName, + tokenExpiry, +} from "@/components/account/token-model"; import { isUnreachable } from "@/components/errors/error-states"; import { ChoiceCards } from "@/components/settings/controls"; import { Banner } from "@/components/ui/banner"; import { Button } from "@/components/ui/button"; import { Dialog } from "@/components/ui/dialog"; -import { Field, Input } from "@/components/ui/field"; +import { Field, Input, Select } from "@/components/ui/field"; import { RenameTitle } from "@/components/ui/rename-title"; import { EmptyState, SkeletonRows } from "@/components/ui/states"; import { Table, Td, Th, THead, Tr } from "@/components/ui/table"; @@ -28,7 +35,7 @@ const SCOPES = [ { value: "write", label: "Read & write", hint: "+ import, edit, reprocess" }, ]; -type Created = { token: string; name: string; scope: string; days: number }; +type Created = { token: string; name: string; scope: string; days: number; namespace: string | null }; /** API tokens: list · create · shown once · revoke · expired (Access AC5). Each person manages their own. */ export function TokensPage() { @@ -40,8 +47,10 @@ export function TokensPage() { queryFn: () => data(Tokens.listTokens({ client })), }); // ?new=1 (the account menu, when there are no tokens yet): the new token's form is open on arrival; it also opens - // once the list comes back empty, for a menu clicked before it knew - const [creating, setCreating] = useState(useSearchParams().get("new") === "1"); + // once the list comes back empty, for a menu clicked before it knew. &namespace=pods (Connect apps): a key for pods + const params = useSearchParams(); + const [creating, setCreating] = useState(params.get("new") === "1"); + const forNamespace = params.get("namespace"); const offered = useRef(false); useEffect(() => { if (offered.current || !tokens.data) return; @@ -126,8 +135,18 @@ export function TokensPage() { /> - - {SCOPE_LABEL[t.scope] ?? t.scope} + + + {SCOPE_LABEL[t.scope] ?? t.scope} + + {opensLabel(t.namespace) && ( + + {opensLabel(t.namespace)} + + )} @@ -166,6 +185,7 @@ export function TokensPage() { t.name)} onClose={() => setCreating(false)} onCreated={(c) => { @@ -194,11 +214,14 @@ export function TokensPage() { function NewTokenDialog({ open, + initialNamespace, taken, onClose, onCreated, }: { open: boolean; + /** The one namespace the key opens at first (Connect apps sends people here with it). */ + initialNamespace?: string | null; /** The names of the tokens there are, so the guessed name is a new one. */ taken: string[]; onClose: () => void; @@ -208,6 +231,18 @@ function NewTokenDialog({ const [name, setName] = useState(""); const [scope, setScope] = useState("read"); const [days, setDays] = useState(""); + const [namespace, setNamespace] = useState(initialNamespace ?? ""); + const spaces = useQuery({ + queryKey: ["namespaces"], + queryFn: () => data(Namespaces.listNamespaces({ client })), + staleTime: 30_000, + }); + const opens = [ + { value: "", label: "Everything you can read" }, + ...(spaces.data ?? []) + .filter((n) => !n.partial) + .map((n) => ({ value: n.name, label: `${n.name} alone: its MCP server and chat completions` })), + ]; const limitsQ = useQuery({ queryKey: ["tokens", "limits"], queryFn: () => data(Tokens.tokenLimits({ client })), @@ -215,7 +250,7 @@ function NewTokenDialog({ }); const limits = limitsQ.data ?? null; const shown = days || (limits ? String(limits.default_days) : ""); - const guess = suggestedTokenName(scope, taken); + const guess = suggestedTokenName(scope, taken, namespace || null); const named = name.trim() || guess; const create = useMutation({ mutationFn: () => @@ -226,6 +261,7 @@ function NewTokenDialog({ name: named, scope: scope as "read" | "write", days: Number(shown), + namespace: namespace || null, }, }), ), @@ -235,10 +271,12 @@ function NewTokenDialog({ name: named, scope, days: Number(shown), + namespace: namespace || null, }); setName(""); setScope("read"); setDays(""); + setNamespace(""); }, }); const nameError = name.trim() ? (name.trim().length > 80 ? "Use at most 80 characters" : null) : null; @@ -297,6 +335,26 @@ function NewTokenDialog({ Scope + + {(f) => ( +