Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(console): support account user agentid (#1198)
Jiahui Zhoua566fe26b682
diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.mdindex 9bb990a6b..9d3f038e8 100644--- a/docs/en/api/08-admin.md+++ b/docs/en/api/08-admin.md@@ -2,6 +2,8 @@The Admin API manages accounts and users in a multi-tenant environment. It covers workspace (account) creation/deletion, user registration/removal, role changes, and API key regeneration.+This API is for the `api_key` admin workflow. In `trusted` mode, ordinary requests do not use user-key registration, and Admin API calls return a permission error explaining that account/user management requires `api_key` mode with `root_api_key`.+## Roles and Permissions| Role | Description |diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.mdindex 13df3148b..f088bd90f 100644--- a/docs/en/guides/01-configuration.md+++ b/docs/en/guides/01-configuration.md@@ -853,13 +853,13 @@ When running OpenViking as an HTTP service, add a `server` section to `ov.conf`:|-------|------|-------------|---------|| `host` | str | Bind address | `0.0.0.0` || `port` | int | Bind port | `1933` |-| `auth_mode` | str | Authentication mode: `"api_key"` or `"trusted"` | `"api_key"` |-| `root_api_key` | str | Root API key for multi-tenant auth in `api_key` mode | `null` |+| `auth_mode` | str | Authentication mode: `"api_key"` or `"trusted"`. Default is `"api_key"` | `"api_key"` |+| `root_api_key` | str | Root API key for multi-tenant auth in `api_key` mode. In `trusted` mode it is optional extra protection, not the source of user identity | `null` || `cors_origins` | list | Allowed CORS origins | `["*"]` |-`api_key` mode uses API keys. `trusted` mode trusts `X-OpenViking-Account` / `X-OpenViking-User` headers from a trusted gateway or internal caller.+`api_key` mode uses API keys and is the default. `trusted` mode trusts `X-OpenViking-Account` / `X-OpenViking-User` headers from a trusted gateway or internal caller.-When `root_api_key` is configured, the server enables multi-tenant authentication. Use the Admin API to create accounts and user keys. Development mode only applies when `auth_mode = "api_key"` and `root_api_key` is not set.+When `root_api_key` is configured in `api_key` mode, the server enables multi-tenant authentication. Use the Admin API to create accounts and user keys. In `trusted` mode, ordinary requests do not require user registration first; each request is resolved as `USER` from the injected identity headers. Development mode only applies when `auth_mode = "api_key"` and `root_api_key` is not set.For startup and deployment details see [Deployment](./03-deployment.md), for authentication see [Authentication](./04-authentication.md).diff --git a/docs/en/guides/04-authentication.md b/docs/en/guides/04-authentication.mdindex a14ebd3a7..2343bb9cb 100644--- a/docs/en/guides/04-authentication.md+++ b/docs/en/guides/04-authentication.md@@ -1,6 +1,6 @@# Authentication-OpenViking Server supports two authentication modes with role-based access control: `api_key` and `trusted`.+OpenViking Server supports two authentication modes with role-based access control: `api_key` and `trusted`. The default mode is `api_key`.## Overview@@ -20,6 +20,8 @@ All API keys are plain random tokens with no embedded identity. The server resol| API key mode | `"api_key"` | API key, with optional tenant headers for root requests | Standard multi-tenant deployment || Trusted mode | `"trusted"` | `X-OpenViking-Account` / `X-OpenViking-User` / optional `X-OpenViking-Agent` headers | Behind a trusted gateway or internal network boundary |+`api_key` is the default and standard production mode. `trusted` is an alternative mode for deployments where an upstream gateway or trusted internal caller injects identity headers on every request.+## Setting Up (Server Side)Configure the authentication mode in the `server` section of `ov.conf`:@@ -41,6 +43,8 @@ openviking-server## Managing Accounts and Users+This section applies to `api_key` mode. In `trusted` mode, normal requests do not use user-key registration or lookup.+Use the root key to create accounts (workspaces) and users via the Admin API:```bash@@ -162,11 +166,19 @@ Trusted mode skips user-key lookup and instead trusts explicit identity headersRules in trusted mode:+- Normal data access does not require user registration or user-key provisioning first.- `X-OpenViking-Account` and `X-OpenViking-User` are required on tenant-scoped requests.- `X-OpenViking-Agent` is optional and defaults to `default`.+- Every trusted-mode request is resolved as `USER`. Identity comes from the headers, not from a root key or user key.- If `root_api_key` is also configured, every request must still provide a matching API key.- Only expose this mode behind a trusted network boundary or an identity-injecting gateway.+Implications:++- Trusted mode is not development mode.+- Trusted mode does not use the Admin API as a prerequisite for ordinary reads, writes, search, or session access.+- Account creation, user registration, role changes, and key regeneration remain part of the `api_key` admin workflow. If you call Admin API endpoints while the server runs in `trusted` mode, the server returns a permission error explaining that admin registration is unavailable in `trusted` mode and that you should switch to `api_key` mode with `root_api_key` for account/user management.+**curl**```bash@@ -197,10 +209,14 @@ client = ov.SyncHTTPClient(| ADMIN | Own account | Regular operations + manage users in own account || USER | Own account | Regular operations (ls, read, find, sessions, etc.) |+In `trusted` mode, requests are resolved as `USER`, so the usual ROOT/ADMIN registration flow does not apply to ordinary traffic.+## Development ModeWhen `auth_mode = "api_key"` and no `root_api_key` is configured, authentication is disabled. All requests are accepted as ROOT with the default account. **This is only allowed when the server binds to localhost** (`127.0.0.1`, `localhost`, or `::1`). If `host` is set to a non-loopback address (e.g. `0.0.0.0`) without a `root_api_key`, the server will refuse to start.+Development mode only exists in `api_key` mode. `trusted` mode never falls back to development mode.+```json{"server": {diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.mdindex f1a542e9d..ba2af9d16 100644--- a/docs/zh/api/08-admin.md+++ b/docs/zh/api/08-admin.md@@ -2,6 +2,8 @@Admin API 用于多租户环境下的账户和用户管理。包括工作区(account)的创建与删除、用户注册与移除、角色变更、API Key 重新生成。+该 API 只适用于 `api_key` 模式下的管理链路。在 `trusted` 模式里,普通请求不使用 user key 注册流程;如果去调用 Admin API,服务端会返回明确权限错误,说明账户/用户管理需要切换到配置了 `root_api_key` 的 `api_key` 模式。+## 角色与权限| 角色 | 说明 |diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.mdindex 4d386846a..ac75a2528 100644--- a/docs/zh/guides/01-configuration.md+++ b/docs/zh/guides/01-configuration.md@@ -826,13 +826,13 @@ openviking --account acme --user alice --agent-id assistant-2 ls viking://|------|------|------|--------|| `host` | str | 绑定地址 | `0.0.0.0` || `port` | int | 绑定端口 | `1933` |-| `auth_mode` | str | 认证模式:`"api_key"` 或 `"trusted"` | `"api_key"` |-| `root_api_key` | str | Root API Key。在 `api_key` 模式下启用多租户认证 | `null` |+| `auth_mode` | str | 认证模式:`"api_key"` 或 `"trusted"`。默认值为 `"api_key"` | `"api_key"` |+| `root_api_key` | str | Root API Key。在 `api_key` 模式下启用多租户认证;在 `trusted` 模式下它只是可选附加保护,不负责解析普通用户身份 | `null` || `cors_origins` | list | CORS 允许的来源 | `["*"]` |-`api_key` 模式使用 API Key 认证;`trusted` 模式信任上游网关或受信调用方注入的 `X-OpenViking-Account` / `X-OpenViking-User` 请求头。+`api_key` 模式使用 API Key 认证,也是默认模式;`trusted` 模式信任上游网关或受信调用方注入的 `X-OpenViking-Account` / `X-OpenViking-User` 请求头。-配置 `root_api_key` 后,服务端启用多租户认证。通过 Admin API 创建工作区和用户 key。只有在 `auth_mode = "api_key"` 且未配置 `root_api_key` 时,服务端才会进入开发模式。+在 `api_key` 模式下配置 `root_api_key` 后,服务端启用正式多租户认证,并通过 Admin API 创建工作区和用户 key。在 `trusted` 模式下,普通请求不需要先注册 user key;每个请求都会根据注入的身份头解析成 `USER`。只有在 `auth_mode = "api_key"` 且未配置 `root_api_key` 时,服务端才会进入开发模式。启动方式和部署详情见 [服务部署](./03-deployment.md),认证详情见 [认证](./04-authentication.md)。diff --git a/docs/zh/guides/04-authentication.md b/docs/zh/guides/04-authentication.mdindex e2c59e750..3101df057 100644--- a/docs/zh/guides/04-authentication.md+++ b/docs/zh/guides/04-authentication.md@@ -1,6 +1,6 @@# 认证-OpenViking Server 支持两种认证模式,并带有基于角色的访问控制:`api_key` 和 `trusted`。+OpenViking Server 支持两种认证模式,并带有基于角色的访问控制:`api_key` 和 `trusted`。默认模式是 `api_key`。## 概述@@ -20,6 +20,8 @@ OpenViking 使用两层 API Key 体系:| API Key 模式 | `"api_key"` | API Key,root 请求可附带租户请求头 | 标准多租户部署 || Trusted 模式 | `"trusted"` | `X-OpenViking-Account` / `X-OpenViking-User` / 可选 `X-OpenViking-Agent` 请求头 | 部署在受信网关或内网边界之后 |+`api_key` 是默认模式,也是标准生产部署方式。`trusted` 是替代模式,适合由上游网关或受信内网调用方在每个请求里显式注入身份头。+## 服务端配置在 `ov.conf` 的 `server` 段配置认证模式:@@ -41,6 +43,8 @@ openviking-server## 管理账户和用户+本节只适用于 `api_key` 模式。在 `trusted` 模式下,普通请求不会走 user key 的注册或查找链路。+使用 root key 通过 Admin API 创建工作区和用户:```bash@@ -162,11 +166,19 @@ Trusted 模式不会查 user key,而是直接信任每个请求显式携带的Trusted 模式规则:+- 普通数据访问不需要先注册 user key,也不依赖 user key 分发流程- 租户级请求必须包含 `X-OpenViking-Account` 和 `X-OpenViking-User`- `X-OpenViking-Agent` 可选,缺省为 `default`+- 每个 trusted 请求都会被解析成 `USER`,身份完全来自请求头,而不是 root key 或 user key- 如果同时配置了 `root_api_key`,每个请求仍然必须带匹配的 API Key- 只应部署在受信网络边界之后,或由身份注入网关统一转发+这意味着:++- `trusted` 不是开发模式+- `trusted` 下的普通读写、检索、会话访问不需要先走 Admin API 注册流程+- 创建 account、注册用户、修改角色、重新生成 key 仍然属于 `api_key` 模式下的管理链路;如果服务端运行在 `trusted` 模式而你去调用这些 Admin API,服务端会返回明确错误,说明 `trusted` 不支持这类注册式管理,并提示切换到配置了 `root_api_key` 的 `api_key` 模式+**curl**```bash@@ -197,10 +209,14 @@ client = ov.SyncHTTPClient(| ADMIN | 所属 account | 常规操作 + 管理所属 account 的用户 || USER | 所属 account | 常规操作(ls、read、find、sessions 等) |+在 `trusted` 模式下,请求角色会解析为 `USER`,因此普通流量不适用 ROOT/ADMIN 的注册式管理语义。+## 开发模式当 `auth_mode = "api_key"` 且未配置 `root_api_key` 时,认证禁用,所有请求以 ROOT 身份访问 default account。**此模式仅允许在服务器绑定 localhost 时使用**(`127.0.0.1`、`localhost` 或 `::1`)。如果 `host` 设置为非回环地址(如 `0.0.0.0`)且未配置 `root_api_key`,服务器将拒绝启动。+开发模式只存在于 `api_key` 模式中;`trusted` 不会退化成开发模式。+```json{"server": {diff --git a/openviking/console/README.md b/openviking/console/README.mdindex 763765864..09d19ba8d 100644--- a/openviking/console/README.md+++ b/openviking/console/README.md@@ -29,8 +29,11 @@ python -m openviking.console.bootstrap \http://127.0.0.1:8020/```-4. In **Settings**, paste your OpenViking `X-API-Key` and click **Save** (or press Enter).-`X-API-Key` is configured in the web UI Settings panel and stored in browser session storage.+4. In **Settings**, configure headers for your upstream auth mode.+`api_key` is the default server mode, so in that mode you normally paste `X-API-Key` and click **Save** (or press Enter). If the upstream server runs in `trusted` mode, you usually do not need `X-API-Key` for ordinary requests; instead set `X-OpenViking-Account` and `X-OpenViking-User` (and optionally `X-OpenViking-Agent`).+`X-API-Key` is stored locally in the browser and restored into the current tab.++When the upstream server runs in `trusted` mode, ordinary access does not require user registration first. If you try account or user management actions against Admin API endpoints in `trusted` mode, the server now returns an explicit error explaining that `trusted` mode resolves requests as `USER` and that account/user management requires `api_key` mode with `root_api_key`.## Startup parametersdiff --git a/openviking/console/static/app.js b/openviking/console/static/app.jsindex 1f12de44a..ef919e5fb 100644--- a/openviking/console/static/app.js+++ b/openviking/console/static/app.js@@ -1,3 +1,9 @@+import {+ buildRequestHeaders,+ resolveRuntimeConsoleSettings,+ saveConsoleSettings,+} from "./console_settings.js";+const API_BASE = "/console/api/v1";const SESSION_KEY = "ov_console_api_key";const THEME_MODE_KEY = "ov_console_theme_mode";@@ -31,6 +37,12 @@ const state = {themeMode: "dark",navCollapsed: false,resultCollapsed: false,+ connectionSettings: {+ apiKey: "",+ accountId: "",+ userId: "",+ agentId: "",+ },};const elements = {@@ -43,6 +55,9 @@ const elements = {sidebarResizer: document.getElementById("sidebarResizer"),outputResizer: document.getElementById("outputResizer"),apiKeyInput: document.getElementById("apiKeyInput"),+ accountInput: document.getElementById("accountInput"),+ userInput: document.getElementById("userInput"),+ agentIdInput: document.getElementById("agentIdInput"),saveKeyBtn: document.getElementById("saveKeyBtn"),clearKeyBtn: document.getElementById("clearKeyBtn"),connectionHint: document.getElementById("connectionHint"),@@ -239,14 +254,22 @@ function setActivePanel(panel) {}function getApiKey() {- return window.sessionStorage.getItem(SESSION_KEY) || "";+ return window.sessionStorage.getItem(SESSION_KEY) || state.connectionSettings.apiKey || "";}function updateConnectionHint() {const key = getApiKey();- elements.connectionHint.textContent = key- ? `API key loaded in session (${key.length} chars).`- : "No API key in session.";+ const identities = [+ state.connectionSettings.accountId ? `account=${state.connectionSettings.accountId}` : "",+ state.connectionSettings.userId ? `user=${state.connectionSettings.userId}` : "",+ state.connectionSettings.agentId ? `agent=${state.connectionSettings.agentId}` : "",+ ].filter(Boolean);++ const apiKeySummary = key ? `API key loaded in session (${key.length} chars).` : "No API key in session.";+ const identitySummary = identities.length+ ? ` Identity headers: ${identities.join(", ")}.`+ : " No account/user/agent id configured.";+ elements.connectionHint.textContent = `${apiKeySummary}${identitySummary}`;}function truncateText(value, maxLength = 4000) {@@ -263,18 +286,17 @@ function isJsonLikeContentType(contentType) {}async function callConsole(path, options = {}) {- const headers = {+ const baseHeaders = {...(options.headers || {}),};if (!(options.body instanceof FormData)) {- headers["Content-Type"] = headers["Content-Type"] || "application/json";- }-- const apiKey = getApiKey();- if (apiKey) {- headers["X-API-Key"] = apiKey;+ baseHeaders["Content-Type"] = baseHeaders["Content-Type"] || "application/json";}+ const headers = buildRequestHeaders(baseHeaders, {+ apiKey: getApiKey(),+ ...state.connectionSettings,+ });let response;try {@@ -1462,22 +1484,33 @@ function bindTabs() {}function bindConnection() {- const saveApiKey = () => {- const value = elements.apiKeyInput.value.trim();- if (!value) {- setOutput("API key is empty.");- return false;+ const saveConnection = () => {+ const nextApiKey = elements.apiKeyInput.value.trim() || state.connectionSettings.apiKey;+ state.connectionSettings = saveConsoleSettings(window.localStorage, {+ apiKey: nextApiKey,+ accountId: elements.accountInput.value,+ userId: elements.userInput.value,+ agentId: elements.agentIdInput.value,+ });++ elements.accountInput.value = state.connectionSettings.accountId;+ elements.userInput.value = state.connectionSettings.userId;+ elements.agentIdInput.value = state.connectionSettings.agentId;++ if (state.connectionSettings.apiKey) {+ window.sessionStorage.setItem(SESSION_KEY, state.connectionSettings.apiKey);+ elements.apiKeyInput.value = "";+ } else {+ window.sessionStorage.removeItem(SESSION_KEY);}- window.sessionStorage.setItem(SESSION_KEY, value);- elements.apiKeyInput.value = "";updateConnectionHint();- setOutput("API key saved in browser session storage.");+ setOutput(nextApiKey ? "Connection settings saved." : "Identity settings saved. API key unchanged.");return true;};elements.saveKeyBtn.addEventListener("click", () => {- saveApiKey();+ saveConnection();});elements.apiKeyInput.addEventListener("keydown", (event) => {@@ -1485,13 +1518,18 @@ function bindConnection() {return;}event.preventDefault();- saveApiKey();+ saveConnection();});elements.clearKeyBtn.addEventListener("click", () => {window.sessionStorage.removeItem(SESSION_KEY);+ state.connectionSettings = saveConsoleSettings(window.localStorage, {});+ elements.accountInput.value = "";+ elements.userInput.value = "";+ elements.agentIdInput.value = "";+ elements.apiKeyInput.value = "";updateConnectionHint();- setOutput("API key cleared from browser session.");+ setOutput("Connection settings cleared from browser storage.");});}@@ -2460,6 +2498,14 @@ function bindMonitor() {}async function init() {+ state.connectionSettings = resolveRuntimeConsoleSettings(window.localStorage, getApiKey());+ if (state.connectionSettings.apiKey) {+ window.sessionStorage.setItem(SESSION_KEY, state.connectionSettings.apiKey);+ }+ elements.accountInput.value = state.connectionSettings.accountId;+ elements.userInput.value = state.connectionSettings.userId;+ elements.agentIdInput.value = state.connectionSettings.agentId;+initShellState();bindShellControls();initResizablePanes();diff --git a/openviking/console/static/console_settings.js b/openviking/console/static/console_settings.jsnew file mode 100644index 000000000..ff023934d--- /dev/null+++ b/openviking/console/static/console_settings.js@@ -0,0 +1,107 @@+const LEGACY_API_KEY_STORAGE_KEY = "ov_console_api_key";+const CONNECTION_SETTINGS_STORAGE_KEY = "ov_console_connection_settings_v1";++function normalizeValue(value) {+ if (value === undefined || value === null) {+ return "";+ }+ return String(value).trim();+}++export function normalizeConsoleSettings(settings = {}) {+ return {+ apiKey: normalizeValue(settings.apiKey),+ accountId: normalizeValue(settings.accountId),+ userId: normalizeValue(settings.userId),+ agentId: normalizeValue(settings.agentId),+ };+}++export function serializeConsoleSettings(settings = {}) {+ const normalized = normalizeConsoleSettings(settings);+ const payload = {};++ for (const [key, value] of Object.entries(normalized)) {+ if (value) {+ payload[key] = value;+ }+ }++ return JSON.stringify(payload);+}++export function parseConsoleSettings(rawValue) {+ if (!rawValue) {+ return normalizeConsoleSettings();+ }++ try {+ const parsed = JSON.parse(rawValue);+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {+ return normalizeConsoleSettings();+ }+ return normalizeConsoleSettings(parsed);+ } catch (_error) {+ return normalizeConsoleSettings();+ }+}++export function loadConsoleSettings(storage) {+ const stored = storage.getItem(CONNECTION_SETTINGS_STORAGE_KEY);+ if (stored) {+ return parseConsoleSettings(stored);+ }++ return normalizeConsoleSettings({+ apiKey: storage.getItem(LEGACY_API_KEY_STORAGE_KEY) || "",+ });+}++export function resolveRuntimeConsoleSettings(storage, sessionApiKey = "") {+ const saved = loadConsoleSettings(storage);+ const runtimeApiKey = normalizeValue(sessionApiKey) || saved.apiKey;+ return normalizeConsoleSettings({+ ...saved,+ apiKey: runtimeApiKey,+ });+}++export function saveConsoleSettings(storage, settings) {+ const normalized = normalizeConsoleSettings(settings);+ storage.setItem(CONNECTION_SETTINGS_STORAGE_KEY, serializeConsoleSettings(normalized));++ if (normalized.apiKey) {+ storage.setItem(LEGACY_API_KEY_STORAGE_KEY, normalized.apiKey);+ } else {+ storage.removeItem(LEGACY_API_KEY_STORAGE_KEY);+ }++ return normalized;+}++export function clearConsoleSettings(storage) {+ storage.removeItem(CONNECTION_SETTINGS_STORAGE_KEY);+ storage.removeItem(LEGACY_API_KEY_STORAGE_KEY);+}++export function buildRequestHeaders(baseHeaders = {}, settings = {}) {+ const normalized = normalizeConsoleSettings(settings);+ const headers = {+ ...baseHeaders,+ };++ if (normalized.apiKey) {+ headers["X-API-Key"] = normalized.apiKey;+ }+ if (normalized.accountId) {+ headers["X-OpenViking-Account"] = normalized.accountId;+ }+ if (normalized.userId) {+ headers["X-OpenViking-User"] = normalized.userId;+ }+ if (normalized.agentId) {+ headers["X-OpenViking-Agent"] = normalized.agentId;+ }++ return headers;+}diff --git a/openviking/console/static/index.html b/openviking/console/static/index.htmlindex ba0af29a8..9209963fa 100644--- a/openviking/console/static/index.html+++ b/openviking/console/static/index.html@@ -109,6 +109,14 @@<tbody id="fsEntries"></tbody></table></div>+ <div class="fs-editor-shell" hidden>+ <label for="fsEditor">Editor</label>+ <textarea id="fsEditor" rows="16" spellcheck="false"></textarea>+ <div class="row">+ <button id="fsSaveBtn">Save</button>+ <button id="fsRevertBtn" class="ghost">Revert</button>+ </div>+ </div></section><section id="panel-find" class="panel">@@ -319,7 +327,13 @@<section id="panel-settings" class="panel"><h2>Settings</h2><label for="apiKeyInput">X-API-Key</label>- <input id="apiKeyInput" type="password" placeholder="Paste key for this browser session" />+ <input id="apiKeyInput" type="password" placeholder="Paste key to reuse in this browser" />+ <label for="accountInput">X-OpenViking-Account</label>+ <input id="accountInput" type="text" placeholder="Default account_id for console requests" />+ <label for="userInput">X-OpenViking-User</label>+ <input id="userInput" type="text" placeholder="Default user_id for console requests" />+ <label for="agentIdInput">X-OpenViking-Agent</label>+ <input id="agentIdInput" type="text" placeholder="Default agent_id for console requests" /><div class="row"><button id="saveKeyBtn">Save</button><button id="clearKeyBtn" class="ghost">Clear</button>diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.pyindex c4b338edb..9e0e5682d 100644--- a/openviking/server/routers/admin.py+++ b/openviking/server/routers/admin.py@@ -2,10 +2,10 @@# SPDX-License-Identifier: AGPL-3.0"""Admin endpoints for OpenViking multi-tenant HTTP Server."""-from fastapi import APIRouter, Path, Request+from fastapi import APIRouter, Depends, Path, Requestfrom pydantic import BaseModel-from openviking.server.auth import require_role+from openviking.server.auth import get_request_contextfrom openviking.server.dependencies import get_servicefrom openviking.server.identity import RequestContext, Rolefrom openviking.server.models import Response@@ -18,6 +18,17 @@ logger = get_logger(__name__)router = APIRouter(prefix="/api/v1/admin", tags=["admin"])+_TRUSTED_MODE_ADMIN_API_MESSAGE = (+ "Admin API is unavailable in trusted mode. In trusted mode, each request is resolved as USER "+ "from X-OpenViking-Account/X-OpenViking-User headers and does not use user-key "+ "registration. Switch to api_key mode with root_api_key for account and user management."+)++_DEV_MODE_ADMIN_API_MESSAGE = (+ "Admin API requires api_key mode with root_api_key configured. Development mode does not "+ "support account or user management."+)+class CreateAccountRequest(BaseModel):account_id: str@@ -37,10 +48,35 @@ def _get_api_key_manager(request: Request):"""Get APIKeyManager from app state."""manager = getattr(request.app.state, "api_key_manager", None)if manager is None:- raise PermissionDeniedError("Admin API requires root_api_key to be configured")+ raise PermissionDeniedError(_DEV_MODE_ADMIN_API_MESSAGE)return manager+def require_admin_role(*allowed_roles: Role):+ """Dependency factory for Admin API routes with mode-aware errors."""++ async def _check(+ request: Request,+ ctx: RequestContext = Depends(get_request_context),+ ) -> RequestContext:+ config = getattr(request.app.state, "config", None)+ auth_mode = getattr(config, "auth_mode", "api_key")+ if auth_mode == "trusted":+ raise PermissionDeniedError(_TRUSTED_MODE_ADMIN_API_MESSAGE)++ manager = getattr(request.app.state, "api_key_manager", None)+ if manager is None:+ raise PermissionDeniedError(_DEV_MODE_ADMIN_API_MESSAGE)++ if ctx.role not in allowed_roles:+ raise PermissionDeniedError(+ f"Requires role: {', '.join(r.value for r in allowed_roles)}"+ )+ return ctx++ return Depends(_check)++def _check_account_access(ctx: RequestContext, account_id: str) -> None:"""ADMIN can only operate on their own account."""if ctx.role == Role.ADMIN and ctx.account_id != account_id:@@ -54,7 +90,7 @@ def _check_account_access(ctx: RequestContext, account_id: str) -> None:async def create_account(body: CreateAccountRequest,request: Request,- ctx: RequestContext = require_role(Role.ROOT),+ ctx: RequestContext = require_admin_role(Role.ROOT),):"""Create a new account (workspace) with its first admin user."""manager = _get_api_key_manager(request)@@ -79,7 +115,7 @@ async def create_account(@router.get("/accounts")async def list_accounts(request: Request,- ctx: RequestContext = require_role(Role.ROOT),+ ctx: RequestContext = require_admin_role(Role.ROOT),):"""List all accounts."""manager = _get_api_key_manager(request)@@ -91,7 +127,7 @@ async def list_accounts(async def delete_account(request: Request,account_id: str = Path(..., description="Account ID"),- ctx: RequestContext = require_role(Role.ROOT),+ ctx: RequestContext = require_admin_role(Role.ROOT),):"""Delete an account and cascade-clean its storage (AGFS + VectorDB)."""manager = _get_api_key_manager(request)@@ -138,7 +174,7 @@ async def register_user(body: RegisterUserRequest,request: Request,account_id: str = Path(..., description="Account ID"),- ctx: RequestContext = require_role(Role.ROOT, Role.ADMIN),+ ctx: RequestContext = require_admin_role(Role.ROOT, Role.ADMIN),):"""Register a new user in an account."""_check_account_access(ctx, account_id)@@ -164,7 +200,7 @@ async def register_user(async def list_users(request: Request,account_id: str = Path(..., description="Account ID"),- ctx: RequestContext = require_role(Role.ROOT, Role.ADMIN),+ ctx: RequestContext = require_admin_role(Role.ROOT, Role.ADMIN),):"""List all users in an account."""_check_account_access(ctx, account_id)@@ -178,7 +214,7 @@ async def remove_user(request: Request,account_id: str = Path(..., description="Account ID"),user_id: str = Path(..., description="User ID"),- ctx: RequestContext = require_role(Role.ROOT, Role.ADMIN),+ ctx: RequestContext = require_admin_role(Role.ROOT, Role.ADMIN),):"""Remove a user from an account."""_check_account_access(ctx, account_id)@@ -193,7 +229,7 @@ async def set_user_role(request: Request,account_id: str = Path(..., description="Account ID"),user_id: str = Path(..., description="User ID"),- ctx: RequestContext = require_role(Role.ROOT),+ ctx: RequestContext = require_admin_role(Role.ROOT),):"""Change a user's role (ROOT only)."""manager = _get_api_key_manager(request)@@ -213,7 +249,7 @@ async def regenerate_key(request: Request,account_id: str = Path(..., description="Account ID"),user_id: str = Path(..., description="User ID"),- ctx: RequestContext = require_role(Role.ROOT, Role.ADMIN),+ ctx: RequestContext = require_admin_role(Role.ROOT, Role.ADMIN),):"""Regenerate a user's API key. Old key is immediately invalidated."""_check_account_access(ctx, account_id)diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.pyindex d6b5c58e1..9f7ed9de9 100644--- a/tests/server/test_admin_api.py+++ b/tests/server/test_admin_api.py@@ -344,3 +344,58 @@ async def test_no_auth_admin_api_returns_401(admin_client: httpx.AsyncClient):"""Admin API without key should return 401."""resp = await admin_client.get("/api/v1/admin/accounts")assert resp.status_code == 401+++@pytest_asyncio.fixture(scope="function")+async def trusted_admin_app(admin_service):+ config = ServerConfig(auth_mode="trusted")+ app = create_app(config=config, service=admin_service)+ set_service(admin_service)+ return app+++@pytest_asyncio.fixture(scope="function")+async def trusted_admin_client(trusted_admin_app):+ transport = httpx.ASGITransport(app=trusted_admin_app)+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as c:+ yield c+++async def test_trusted_mode_create_account_returns_mode_specific_error(+ trusted_admin_client: httpx.AsyncClient,+):+ """Trusted mode should explain why account management is unavailable."""+ resp = await trusted_admin_client.post(+ "/api/v1/admin/accounts",+ json={"account_id": _uid(), "admin_user_id": "alice"},+ headers={+ "X-OpenViking-Account": "acme",+ "X-OpenViking-User": "alice",+ },+ )+ assert resp.status_code == 403+ body = resp.json()+ assert body["error"]["code"] == "PERMISSION_DENIED"+ assert "trusted mode" in body["error"]["message"].lower()+ assert "user-key registration" in body["error"]["message"].lower()+ assert "api_key mode" in body["error"]["message"].lower()+++async def test_trusted_mode_register_user_returns_mode_specific_error(+ trusted_admin_client: httpx.AsyncClient,+):+ """Trusted mode should explain why user registration is unavailable."""+ resp = await trusted_admin_client.post(+ "/api/v1/admin/accounts/acme/users",+ json={"user_id": "bob", "role": "user"},+ headers={+ "X-OpenViking-Account": "acme",+ "X-OpenViking-User": "alice",+ },+ )+ assert resp.status_code == 403+ body = resp.json()+ assert body["error"]["code"] == "PERMISSION_DENIED"+ assert "trusted mode" in body["error"]["message"].lower()+ assert "resolved as user" in body["error"]["message"].lower()+ assert "root_api_key" in body["error"]["message"].lower()