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
fix(auth)!: trusted 模式强制要求 root API key (#5947)
Qin Haojiedf2b6df27964
diff --git a/bot/tests/test_openapi_auth.py b/bot/tests/test_openapi_auth.pyindex 52aff0743..ebd1e166a 100644--- a/bot/tests/test_openapi_auth.py+++ b/bot/tests/test_openapi_auth.py@@ -688,15 +688,16 @@ class TestOpenAPIAuth:"server_url": "http://ov.local",}- def test_chat_rejects_keyless_forwarded_connection_in_api_key_mode(- self, message_bus, temp_workspace, monkeypatch+ @pytest.mark.parametrize("auth_mode", ["api_key", "trusted"])+ def test_chat_rejects_keyless_forwarded_connection_in_authenticated_modes(+ self, message_bus, temp_workspace, monkeypatch, auth_mode):- """api_key upstream must not accept forged identity without an API key."""+ """Authenticated upstreams must not accept forged identity without an API key."""config = SimpleNamespace(gateway=SimpleNamespace(host="127.0.0.1", token=""),ov_server=SimpleNamespace(server_url="http://ov.local",- effective_auth_mode="api_key",+ effective_auth_mode=auth_mode,api_key_type="user",),)@@ -718,11 +719,11 @@ class TestOpenAPIAuth:return Noneasync def get(self, url, headers=None):- # Unauthenticated /health in api_key mode: mode only, no identity.- return httpx.Response(200, json={"status": "ok", "auth_mode": "api_key"})+ # Anonymous /health returns the mode without an identity.+ return httpx.Response(200, json={"status": "ok", "auth_mode": auth_mode})async def fake_handle_chat(_request):- raise AssertionError("chat handler must not run for keyless api_key forwards")+ raise AssertionError("chat handler must not run for keyless authenticated forwards")monkeypatch.setattr("vikingbot.channels.openapi.httpx.AsyncClient", FakeAsyncClient)monkeypatch.setattr(channel, "_handle_chat", fake_handle_chat)@@ -747,18 +748,19 @@ class TestOpenAPIAuth:assert response.status_code == 401assert "API key required on forwarded connection" in response.json()["detail"]- def test_compile_rejects_keyless_forwarded_connection_in_api_key_mode(- self, message_bus, temp_workspace, monkeypatch+ @pytest.mark.parametrize("auth_mode", ["api_key", "trusted"])+ def test_compile_rejects_keyless_forwarded_connection_in_authenticated_modes(+ self, message_bus, temp_workspace, monkeypatch, auth_mode):class FakeCompileService:async def create_task(self, request, *, principal_scope, task_id=None):- raise AssertionError("compile task must not start for keyless api_key forwards")+ raise AssertionError("compile task must not start for keyless authenticated forwards")config = SimpleNamespace(gateway=SimpleNamespace(host="127.0.0.1", token=""),ov_server=SimpleNamespace(server_url="http://ov.local",- effective_auth_mode="api_key",+ effective_auth_mode=auth_mode,api_key_type="user",),)@@ -781,7 +783,7 @@ class TestOpenAPIAuth:return Noneasync def get(self, url, headers=None):- return httpx.Response(200, json={"status": "ok", "auth_mode": "api_key"})+ return httpx.Response(200, json={"status": "ok", "auth_mode": auth_mode})monkeypatch.setattr("vikingbot.channels.openapi.httpx.AsyncClient", FakeAsyncClient)app = FastAPI()@@ -810,14 +812,15 @@ class TestOpenAPIAuth:assert response.status_code == 401assert "API key required on forwarded connection" in response.json()["detail"]- def test_feedback_rejects_keyless_forwarded_connection_in_api_key_mode(- self, message_bus, temp_workspace, monkeypatch+ @pytest.mark.parametrize("auth_mode", ["api_key", "trusted"])+ def test_feedback_rejects_keyless_forwarded_connection_in_authenticated_modes(+ self, message_bus, temp_workspace, monkeypatch, auth_mode):config = SimpleNamespace(gateway=SimpleNamespace(host="127.0.0.1", token=""),ov_server=SimpleNamespace(server_url="http://ov.local",- effective_auth_mode="api_key",+ effective_auth_mode=auth_mode,api_key_type="user",),)@@ -839,10 +842,10 @@ class TestOpenAPIAuth:return Noneasync def get(self, url, headers=None):- return httpx.Response(200, json={"status": "ok", "auth_mode": "api_key"})+ return httpx.Response(200, json={"status": "ok", "auth_mode": auth_mode})async def fake_handle_feedback(_request):- raise AssertionError("feedback handler must not run for keyless api_key forwards")+ raise AssertionError("feedback handler must not run for keyless authenticated forwards")monkeypatch.setattr("vikingbot.channels.openapi.httpx.AsyncClient", FakeAsyncClient)monkeypatch.setattr(channel, "_handle_feedback", fake_handle_feedback)@@ -1209,8 +1212,10 @@ class TestOpenAPIAuth:assert captured["connection"]["user_id"] == "alice"assert captured["connection"]["api_key_type"] == "root"+ @pytest.mark.parametrize("configured_key", ["", "configured-root-key"])+ @pytest.mark.parametrize("client_host", ["127.0.0.1", "203.0.113.1"])def test_chat_rejects_trusted_identity_without_request_api_key(- self, message_bus, temp_workspace, monkeypatch+ self, message_bus, temp_workspace, monkeypatch, configured_key, client_host):config = SimpleNamespace(gateway=SimpleNamespace(host="127.0.0.1", token=""),@@ -1218,7 +1223,7 @@ class TestOpenAPIAuth:server_url="http://ov.local",effective_auth_mode="trusted",api_key_type="root",- api_key="configured-root-key",+ api_key=configured_key,account_id="configured-account",admin_user_id="configured-user",),@@ -1252,7 +1257,9 @@ class TestOpenAPIAuth:monkeypatch.setattr("vikingbot.channels.openapi.httpx.AsyncClient", FakeAsyncClient)monkeypatch.setattr(channel, "_handle_chat", fake_handle_chat)- client = _make_client(channel)+ app = FastAPI()+ app.include_router(channel.get_router(), prefix="/bot/v1")+ client = TestClient(app, client=(client_host, 50000))response = client.post("/bot/v1/chat",@@ -1266,75 +1273,11 @@ class TestOpenAPIAuth:assert response.status_code == 401assert response.json()["detail"] == "OpenViking API key header required"- def test_compile_status_rejects_untrusted_identity_when_no_root_key_is_configured(- self, message_bus, temp_workspace, monkeypatch- ):- config = SimpleNamespace(- gateway=SimpleNamespace(host="127.0.0.1", token=""),- ov_server=SimpleNamespace(- server_url="http://ov.local",- effective_auth_mode="trusted",- api_key_type="root",- api_key="",- account_id="",- admin_user_id="",- ),- )- compile_service = SimpleNamespace()- channel = OpenAPIChannel(- OpenAPIChannelConfig(),- message_bus,- workspace_path=temp_workspace,- global_config=config,- compile_service=compile_service,- )-- class FakeAsyncClient:- def __init__(self, **kwargs):- self.kwargs = kwargs-- async def __aenter__(self):- return self-- async def __aexit__(self, exc_type, exc, tb):- return None-- async def get(self, url, headers=None):- raise AssertionError("untrusted keyless identity must not hit upstream health")-- async def fake_get_task(task_id, principal_scope):- raise AssertionError("compile task must not be read for untrusted keyless identity")-- compile_service.get_task = fake_get_task- monkeypatch.setattr("vikingbot.channels.openapi.httpx.AsyncClient", FakeAsyncClient)- client = _make_client(channel)-- response = client.get(- "/bot/v1/compile/cmp_1",- headers={- "X-OpenViking-Account": "acct",- "X-OpenViking-User": "alice",- },- )-- assert response.status_code == 401- assert (- response.json()["detail"]- == "Trusted OpenViking identity requires a trusted local proxy or configured root API key"- )-- @pytest.mark.parametrize(- ("root_api_key_required", "expected_status"),- [(False, 401), (True, 200)],- ids=["rootless-rejects-request-key", "root-key-validates-request-key"],- )def test_compile_status_validates_request_key_when_not_statically_configured(self,message_bus,temp_workspace,monkeypatch,- root_api_key_required,- expected_status,):config = SimpleNamespace(gateway=SimpleNamespace(host="127.0.0.1", token=""),@@ -1375,7 +1318,7 @@ class TestOpenAPIAuth:json={"status": "ok","auth_mode": "trusted",- "root_api_key_required": root_api_key_required,+ "root_api_key_required": True,"role": "user","account_id": "acct","user_id": "alice",@@ -1384,8 +1327,6 @@ class TestOpenAPIAuth:)async def fake_get_task(task_id, principal_scope):- if not root_api_key_required:- raise AssertionError("rootless request key must not authorize compile access")assert task_id == "cmp_1"assert principal_scope == channel._principal_scope("openviking:acct:alice")return {@@ -1409,88 +1350,6 @@ class TestOpenAPIAuth:},)- assert response.status_code == expected_status- if not root_api_key_required:- assert (- response.json()["detail"]- == "Trusted OpenViking identity requires a trusted local proxy or upstream-validated root API key"- )-- def test_compile_status_accepts_local_trusted_identity_when_no_root_key_is_configured(- self, message_bus, temp_workspace, monkeypatch- ):- config = SimpleNamespace(- gateway=SimpleNamespace(host="127.0.0.1", token=""),- ov_server=SimpleNamespace(- server_url="http://ov.local",- effective_auth_mode="trusted",- api_key_type="root",- api_key="",- account_id="",- admin_user_id="",- ),- )- compile_service = SimpleNamespace()- channel = OpenAPIChannel(- OpenAPIChannelConfig(),- message_bus,- workspace_path=temp_workspace,- global_config=config,- compile_service=compile_service,- )-- class FakeAsyncClient:- def __init__(self, **kwargs):- self.kwargs = kwargs-- async def __aenter__(self):- return self-- async def __aexit__(self, exc_type, exc, tb):- return None-- async def get(self, url, headers=None):- assert "X-API-Key" not in headers- assert headers["X-OpenViking-Account"] == "acct"- assert headers["X-OpenViking-User"] == "alice"- return httpx.Response(- 200,- json={- "status": "ok",- "auth_mode": "trusted",- "role": "user",- "account_id": "acct",- "user_id": "alice",- },- headers={"content-type": "application/json"},- )-- async def fake_get_task(task_id, principal_scope):- assert task_id == "cmp_1"- assert principal_scope == channel._principal_scope("openviking:acct:alice")- return {- "task_id": task_id,- "status": "running",- "stage": "agent",- "created_at": "2026-07-20T00:00:00Z",- "updated_at": "2026-07-20T00:00:01Z",- }-- compile_service.get_task = fake_get_task- monkeypatch.setattr("vikingbot.channels.openapi.httpx.AsyncClient", FakeAsyncClient)- app = FastAPI()- app.include_router(channel.get_router(), prefix="/bot/v1")- app.include_router(channel.get_gateway_router())- client = TestClient(app, client=("127.0.0.1", 50000))-- response = client.get(- "/bot/v1/compile/cmp_1",- headers={- "X-OpenViking-Account": "acct",- "X-OpenViking-User": "alice",- },- )-assert response.status_code == 200assert response.json()["task_id"] == "cmp_1"diff --git a/bot/tests/test_openviking_api_key_type.py b/bot/tests/test_openviking_api_key_type.pyindex ae3d7851f..85be5f59d 100644--- a/bot/tests/test_openviking_api_key_type.py+++ b/bot/tests/test_openviking_api_key_type.py@@ -614,13 +614,17 @@ def test_validate_openviking_auth_exits_when_explicit_server_unavailable(monkeypassert "user-key" not in captured.err-def test_validate_openviking_auth_keeps_managed_upstream_while_server_starts(monkeypatch, capsys):[email protected]("auth_mode", ["api_key", "trusted"])+def test_validate_openviking_auth_keeps_managed_upstream_while_server_starts(+ monkeypatch, capsys, auth_mode+):config = SimpleNamespace(ov_server=SimpleNamespace(_source="inherited",_server_managed=True,+ effective_auth_mode=auth_mode,mode="remote",- api_key_type="user",+ api_key_type="root" if auth_mode == "trusted" else "user",api_key="",root_api_key="",server_url="http://127.0.0.1:1935",@@ -632,6 +636,11 @@ def test_validate_openviking_auth_keeps_managed_upstream_while_server_starts(monlambda *_args, **_kwargs: _auth_probe(ok=False, status_code=None, error="ConnectError"),)+ if auth_mode == "trusted":+ with pytest.raises(SystemExit):+ config_loader_module.validate_openviking_auth(config)+ assert "no valid root API key" in capsys.readouterr().err+ returnconfig_loader_module.validate_openviking_auth(config)assert config.ov_server.server_url == "http://127.0.0.1:1935"@@ -972,30 +981,6 @@ def test_viking_client_request_connection_preserves_trusted_scope(monkeypatch):}-def test_viking_client_request_connection_allows_trusted_no_key(monkeypatch):- monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))-- VikingClient(- agent_id="workspace#channel",- connection={- "server_url": "http://studio.local",- "account_id": "acct",- "user_id": "alice",- "agent_id": "web-playground",- "role": "user",- "api_key_type": "root",- },- )-- first = _DummyHTTPClient.instances[0]- assert first.kwargs == {- "url": "http://ov.local",- "profile_enabled": False,- "account": "acct",- "user": "alice",- }--def test_viking_client_request_connection_does_not_fill_identity_from_bot_config(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("user"))diff --git a/bot/vikingbot/channels/openapi.py b/bot/vikingbot/channels/openapi.pyindex 01e0e8dfd..a01c80e62 100644--- a/bot/vikingbot/channels/openapi.py+++ b/bot/vikingbot/channels/openapi.py@@ -914,11 +914,8 @@ class OpenAPIChannel(BaseChannel):rebuilt["agent_id"] = agent_idreturn OpenVikingConnection(**rebuilt)- # Keyless forwards are only valid for trusted/dev upstreams. In api_key- # mode, unauthenticated /health still returns 200 with auth_mode and no- # resolved identity, so claimed account/user/role must not be accepted- # without a real API key (Web Studio review on #4866).- if auth_mode not in {"trusted", "dev"}:+ # Only dev mode accepts forwarded identities without an API key.+ if auth_mode != "dev":raise HTTPException(status_code=401,detail=(@@ -927,7 +924,7 @@ class OpenAPIChannel(BaseChannel):),)- # Trusted / DEV forwards may omit api_key; keep proxy-asserted identity+ # DEV forwards may omit api_key; keep proxy-asserted identity# but never honor a client-chosen upstream URL.values["server_url"] = self._ov_server_url()values["agent_id"] = agent_id@@ -983,27 +980,12 @@ class OpenAPIChannel(BaseChannel):actor_peer_id=request.headers.get("X-OpenViking-Actor-Peer", ""),)- async def _resolve_trusted_connection(- self,- request: Request,- auth: GatewayRequestAuth,- ) -> dict[str, Any] | None:+ async def _resolve_trusted_connection(self, request: Request) -> dict[str, Any] | None:if not self._ov_server_url():return Noneapi_key = self._extract_api_key(request)- configured_api_key = str(- getattr(getattr(self._global_config, "ov_server", None), "api_key", "") or ""- ).strip()- if not api_key and configured_api_key:+ if not api_key:raise HTTPException(status_code=401, detail="OpenViking API key header required")- if not configured_api_key and not api_key and not auth.can_trust_forwarded_connection:- raise HTTPException(- status_code=401,- detail=(- "Trusted OpenViking identity requires a trusted local proxy "- "or configured root API key"- ),- )account_id = str(request.headers.get("X-OpenViking-Account") or "").strip()user_id = str(request.headers.get("X-OpenViking-User") or "").strip()if not account_id or not user_id:@@ -1022,18 +1004,6 @@ class OpenAPIChannel(BaseChannel):)health = await self._request_upstream_health(request)self._assert_runtime_health_mode(health)- if (- not configured_api_key- and not auth.can_trust_forwarded_connection- and health.get("root_api_key_required") is not True- ):- raise HTTPException(- status_code=401,- detail=(- "Trusted OpenViking identity requires a trusted local proxy "- "or upstream-validated root API key"- ),- )resolved_account_id = str(health.get("account_id") or "").strip()resolved_user_id = str(health.get("user_id") or "").strip()role = str(health.get("role") or "").strip().lower()@@ -1205,7 +1175,7 @@ class OpenAPIChannel(BaseChannel):self._assert_runtime_health_mode(health)connection = self._resolve_api_key_connection(http_request, health)elif auth_mode == "trusted":- connection = await self._resolve_trusted_connection(http_request, auth)+ connection = await self._resolve_trusted_connection(http_request)else:raise HTTPException(status_code=503,diff --git a/bot/vikingbot/config/loader.py b/bot/vikingbot/config/loader.pyindex eb78fadda..418341e70 100644--- a/bot/vikingbot/config/loader.py+++ b/bot/vikingbot/config/loader.py@@ -381,10 +381,11 @@ def _ov_server_is_server_managed(ov_server: Any) -> bool:return bool(getattr(ov_server, "_server_managed", False))-def _ov_server_trusted_api_key(ov_server: Any) -> str:- if _normalize_api_key_type(getattr(ov_server, "api_key_type", "")) == "root":- return str(getattr(ov_server, "api_key", "") or "").strip()- return ""+def _require_trusted_api_key(ov_server: Any) -> str:+ api_key = str(getattr(ov_server, "api_key", "") or "").strip()+ if not api_key or _normalize_api_key_type(getattr(ov_server, "api_key_type", "")) != "root":+ _raise_trusted_mode_requires_root_key(ov_server)+ return api_key@dataclass@@ -685,17 +686,14 @@ def _validate_api_key_mode_key(ov_server: Any, server_url: str) -> None:def _validate_trusted_mode_key(ov_server: Any, server_url: str) -> None:- root_api_key = _ov_server_trusted_api_key(ov_server)- if not root_api_key:- _raise_trusted_mode_requires_root_key(ov_server)+ root_api_key = _require_trusted_api_key(ov_server)account_id = str(getattr(ov_server, "account_id", "") or "default").strip()user_id = str(getattr(ov_server, "admin_user_id", "") or "default").strip()headers = {+ "X-API-Key": root_api_key,"X-OpenViking-Account": account_id,"X-OpenViking-User": user_id,}- if root_api_key:- headers["X-API-Key"] = root_api_keyresult = _request_openviking_json(server_url, "/api/v1/system/status", headers=headers)if result.ok:@@ -726,6 +724,8 @@ def validate_openviking_auth(config: Config) -> None:returnauth_mode = _ov_server_auth_mode(ov_server)+ if auth_mode == "trusted":+ _require_trusted_api_key(ov_server)# Build headers with API key if configured# Public gateways like Volcengine VikingDB require X-API-Key on every requestdiff --git a/bot/vikingbot/openviking_mount/ov_server.py b/bot/vikingbot/openviking_mount/ov_server.pyindex f6e7ff756..b921ed69f 100644--- a/bot/vikingbot/openviking_mount/ov_server.py+++ b/bot/vikingbot/openviking_mount/ov_server.py@@ -156,12 +156,6 @@ class VikingClient:if isinstance(value, str) and value.strip():normalized[key] = value.strip()if not normalized.get("api_key"):- if (- normalized.get("api_key_type") == "root"- and normalized.get("account_id")- and normalized.get("user_id")- ):- return normalizedreturn Nonereturn normalizeddiff --git a/docs/en/api/07-system.md b/docs/en/api/07-system.mdindex bd62fa6e1..78a175fcc 100644--- a/docs/en/api/07-system.md+++ b/docs/en/api/07-system.md@@ -11,11 +11,10 @@ The OpenViking System API provides health, readiness, consistency, and multi-wriBasic liveness check; no authentication is required. Returns the service version, health status, and auth mode. Supplied credentials trigger identity resolution; successful resolution adds identity fields, and invalid credentials are rejected with an authentication error.In trusted mode, a complete `X-OpenViking-Account` and `X-OpenViking-User` header pair-requests identity resolution, including on localhost deployments with `root_api_key`-omitted. Configured Root keys remain required for authenticated requests. The optional-`root_api_key_required` boolean reports that trusted-server configuration requirement;-the resolved `role` describes the caller's permissions. Older servers may omit this field.-Anonymous health probes return basic liveness information.+requests identity resolution and requires the matching root API key, including on+localhost. `root_api_key_required` is always `true` in trusted mode; the resolved `role`+describes the caller's permissions. Anonymous health probes return basic liveness+information without identity fields.**Code Entry Points**:- `openviking/server/routers/system.py:health_check` - HTTP routediff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.mdindex d782b9a17..932557caf 100644--- a/docs/en/guides/01-configuration.md+++ b/docs/en/guides/01-configuration.md@@ -1921,7 +1921,7 @@ When running OpenViking as an HTTP service, add a `server` section to `ov.conf`:| `host` | str | Bind address | `127.0.0.1` || `port` | int | Bind port | `1933` || `auth_mode` | str / null | Built-in modes: `"dev"`, `"api_key"`, `"trusted"`, `"oidc"`, `"ldap"`. When omitted/null, infer `api_key` from a non-empty `root_api_key`; otherwise infer `dev`. | `null` |-| `root_api_key` | str | Root API key for multi-tenant auth in `api_key` mode. In `trusted` mode it is optional on localhost, but required for any non-localhost deployment; it does not become the source of user identity | `null` |+| `root_api_key` | str | Root API key for multi-tenant auth in `api_key` mode. In `trusted` mode it is required on every deployment, including localhost; it does not become the source of user identity | `null` || `profile_enabled` | bool | Whether to allow request-scoped cProfile via `profile=1` on HTTP requests. When disabled, the server ignores that query parameter. When enabled, the CLI can display the returned `profile`, while the Python HTTP client currently triggers profiling but does not automatically attach the top-level `profile` field to most SDK return values. | `false` || `cors_origins` | list | Allowed CORS origins | `["*"]` || `public_base_url` | str | Public-facing base URL emitted in MCP-issued upload instructions. Resolution order: env var `OPENVIKING_PUBLIC_BASE_URL` → this field → `X-Forwarded-Host`/`X-Forwarded-Proto` request headers → `Host` request header → listen-address fallback. Set this (or the env var) when the server runs behind a reverse proxy that does not forward `X-Forwarded-*` headers. | `null` |@@ -1937,7 +1937,7 @@ When running OpenViking as an HTTP service, add a `server` section to `ov.conf`:Omitting `auth_mode` (or setting it to `null`) selects `api_key` when a non-empty `root_api_key` is configured, and `dev` otherwise. `dev` is allowed only on localhost and accepts requests without authentication. An empty-string `root_api_key` is invalid.-Explicit `auth_mode: "api_key"` requires a non-empty `root_api_key`, including on localhost; without it, startup fails instead of falling back to development mode. Use the root key with the Admin API to create accounts and user/admin keys; use those tenant-bound keys for data access. `trusted` mode accepts account/user identity headers from a trusted gateway and does not require user-key provisioning first. Its root key is optional only on localhost and required for non-localhost binds. For role resolution, OIDC/LDAP setup, and gateway requirements, see [Authentication](04-authentication.md).+Explicit `auth_mode: "api_key"` requires a non-empty `root_api_key`, including on localhost; without it, startup fails instead of falling back to development mode. Use the root key with the Admin API to create accounts and user/admin keys; use those tenant-bound keys for data access. `trusted` mode accepts account/user identity headers from a trusted gateway and does not require user-key provisioning first. Its non-empty root key is required for startup and authenticated requests on every bind address, including localhost. For role resolution, OIDC/LDAP setup, and gateway requirements, see [Authentication](04-authentication.md).`user_config_defaults` provides deployment defaults for add targets and memory extraction. For add operations, explicit request targets still win: `add_resource.to` / `add_resource.parent` take precedence over user defaults, and `add_skill.target_uri` takes precedence over user defaults. Memory policy precedence is Session policy > User `settings/user_config.json` policy > `server.user_config_defaults.memory_policy` > kernel default. `server.agent_evolution.enabled` supplies the startup default. Runtime resolution is Account override > Cluster runtime override > that startup value. Use the Admin settings APIs for changes without restarting; editing `ov.conf` directly takes effect after restart.diff --git a/docs/en/guides/04-authentication.md b/docs/en/guides/04-authentication.mdindex 25ed656ac..c0c518785 100644--- a/docs/en/guides/04-authentication.md+++ b/docs/en/guides/04-authentication.md@@ -11,7 +11,7 @@ API Key mode is recommended for most deployments; it is auto-selected when no mo| **API Key Mode** | `api_key` | API key. Data ownership is resolved from the user/admin key. | Standard multi-tenant deployment || **OIDC Mode** | `oidc` | JWT tokens from external identity providers | Enterprise SSO integration with Okta/Auth0/Keycloak || **LDAP Mode** | `ldap` | Enterprise LDAP/AD directory services | Integrate with existing enterprise user directory |-| **Trusted Mode** | `trusted` | `X-OpenViking-Account` / `X-OpenViking-User`, plus `root_api_key` on non-localhost deployments. Role is looked up from APIKeyManager if the user exists. | Behind a trusted gateway or internal network boundary |+| **Trusted Mode** | `trusted` | `X-OpenViking-Account` / `X-OpenViking-User`, plus `root_api_key` on every deployment. Role is looked up from APIKeyManager if the user exists. | Behind a trusted gateway or internal network boundary || **Dev Mode** | `dev` | No authentication, always ROOT | Local development only |If `auth_mode` is not explicitly configured:@@ -506,17 +506,20 @@ curl https://openviking.example.com/api/v1/fs/ls?uri=viking:// \## Trusted Mode-Trusted mode skips user-key lookup and instead trusts explicit identity headers on each request:+Trusted mode requires a root API key to authenticate the upstream and uses explicit identity headers instead of user-key lookup:```json{"server": {"auth_mode": "trusted",+ "root_api_key": "your-secret-root-key","host": "127.0.0.1"}}```+A missing, empty, or whitespace-only `server.root_api_key` prevents startup, including on localhost.+### Rules in Trusted Mode- Normal data access does not require user registration or user-key provisioning first.@@ -524,9 +527,9 @@ Trusted mode skips user-key lookup and instead trusts explicit identity headers- A trusted upstream may also send `X-OpenViking-Role: user` or `X-OpenViking-Role: admin` to assert the request role. This header is accepted only when `root_api_key` is configured and the request presents the matching API key. `root` is not an allowed asserted value; ROOT is reserved for validated Admin API fallback.- `/api/v1/admin/*` is special: when a configured `root_api_key` is presented, trusted mode treats the request as ROOT. Explicit account/user headers are allowed only when they are complete and match the target URL.- For ordinary trusted data APIs, role is determined by `X-OpenViking-Role` when present and authorized; otherwise by looking up the account/user in APIKeyManager. If the user exists, their configured role is used; otherwise it defaults to `USER`.-- Trusted identity comes from the headers, not from a user key. If `root_api_key` is configured, it acts as proof that the caller is an approved trusted upstream.+- Trusted identity comes from the headers, not from a user key. The required `root_api_key` authenticates the trusted upstream.- Trusted data-plane identities are asynchronously registered in batches (five minutes by default) so they eventually appear in the existing account/user management APIs. Registration creates no user API key and never changes groups or an existing user's role. Set `server.trusted_identity_flush_interval_seconds` to `0` to disable registration entirely; `/api/v1/admin/*` requests are never registered.-- If `root_api_key` is also configured, every request must still provide a matching API key.+- Every authenticated request must provide the matching root API key. Anonymous `/health` probes remain available for liveness checks.- Only expose this mode behind a trusted network boundary or an identity-injecting gateway.### Trusted Deployment Admin API@@ -559,12 +562,13 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \}```-The curl and SDK examples below use the localhost configuration without a root key. If one is configured, also provide it as `X-API-Key` or SDK `api_key`.+Provide the configured root key as `X-API-Key` or SDK `api_key`, including when connecting to localhost.**curl Example**```bashcurl http://localhost:1933/api/v1/fs/ls?uri=viking:// \+ -H "X-API-Key: your-secret-root-key" \-H "X-OpenViking-Account: acme" \-H "X-OpenViking-User: alice"```@@ -576,6 +580,7 @@ import openviking_sdk as ovclient = ov.SyncHTTPClient(url="http://localhost:1933",+ api_key="your-secret-root-key",account="acme",user="alice",)@@ -618,11 +623,11 @@ Or explicitly:Regular resource operations in this table are still subject to resource ACLs. Account roles determine identity administration and implicit management of public resources; [Resource Access Control (ACL)](../concepts/15-acl.md) determines `read/write/manage` permissions on individual directories and files.-In `trusted` mode, ordinary tenant requests default to `USER` unless the account/user is registered with a higher role or the gateway asserts `X-OpenViking-Role: admin` with the configured root API key. `X-OpenViking-Role: root` is rejected. Admin routes also allow a trusted ROOT fallback when no explicit identity is provided.+In `trusted` mode, ordinary tenant requests default to `USER` unless the account/user is registered with a higher role or the gateway asserts `X-OpenViking-Role: admin` with the configured root API key. `X-OpenViking-Role: root` is rejected. Admin routes grant ROOT only after validating the root key, with or without explicit identity headers.## Unauthenticated Endpoints-The `/health` endpoint never requires authentication. This allows load balancers and monitoring tools to check server health.+Anonymous `/health` requests require no credentials, allowing load balancers and monitoring tools to check server health. Supplying credentials or complete trusted identity headers triggers authentication.```bashcurl http://localhost:1933/healthdiff --git a/docs/zh/api/07-system.md b/docs/zh/api/07-system.mdindex 614559f62..9281b3fb1 100644--- a/docs/zh/api/07-system.md+++ b/docs/zh/api/07-system.md@@ -11,9 +11,8 @@ OpenViking 系统 API 提供健康检查、就绪检查、一致性检查和主基础存活检查,无需认证。返回版本号、健康状态和认证模式。提供凭据后会尝试解析身份,成功时补充身份字段;凭据无效时返回认证错误。Trusted 模式下,完整的 `X-OpenViking-Account` 和 `X-OpenViking-User` 请求头会触发身份解析,-包括省略 `root_api_key` 的 localhost 部署。配置了 Root 密钥的服务继续校验认证请求中的密钥。-可选布尔字段 `root_api_key_required` 表示 Trusted 服务配置的密钥要求,解析得到的 `role`-表示调用者权限。较早版本可能省略该字段。匿名健康探测返回基础存活信息。+必须携带匹配的 root API key,localhost 也不例外。Trusted 模式的 `root_api_key_required`+始终为 `true`,解析得到的 `role` 表示调用者权限。匿名健康探测返回基础存活信息,不包含身份字段。**代码入口**:- `openviking/server/routers/system.py:health_check` - HTTP 路由diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.mdindex 2e0d2cd0b..59324bb0a 100644--- a/docs/zh/guides/01-configuration.md+++ b/docs/zh/guides/01-configuration.md@@ -1911,7 +1911,7 @@ ov add-resource ./docs --exclude "*.tmp"| `host` | str | 绑定地址 | `127.0.0.1` || `port` | int | 绑定端口 | `1933` || `auth_mode` | str / null | 内置模式:`"dev"`、`"api_key"`、`"trusted"`、`"oidc"`、`"ldap"`。省略或设为 null 时,有非空 `root_api_key` 则推导为 `api_key`,否则为 `dev`。 | `null` |-| `root_api_key` | str | `api_key` 模式必填的 Root API Key;`trusted` 模式仅在 localhost 可省略,非 localhost 部署必填,不负责解析普通用户身份 | `null` |+| `root_api_key` | str | `api_key` 模式必填的 Root API Key;`trusted` 模式在所有部署中均必填,包括 localhost,不负责解析普通用户身份 | `null` || `profile_enabled` | bool | 是否允许 HTTP 请求通过 `profile=1` 开启请求级 cProfile。关闭时服务端会忽略该请求参数;开启后,CLI 可以显示返回的 `profile`,而 Python HTTP client 默认只触发服务端 profile,不会把顶层 `profile` 字段自动附着到大多数 SDK 返回值上。 | `false` || `cors_origins` | list | CORS 允许的来源 | `["*"]` || `public_base_url` | str | MCP `add_resource` 和 `add_skill` 工具向客户端返回的上传指令里使用的对外可见 base URL。解析顺序:环境变量 `OPENVIKING_PUBLIC_BASE_URL` → 本字段 → 请求头 `X-Forwarded-Host` / `X-Forwarded-Proto` → 请求头 `Host` → 监听地址兜底。当 server 部署在反向代理后且代理不转发 `X-Forwarded-*` 时,请显式设置本字段(或环境变量)。 | `null` |@@ -1927,7 +1927,7 @@ ov add-resource ./docs --exclude "*.tmp"省略 `auth_mode`(或设为 `null`)时,配置了非空 `root_api_key` 则选择 `api_key`,否则选择 `dev`。`dev` 仅允许监听 localhost,不进行身份认证。`root_api_key` 不能配置为空字符串。-显式设置 `auth_mode: "api_key"` 时,包括 localhost 在内都必须提供非空 `root_api_key`;缺少该 key 会导致启动失败,不会回退到开发模式。使用 root key 调用 Admin API 创建 account 和 user/admin key,数据访问使用这些绑定租户身份的 key。`trusted` 模式接受可信网关注入的 account/user 身份头,无需预先创建 user key;其 root key 仅在 localhost 可省略,监听非 localhost 地址时必填。角色解析、OIDC/LDAP 配置与网关要求参见 [身份认证](04-authentication.md)。+显式设置 `auth_mode: "api_key"` 时,包括 localhost 在内都必须提供非空 `root_api_key`;缺少该 key 会导致启动失败,不会回退到开发模式。使用 root key 调用 Admin API 创建 account 和 user/admin key,数据访问使用这些绑定租户身份的 key。`trusted` 模式接受可信网关注入的 account/user 身份头,无需预先创建 user key;其非空 root key 是启动和认证请求的必要条件,包括 localhost。角色解析、OIDC/LDAP 配置与网关要求参见 [身份认证](04-authentication.md)。`user_config_defaults` 提供添加目标和记忆抽取的部署级默认配置。添加操作中,显式请求目标仍然优先:`add_resource.to` / `add_resource.parent` 优先于用户默认值,`add_skill.target_uri` 优先于用户默认值。记忆策略优先级为 Session 策略 > User `settings/user_config.json` 策略 > `server.user_config_defaults.memory_policy` > 内核默认策略。`server.agent_evolution.enabled` 提供启动默认值,运行时优先级为 Account 覆盖 > Cluster 运行时覆盖 > 启动值。无需重启的修改应使用 Admin settings 接口;直接编辑 `ov.conf` 需要重启后生效。diff --git a/docs/zh/guides/04-authentication.md b/docs/zh/guides/04-authentication.mdindex bb1248f9e..1a940281b 100644--- a/docs/zh/guides/04-authentication.md+++ b/docs/zh/guides/04-authentication.md@@ -582,18 +582,19 @@ root key 请求上携带身份 header。## Trusted 模式-Trusted 模式不会查询 user key,而是直接信任每个请求显式携带的身份请求头:+Trusted 模式使用 root API key 验证上游,再从每个请求显式携带的身份请求头解析用户,不查询 user key:```json{"server": {"auth_mode": "trusted",+ "root_api_key": "your-secret-root-key","host": "127.0.0.1"}}```-数据请求必须提供 `X-OpenViking-Account` 和 `X-OpenViking-User`。若配置了 `root_api_key`,请求还必须携带匹配的 API Key,以验证上游网关。+`server.root_api_key` 缺失、为空或仅含空白时拒绝启动,localhost 也不例外。数据请求必须提供 `X-OpenViking-Account`、`X-OpenViking-User` 和匹配的 API Key,以验证上游网关。匿名 `/health` 存活探测仍可使用。角色默认从已注册用户查询,未注册时为 USER。配置并验证 root key 后,上游可用 `X-OpenViking-Role: user` 或 `admin` 断言角色,不接受 `root`。Admin API 的 ROOT 授权来自部署 root key。diff --git a/examples/hermes-plugin/CONFIGURATION.md b/examples/hermes-plugin/CONFIGURATION.mdindex 7c7c3bdd1..7d7d991e3 100644--- a/examples/hermes-plugin/CONFIGURATION.md+++ b/examples/hermes-plugin/CONFIGURATION.md@@ -103,8 +103,9 @@ home address requires OpenViking 0.4.16 or newer for user and admin keys, or| `OPENVIKING_AGENT` | (none) | Optional peer ID for separate assistant context |User and admin API keys let OpenViking derive account/user identity from the key.-In local or trusted deployments without an API key,+In trusted deployments, set `OPENVIKING_API_KEY` to the server's root API key;Hermes sends `OPENVIKING_ACCOUNT` and `OPENVIKING_USER` as identity headers.+Only local dev mode allows access without an API key.Hermes also sends `User-Agent: openviking-memory-hermes/<version>` onOpenViking requests. This header contains the Hermes version. It does notcontain a user identifier or require an extra request.diff --git a/openviking/server/auth/__init__.py b/openviking/server/auth/__init__.pyindex 4a03f696c..9f2509ca3 100644--- a/openviking/server/auth/__init__.py+++ b/openviking/server/auth/__init__.py@@ -33,12 +33,6 @@ def _auth_mode(request: Request) -> str:return AuthMode.API_KEY.value-def _configured_root_api_key(request: Request) -> Optional[str]:- config = getattr(request.app.state, "config", None)- key = getattr(config, "root_api_key", None)- return key if key != "" else None--def _extract_api_key(x_api_key: Optional[str], authorization: Optional[str]) -> Optional[str]:if not isinstance(x_api_key, str):x_api_key = Nonediff --git a/openviking/server/auth/health_check.py b/openviking/server/auth/health_check.pyindex 2b664e8bc..cb51f905c 100644--- a/openviking/server/auth/health_check.py+++ b/openviking/server/auth/health_check.py@@ -359,19 +359,29 @@ class TrustedAuthChecker(AuthHealthChecker):return "trusted"async def run_checks(self, config: ServerConfig) -> List[HealthCheckResult]:- from time import time- results: List[HealthCheckResult] = []-- # Basic config check- start_time = time()- results.append(HealthCheckResult(- name="trusted_config_valid",- status=HealthStatus.PASS,- message="Trusted mode configuration is valid",- duration_seconds=time() - start_time,- ))+ from openviking.server.auth.plugins.trusted import TrustedAuthPlugin- return results+ try:+ TrustedAuthPlugin().validate_config(config)+ except SystemExit:+ return [+ HealthCheckResult(+ name="trusted_config_valid",+ status=HealthStatus.FAIL,+ message=(+ "Trusted mode requires a non-empty server.root_api_key, including on "+ "localhost. Set it in the server's ov.conf, restart, and configure "+ "clients to use the same key."+ ),+ )+ ]+ return [+ HealthCheckResult(+ name="trusted_config_valid",+ status=HealthStatus.PASS,+ message="Trusted mode configuration is valid",+ )+ ]class DevAuthChecker(AuthHealthChecker):diff --git a/openviking/server/auth/plugins/trusted.py b/openviking/server/auth/plugins/trusted.pyindex 71b91b4b3..7ce9607a7 100644--- a/openviking/server/auth/plugins/trusted.py+++ b/openviking/server/auth/plugins/trusted.py@@ -19,7 +19,6 @@ from openviking.server.identity import ResolvedIdentity, Rolefrom openviking_cli.exceptions import InvalidArgumentError, UnauthenticatedErrorfrom openviking_cli.utils import get_logger-_LOCALHOST_HOSTS = {"127.0.0.1", "localhost", "::1"}_TRUSTED_ROLE_HEADER = "X-OpenViking-Role"_TRUSTED_ASSERTABLE_ROLES = {Role.USER: Role.USER,@@ -29,16 +28,6 @@ _TRUSTED_ASSERTABLE_ROLES = {logger = get_logger(__name__)-def _is_localhost(host: str) -> bool:- return host in _LOCALHOST_HOSTS---def _configured_root_api_key(request: Request) -> Optional[str]:- config = getattr(request.app.state, "config", None)- key = getattr(config, "root_api_key", None)- return key if key != "" else None--def _normalize_request_value(value: object) -> Optional[str]:if isinstance(value, str):normalized = value.strip()@@ -61,10 +50,6 @@ def _explicit_identity_from_request(request: Request) -> tuple[Optional[str], Opreturn account_id, user_id-def _trusted_request_requires_explicit_identity(path: str) -> bool:- return not _is_trusted_admin_path(path)--def _validate_trusted_identity(account_id: str, user_id: str) -> None:"""Reject invalid identity path components before registry lookup or enqueueing."""account_error = validate_account_id(account_id)@@ -79,16 +64,11 @@ def _is_trusted_admin_path(path: str) -> bool:return path == "/api/v1/admin" or path.startswith("/api/v1/admin/")-def _asserted_role_from_header(request: Request, *, allow_assertion: bool) -> Optional[Role]:+def _asserted_role_from_header(request: Request) -> Optional[Role]:raw_role = request.headers.get(_TRUSTED_ROLE_HEADER)normalized_role = _normalize_request_value(raw_role)if normalized_role is None:return None- if not allow_assertion:- raise InvalidArgumentError(- f"{_TRUSTED_ROLE_HEADER} requires trusted mode with Root API Key enabled."- )-role = normalized_role.lower()if role not in _TRUSTED_ASSERTABLE_ROLES:raise InvalidArgumentError(f"{_TRUSTED_ROLE_HEADER} must be one of: user, admin.")@@ -98,7 +78,7 @@ def _asserted_role_from_header(request: Request, *, allow_assertion: bool) -> Opclass TrustedAuthPlugin(AuthPlugin):"""Trusted mode: trust X-OpenViking-Account/User headers.- Optionally validates a configured root_api_key. Role is looked up from+ Requires a matching root_api_key on every authenticated request. Role is looked up fromAPIKeyManager if the user exists, otherwise defaults to USER."""@@ -122,20 +102,19 @@ class TrustedAuthPlugin(AuthPlugin):x_openviking_account: Optional[str] = None,x_openviking_user: Optional[str] = None,) -> ResolvedIdentity:- configured_root_api_key = _configured_root_api_key(request)- if configured_root_api_key:- if not api_key:- raise UnauthenticatedError(- "Missing API Key in trusted mode with Root API Key enabled."- )- if not hmac.compare_digest(api_key, configured_root_api_key):- raise UnauthenticatedError(- "Invalid API Key in trusted mode with Root API Key enabled."- )- asserted_role = _asserted_role_from_header(- request,- allow_assertion=bool(configured_root_api_key),- )+ configured_root_api_key = request.app.state.config.root_api_key+ if not api_key:+ raise UnauthenticatedError(+ "Missing API Key in trusted mode. Send X-API-Key with the value of "+ "server.root_api_key from the server's ov.conf. In Web Studio, enter "+ "this value in Connection settings > Root or Admin API Key."+ )+ if not configured_root_api_key or not hmac.compare_digest(api_key, configured_root_api_key):+ raise UnauthenticatedError(+ "Invalid API Key in trusted mode. The supplied key must match "+ "server.root_api_key in the server's ov.conf."+ )+ asserted_role = _asserted_role_from_header(request)explicit_account_id, explicit_user_id = _explicit_identity_from_request(request)if (@@ -159,108 +138,60 @@ class TrustedAuthPlugin(AuthPlugin):# they must not be mistaken for a partial caller identity.is_admin_path = _is_trusted_admin_path(request.url.path)if is_admin_path:- if configured_root_api_key:- return ResolvedIdentity(- role=Role.ROOT,- account_id=effective_account_id or "trusted",- user_id=effective_user_id or "trusted",- )- if bool(effective_account_id) != bool(effective_user_id):- raise InvalidArgumentError(- "Trusted mode requests must include "- "X-OpenViking-Account or explicit account_id in the URL and "- "X-OpenViking-User or explicit user_id in the URL."- )- if not effective_account_id and not effective_user_id:- return ResolvedIdentity(- role=Role.ROOT,- account_id="trusted",- user_id="trusted",- )-- if _trusted_request_requires_explicit_identity(request.url.path):- missing_fields = []- if not effective_account_id:- missing_fields.append("X-OpenViking-Account or explicit account_id in the URL")- if not effective_user_id:- missing_fields.append("X-OpenViking-User or explicit user_id in the URL")- if missing_fields:- raise InvalidArgumentError(- "Trusted mode requests must include " + " and ".join(missing_fields) + "."- )+ return ResolvedIdentity(+ role=Role.ROOT,+ account_id=effective_account_id or "trusted",+ user_id=effective_user_id or "trusted",+ )- if effective_account_id and effective_user_id:- _validate_trusted_identity(effective_account_id, effective_user_id)+ missing_fields = []+ if not effective_account_id:+ missing_fields.append("X-OpenViking-Account or explicit account_id in the URL")+ if not effective_user_id:+ missing_fields.append("X-OpenViking-User or explicit user_id in the URL")+ if missing_fields:+ raise InvalidArgumentError(+ "Trusted mode requests must include " + " and ".join(missing_fields) + "."+ )+ _validate_trusted_identity(effective_account_id, effective_user_id)- # In rootless trusted mode this manager stays private to the plugin so- # Admin routes remain disabled. It is still used to preserve a role- # explicitly assigned through the account/user management APIs.api_key_manager = self._api_key_managertrusted_role = Role.USERif asserted_role is not None:trusted_role = asserted_role- elif api_key_manager and effective_account_id and effective_user_id:+ elif api_key_manager:looked_up_role = api_key_manager.get_user_role(effective_account_id, effective_user_id)if looked_up_role is not None:trusted_role = looked_up_roleidentity = ResolvedIdentity(role=trusted_role,- account_id=effective_account_id or "trusted",- user_id=effective_user_id or "trusted",+ account_id=effective_account_id,+ user_id=effective_user_id,)- if (- self.should_auto_register_trusted_identity(request)- and not is_admin_path- and effective_account_id- and effective_user_id- ):+ if self.should_auto_register_trusted_identity(request):self._queue_trusted_identity(effective_account_id, effective_user_id)return identitydef validate_config(self, config) -> None:- if config.root_api_key and config.root_api_key != "":+ if config.root_api_key and config.root_api_key.strip():return- if _is_localhost(config.host):- import logging-- logger = logging.getLogger(__name__)- logger.warning(- "Trusted mode without API key: authentication trusts "- "X-OpenViking-Account/User headers. This is allowed because "- "the server is bound to localhost (%s).",- config.host,- )- return- import logging-- logger = logging.getLogger(__name__)logger.error(- "SECURITY: server.auth_mode='trusted' requires server.root_api_key when "- "server.host is '%s' (non-localhost). Only localhost trusted mode may run "- "without an API key.",- config.host,- )- logger.error(- "To fix, either:\n"- " 1. Set server.root_api_key in ov.conf, or\n"- ' 2. Bind trusted mode to localhost (server.host = "127.0.0.1")'+ "Cannot start OpenViking: trusted mode requires a non-empty server.root_api_key, "+ "including on localhost. Set server.root_api_key in the server's ov.conf and "+ "restart. Configure clients and Web Studio to use the same key.")sys.exit(1)async def initialize(self, app, service, config) -> None:api_key_manager = APIKeyManager(- root_key=config.root_api_key or "",+ root_key=config.root_api_key,viking_fs=service.viking_fs,api_key_hashing_enabled=config.api_key_hashing_enabled,)await api_key_manager.load()self._api_key_manager = api_key_manager- # ``require_auth_role`` treats a populated app-state manager as the- # availability signal for the Admin API. A rootless trusted deployment- # must therefore keep this manager plugin-private even though it needs- # one for the optional identity registry.- app.state.api_key_manager = api_key_manager if config.root_api_key else None+ app.state.api_key_manager = api_key_managerself._flush_interval_seconds = config.trusted_identity_flush_interval_secondsself._pending_max_size = config.trusted_identity_pending_max_sizeif self._flush_interval_seconds > 0:@@ -338,12 +269,6 @@ class TrustedAuthPlugin(AuthPlugin):self._flush_task = Noneawait self.flush_trusted_identities()- def requires_api_key_manager(self) -> bool:- return False-- def can_skip_api_key_for_bot_proxy(self) -> bool:- return True-def get_request_context_checks(self,path: str,diff --git a/openviking/server/config.py b/openviking/server/config.pyindex fa75c8eb9..04322a090 100644--- a/openviking/server/config.py+++ b/openviking/server/config.py@@ -547,7 +547,9 @@ def validate_server_config(config: ServerConfig) -> None:if config.root_api_key == "":logger.error("Invalid server.root_api_key: empty string is not allowed. "- "Either set a non-empty root_api_key or remove the setting entirely."+ "Set a non-empty server.root_api_key in ov.conf and restart. "+ "Only remove this setting if the selected auth mode does not require a root key; "+ "trusted and api_key modes require it even on localhost.")sys.exit(1)diff --git a/openviking/server/routers/bot.py b/openviking/server/routers/bot.pyindex ef5219a60..ddcaaaf69 100644--- a/openviking/server/routers/bot.py+++ b/openviking/server/routers/bot.py@@ -119,14 +119,6 @@ def _attach_openviking_connection(server_url = get_server_url_from_server_data(getattr(request.app.state, "config", None))if not api_key:if plugin is not None and plugin.can_skip_api_key_for_bot_proxy():- if effective_auth_mode == "trusted":- enriched["openviking_connection"] = _build_openviking_connection(- api_key="",- ctx=ctx,- effective_auth_mode=effective_auth_mode,- server_url=server_url,- )- return enrichedif include_legacy_user_id:enriched.setdefault("user_id", ctx.user.user_id)return enricheddiff --git a/openviking/server/routers/system.py b/openviking/server/routers/system.pyindex 93ad7ecca..0ef245f79 100644--- a/openviking/server/routers/system.py+++ b/openviking/server/routers/system.py@@ -11,7 +11,7 @@ from pydantic import BaseModelfrom openviking.core.path_variables import resolve_path_variablesfrom openviking.core.uri_validation import validate_request_viking_urifrom openviking.pyagfs.exceptions import AGFSInvalidOperationError, AGFSNotSupportedError-from openviking.server.auth import _configured_root_api_key, get_request_context, require_role+from openviking.server.auth import get_request_context, require_rolefrom openviking.server.dependencies import get_servicefrom openviking.server.identity import AuthMode, RequestContext, Rolefrom openviking.server.models import Response@@ -68,7 +68,7 @@ async def health_check(request: Request):effective_auth_mode = config.get_effective_auth_mode()result["auth_mode"] = effective_auth_modeif effective_auth_mode == AuthMode.TRUSTED.value:- result["root_api_key_required"] = bool(_configured_root_api_key(request))+ result["root_api_key_required"] = Truex_api_key = request.headers.get("X-API-Key")authorization = request.headers.get("Authorization")diff --git a/openviking_cli/doctor.py b/openviking_cli/doctor.pyindex 0d1b621b7..af4b2d5ec 100644--- a/openviking_cli/doctor.py+++ b/openviking_cli/doctor.py@@ -544,8 +544,7 @@ def check_vikingbot() -> CheckResult:return ("warn","server.auth_mode=trusted without server.root_api_key",- "Configure server.root_api_key for VikingBot trusted OpenViking calls "- "outside localhost",+ "Configure server.root_api_key; trusted mode requires it even on localhost",)return ("warn",diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.pyindex 52b154062..7dad658af 100644--- a/tests/server/test_admin_api.py+++ b/tests/server/test_admin_api.py@@ -3482,7 +3482,9 @@ async def test_user_page_summary_and_search_preserve_legacy_response()assert credentials["users"][0]["api_key"] == "test-key-2832"original_config = lightweight_admin_app.state.config- lightweight_admin_app.state.config = ServerConfig(auth_mode="trusted")+ lightweight_admin_app.state.config = ServerConfig(+ auth_mode="trusted", root_api_key=ROOT_KEY+ )try:with pytest.raises(PermissionDeniedError, match="trusted"):await mcp_endpoint.list_users(context, include_credentials=True)@@ -3546,7 +3548,7 @@ async def test_server_restart_requires_root_and_valid_revision(server = {}server_overrides = {}if cli_host:- server = {"host": "0.0.0.0", "auth_mode": "trusted"}+ server = {"host": "0.0.0.0", "auth_mode": "trusted", "root_api_key": ROOT_KEY}server_overrides = {"host": cli_host}lightweight_admin_app.state.server_config_overrides = server_overridespath.write_text(@@ -3610,6 +3612,7 @@ async def test_server_restart_requires_root_and_valid_revision({"port": "invalid"},{"root_api_key": ""},{"auth_mode": "api_key"},+ {"auth_mode": "trusted", "host": "127.0.0.1"},{"auth_mode": "dev", "host": "0.0.0.0"},],)diff --git a/tests/server/test_auth.py b/tests/server/test_auth.pyindex abeeccc75..f0376244f 100644--- a/tests/server/test_auth.py+++ b/tests/server/test_auth.py@@ -107,6 +107,8 @@ def _make_request(plugin_cls = registry.get(effective_auth_mode)if plugin_cls is not None:app.state.auth_plugin = plugin_cls()+ if effective_auth_mode == "trusted" and api_key_manager is not None:+ app.state.auth_plugin._api_key_manager = api_key_managerscope = {"type": "http","path": path,@@ -913,29 +915,6 @@ async def test_dev_mode_root_tenant_scoped_requests_keep_200_via_http():assert response.json()["status"] == "ok"-async def test_trusted_mode_allows_header_identity_without_api_key():- """Trusted mode should accept explicit tenant headers without API key."""- request = _make_request(- "/api/v1/resources",- headers={- "X-OpenViking-Account": "acme",- "X-OpenViking-User": "alice",- },- auth_enabled=False,- auth_mode="trusted",- )-- identity = await resolve_identity(- request,- x_openviking_account="acme",- x_openviking_user="alice",- )-- assert identity.role == Role.USER- assert identity.account_id == "acme"- assert identity.user_id == "alice"--async def test_trusted_mode_defaults_role_to_user():"""Trusted mode should default requests to USER when no explicit role header is sent."""request = _make_request(@@ -946,10 +925,12 @@ async def test_trusted_mode_defaults_role_to_user():},auth_enabled=False,auth_mode="trusted",+ root_api_key=ROOT_KEY,)identity = await resolve_identity(request,+ x_api_key=ROOT_KEY,x_openviking_account="acme",x_openviking_user="alice",)@@ -972,11 +953,13 @@ async def test_trusted_mode_looks_up_role_from_api_key_manager(auth_app):},auth_enabled=True,auth_mode="trusted",+ root_api_key=ROOT_KEY,api_key_manager=manager,)identity = await resolve_identity(request,+ x_api_key=ROOT_KEY,x_openviking_account=account_id,x_openviking_user="admin_user",)@@ -994,11 +977,13 @@ async def test_trusted_mode_looks_up_role_from_api_key_manager(auth_app):},auth_enabled=True,auth_mode="trusted",+ root_api_key=ROOT_KEY,api_key_manager=manager,)identity = await resolve_identity(request,+ x_api_key=ROOT_KEY,x_openviking_account=account_id,x_openviking_user="regular_user",)@@ -1022,11 +1007,13 @@ async def test_trusted_mode_defaults_to_user_when_user_not_found(auth_app):},auth_enabled=True,auth_mode="trusted",+ root_api_key=ROOT_KEY,api_key_manager=manager,)identity = await resolve_identity(request,+ x_api_key=ROOT_KEY,x_openviking_account=account_id,x_openviking_user="nonexistent_user",)@@ -1049,11 +1036,13 @@ async def test_trusted_mode_defaults_to_user_when_account_not_found(auth_app):},auth_enabled=False,auth_mode="trusted",+ root_api_key=ROOT_KEY,api_key_manager=manager,)identity = await resolve_identity(request,+ x_api_key=ROOT_KEY,x_openviking_account=account_id,x_openviking_user="some_user",)@@ -1069,6 +1058,7 @@ async def test_trusted_identity_registration_batches_data_plane_identity(auth_seconfig = ServerConfig(auth_mode="trusted",+ root_api_key=ROOT_KEY,trusted_identity_flush_interval_seconds=300,)app = FastAPI()@@ -1084,12 +1074,14 @@ async def test_trusted_identity_registration_batches_data_plane_identity(auth_se},auth_enabled=False,auth_mode="trusted",+ root_api_key=ROOT_KEY,)request.app.state.config = configrequest.app.state.api_key_manager = app.state.api_key_manageridentity = await plugin.resolve_identity(request,+ api_key=ROOT_KEY,x_openviking_account="acme",x_openviking_user="alice",)@@ -1114,6 +1106,7 @@ async def test_invalid_trusted_identity_does_not_block_later_registration(config = ServerConfig(auth_mode="trusted",+ root_api_key=ROOT_KEY,trusted_identity_flush_interval_seconds=300,)app = FastAPI()@@ -1129,12 +1122,14 @@ async def test_invalid_trusted_identity_does_not_block_later_registration(},auth_enabled=False,auth_mode="trusted",+ root_api_key=ROOT_KEY,)request.app.state.config = configwith pytest.raises(InvalidArgumentError, match="user_id"):await plugin.resolve_identity(request,+ api_key=ROOT_KEY,x_openviking_account="acme",x_openviking_user="invalid/user",)@@ -1149,10 +1144,12 @@ async def test_invalid_trusted_identity_does_not_block_later_registration(},auth_enabled=False,auth_mode="trusted",+ root_api_key=ROOT_KEY,)valid_request.app.state.config = configawait plugin.resolve_identity(valid_request,+ api_key=ROOT_KEY,x_openviking_account="good-account",x_openviking_user="alice",)@@ -1167,7 +1164,7 @@ async def test_trusted_identity_registration_skips_identity_loaded_from_registry"""A restarted plugin must not queue an identity already loaded from storage."""from openviking.server.auth.plugins import TrustedAuthPlugin- config = ServerConfig(auth_mode="trusted")+ config = ServerConfig(auth_mode="trusted", root_api_key=ROOT_KEY)app = FastAPI()app.state.config = configfirst_plugin = TrustedAuthPlugin()@@ -1190,11 +1187,12 @@ async def test_trusted_identity_registration_skips_identity_loaded_from_registry},auth_enabled=False,auth_mode="trusted",+ root_api_key=ROOT_KEY,)request.app.state.config = configawait restarted_plugin.resolve_identity(- request, x_openviking_account="acme", x_openviking_user="alice"+ request, api_key=ROOT_KEY, x_openviking_account="acme", x_openviking_user="alice")assert restarted_plugin._pending == {}@@ -1202,55 +1200,13 @@ async def test_trusted_identity_registration_skips_identity_loaded_from_registryawait restarted_plugin.shutdown()-async def test_trusted_identity_registration_keeps_rootless_admin_api_disabled(auth_service):- """A private registry manager must not enable Admin APIs in rootless trusted mode."""- from openviking.server.auth import require_auth_root- from openviking.server.auth.plugins import TrustedAuthPlugin-- config = ServerConfig(auth_mode="trusted")- app = _build_auth_http_test_app(- identity=None, auth_enabled=False, auth_mode="trusted"- )- app.state.config = config-- @app.get("/api/v1/admin/guarded")- @require_auth_root- async def guarded_admin(request: FastAPIRequest, ctx=Depends(get_request_context)):- return {"status": "ok"}-- plugin = TrustedAuthPlugin()- await plugin.initialize(app, auth_service, config)- try:- assert app.state.api_key_manager is None- transport = httpx.ASGITransport(app=app)- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:- admin_response = await client.get("/api/v1/admin/guarded")- assert admin_response.status_code == 403-- request = _make_request(- "/api/v1/resources",- headers={- "X-OpenViking-Account": "acme",- "X-OpenViking-User": "alice",- },- auth_enabled=False,- auth_mode="trusted",- )- request.app.state.config = config- await plugin.resolve_identity(- request, x_openviking_account="acme", x_openviking_user="alice"- )- await plugin.flush_trusted_identities()- assert plugin._api_key_manager.has_user("acme", "alice")- finally:- await plugin.shutdown()--async def test_disabled_trusted_identity_registration_and_admin_paths_do_not_enqueue(auth_service):"""A zero interval disables registration, and Admin paths never register."""from openviking.server.auth.plugins import TrustedAuthPlugin- config = ServerConfig(auth_mode="trusted", trusted_identity_flush_interval_seconds=0)+ config = ServerConfig(+ auth_mode="trusted", root_api_key=ROOT_KEY, trusted_identity_flush_interval_seconds=0+ )app = FastAPI()app.state.config = configplugin = TrustedAuthPlugin()@@ -1263,12 +1219,17 @@ async def test_disabled_trusted_identity_registration_and_admin_paths_do_not_enq"X-OpenViking-User": "alice",}request = _make_request(- path, headers=headers, auth_enabled=False, auth_mode="trusted"+ path,+ headers=headers,+ auth_enabled=False,+ auth_mode="trusted",+ root_api_key=ROOT_KEY,)request.app.state.config = configrequest.app.state.api_key_manager = app.state.api_key_managerawait plugin.resolve_identity(request,+ api_key=ROOT_KEY,x_openviking_account="acme",x_openviking_user="alice",)@@ -1283,7 +1244,7 @@ async def test_trusted_identity_registration_excludes_admin_paths(auth_service):"""Enabled registration must still exclude Admin requests."""from openviking.server.auth.plugins import TrustedAuthPlugin- config = ServerConfig(auth_mode="trusted")+ config = ServerConfig(auth_mode="trusted", root_api_key=ROOT_KEY)app = FastAPI()app.state.config = configplugin = TrustedAuthPlugin()@@ -1297,12 +1258,14 @@ async def test_trusted_identity_registration_excludes_admin_paths(auth_service):},auth_enabled=False,auth_mode="trusted",+ root_api_key=ROOT_KEY,)request.app.state.config = configrequest.app.state.api_key_manager = app.state.api_key_managerawait plugin.resolve_identity(request,+ api_key=ROOT_KEY,x_openviking_account="acme",x_openviking_user="alice",)@@ -1320,6 +1283,7 @@ async def test_trusted_identity_registration_retries_failed_batch_without_exceedconfig = ServerConfig(auth_mode="trusted",+ root_api_key=ROOT_KEY,trusted_identity_pending_max_size=2,)app = FastAPI()@@ -1462,37 +1426,19 @@ async def test_trusted_mode_rejects_root_role_header():)-async def test_trusted_mode_rejects_role_header_without_root_key():- """Role assertions require a configured root key so localhost trusted mode cannot self-elevate."""- request = _make_request(- "/api/v1/resources",- headers={- "X-OpenViking-Account": "acme",- "X-OpenViking-User": "alice",- "X-OpenViking-Role": "admin",- },- auth_enabled=False,- auth_mode="trusted",- )-- with pytest.raises(InvalidArgumentError, match="X-OpenViking-Role"):- await resolve_identity(- request,- x_openviking_account="acme",- x_openviking_user="alice",- )--async def test_trusted_mode_tenant_http_routes_require_explicit_identity_headers():"""Trusted mode should reject tenant-scoped routes without account/user headers."""app = _build_auth_http_test_app(identity=None,auth_enabled=False,auth_mode="trusted",+ root_api_key=ROOT_KEY,)transport = httpx.ASGITransport(app=app)- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ async with httpx.AsyncClient(+ transport=transport, headers={"X-API-Key": ROOT_KEY}, base_url="http://testserver"+ ) as client:response = await client.get("/api/v1/fs/ls")assert response.status_code == 400@@ -1505,10 +1451,13 @@ async def test_trusted_mode_tenant_http_routes_accept_explicit_identity_headers(identity=None,auth_enabled=False,auth_mode="trusted",+ root_api_key=ROOT_KEY,)transport = httpx.ASGITransport(app=app)- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ async with httpx.AsyncClient(+ transport=transport, headers={"X-API-Key": ROOT_KEY}, base_url="http://testserver"+ ) as client:response = await client.get("/api/v1/fs/ls",headers={@@ -1527,10 +1476,13 @@ async def test_trusted_mode_http_routes_accept_explicit_identity_from_url():identity=None,auth_enabled=False,auth_mode="trusted",+ root_api_key=ROOT_KEY,)transport = httpx.ASGITransport(app=app)- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ async with httpx.AsyncClient(+ transport=transport, headers={"X-API-Key": ROOT_KEY}, base_url="http://testserver"+ ) as client:response = await client.get("/api/v1/test/accounts/acme/users/alice")assert response.status_code == 200@@ -1548,10 +1500,13 @@ async def test_trusted_mode_rejects_conflicting_header_and_url_identity():identity=None,auth_enabled=False,auth_mode="trusted",+ root_api_key=ROOT_KEY,)transport = httpx.ASGITransport(app=app)- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ async with httpx.AsyncClient(+ transport=transport, headers={"X-API-Key": ROOT_KEY}, base_url="http://testserver"+ ) as client:response = await client.get("/api/v1/test/accounts/acme/users/alice",headers={"X-OpenViking-Account": "other-acct"},@@ -1561,51 +1516,26 @@ async def test_trusted_mode_rejects_conflicting_header_and_url_identity():assert response.json()["error"]["code"] == "INVALID_ARGUMENT"-async def test_trusted_mode_http_routes_require_api_key_when_root_key_configured():- """Trusted mode HTTP routes should require the configured server API key when present."""[email protected]("api_key", [None, "wrong-key", ROOT_KEY])[email protected]("path", ["/api/v1/fs/ls", "/api/v1/test/accounts/acme/users/alice"])+async def test_trusted_mode_http_routes_require_matching_root_key(api_key, path):app = _build_auth_http_test_app(- identity=None,- auth_enabled=False,- auth_mode="trusted",- root_api_key=ROOT_KEY,+ identity=None, auth_enabled=False, auth_mode="trusted", root_api_key=ROOT_KEY)- transport = httpx.ASGITransport(app=app)-- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:- response = await client.get(- "/api/v1/fs/ls",- headers={- "X-OpenViking-Account": "acme",- "X-OpenViking-User": "alice",- },- )-- assert response.status_code == 401- assert response.json()["error"]["code"] == "UNAUTHENTICATED"---async def test_trusted_mode_http_routes_accept_api_key_when_root_key_configured():- """Trusted mode HTTP routes should accept the configured server API key plus explicit identity headers."""- app = _build_auth_http_test_app(- identity=None,- auth_enabled=False,- auth_mode="trusted",- root_api_key=ROOT_KEY,- )- transport = httpx.ASGITransport(app=app)-- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:- response = await client.get(- "/api/v1/fs/ls",- headers={- "X-API-Key": ROOT_KEY,- "X-OpenViking-Account": "acme",- "X-OpenViking-User": "alice",- },- )-- assert response.status_code == 200- assert response.json()["result"] == {"account_id": "acme", "user_id": "alice"}+ headers = {"X-OpenViking-Account": "acme", "X-OpenViking-User": "alice"}+ if api_key is not None:+ headers["X-API-Key"] = api_key+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url="http://testserver"+ ) as client:+ response = await client.get(path, headers=headers)+ if api_key == ROOT_KEY:+ assert response.status_code == 200+ assert response.json()["result"]["account_id"] == "acme"+ assert response.json()["result"]["user_id"] == "alice"+ else:+ assert response.status_code == 401+ assert response.json()["error"]["code"] == "UNAUTHENTICATED"# ---- _is_localhost tests ----@@ -1645,18 +1575,19 @@ def test_validate_with_key_any_host_passes():validate_server_config(config) # should not raise-def test_validate_trusted_mode_without_key_localhost_passes():- """Trusted mode without root_api_key should still be allowed on localhost only."""- for host in ("127.0.0.1", "localhost", "::1"):- config = ServerConfig(host=host, root_api_key=None, auth_mode="trusted")- validate_server_config(config)[email protected]("host", ["127.0.0.1", "localhost", "::1", "0.0.0.0"])[email protected]("root_key", [None, "", " ", ROOT_KEY])+async def test_validate_trusted_mode_requires_root_key_on_every_host(host, root_key):+ from openviking.server.auth.health_check import HealthStatus, TrustedAuthChecker--def test_validate_trusted_mode_without_key_non_localhost_raises():- """Trusted mode without root_api_key should be rejected off localhost."""- config = ServerConfig(host="0.0.0.0", root_api_key=None, auth_mode="trusted")- with pytest.raises(SystemExit):+ config = ServerConfig(host=host, root_api_key=root_key, auth_mode="trusted")+ (check,) = await TrustedAuthChecker().run_checks(config)+ assert check.status == (HealthStatus.PASS if root_key == ROOT_KEY else HealthStatus.FAIL)+ if root_key == ROOT_KEY:validate_server_config(config)+ else:+ with pytest.raises(SystemExit):+ validate_server_config(config)async def test_trusted_mode_admin_api_without_identity_defaults_to_root():@@ -1666,32 +1597,16 @@ async def test_trusted_mode_admin_api_without_identity_defaults_to_root():headers={},auth_enabled=False,auth_mode="trusted",+ root_api_key=ROOT_KEY,)- identity = await resolve_identity(request)+ identity = await resolve_identity(request, x_api_key=ROOT_KEY)assert identity.role == Role.ROOTassert identity.account_id == "trusted"assert identity.user_id == "trusted"-async def test_trusted_mode_admin_api_with_partial_identity_still_requires_full_identity():- """Trusted mode admin APIs with partial identity should still require full identity."""- # Only account, no user- request = _make_request(- "/api/v1/admin/accounts",- headers={"X-OpenViking-Account": "acme"},- auth_enabled=False,- auth_mode="trusted",- )-- with pytest.raises(InvalidArgumentError, match="Trusted mode requests must include"):- await resolve_identity(- request,- x_openviking_account="acme",- )--async def test_trusted_mode_root_key_can_target_account_without_caller_identity():"""A verified Root key should not treat a target account as partial caller identity."""request = _make_request(@@ -1716,6 +1631,7 @@ async def test_trusted_mode_get_request_context_exempts_admin_paths():"/api/v1/admin/accounts",auth_enabled=False,auth_mode="trusted",+ root_api_key=ROOT_KEY,)identity = ResolvedIdentity(role=Role.ROOT,@@ -1734,6 +1650,7 @@ async def test_trusted_mode_get_request_context_exempts_admin_paths():"/api/v1/fs/ls",auth_enabled=False,auth_mode="trusted",+ root_api_key=ROOT_KEY,)incomplete_identity = ResolvedIdentity(role=Role.ROOT,@@ -1751,6 +1668,7 @@ async def test_trusted_mode_admin_api_http_route_without_identity():identity=None,auth_enabled=False,auth_mode="trusted",+ root_api_key=ROOT_KEY,)# Add an admin route to the test app@@ -1767,7 +1685,9 @@ async def test_trusted_mode_admin_api_http_route_without_identity():transport = httpx.ASGITransport(app=app)- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ async with httpx.AsyncClient(+ transport=transport, headers={"X-API-Key": ROOT_KEY}, base_url="http://testserver"+ ) as client:response = await client.get("/api/v1/admin/accounts")assert response.status_code == 200diff --git a/tests/server/test_bot_proxy_auth.py b/tests/server/test_bot_proxy_auth.pyindex b32608fca..7e909871c 100644--- a/tests/server/test_bot_proxy_auth.py+++ b/tests/server/test_bot_proxy_auth.py@@ -136,7 +136,9 @@ async def test_chat_proxy_attaches_authenticated_openviking_connection(monkeypatmonkeypatch.setattr(bot_router_module, "_create_bot_proxy_client", lambda: FakeClient())app = FastAPI()- app.state.config = ServerConfig(auth_mode="trusted", host="127.0.0.1", port=1944)+ app.state.config = ServerConfig(+ auth_mode="trusted", root_api_key="active-root-key", host="127.0.0.1", port=1944+ )app.state.auth_plugin = TrustedAuthPlugin()app.include_router(bot_router_module.router, prefix="/bot/v1")transport = httpx.ASGITransport(app=app)@@ -145,7 +147,7 @@ async def test_chat_proxy_attaches_authenticated_openviking_connection(monkeypatresponse = await client.post("/bot/v1/chat",headers={- "X-API-Key": "active-user-key",+ "X-API-Key": "active-root-key","X-OpenViking-Account": "acct","X-OpenViking-User": "alice",},@@ -155,7 +157,7 @@ async def test_chat_proxy_attaches_authenticated_openviking_connection(monkeypatassert response.status_code == 200assert forwarded["url"] == "http://127.0.0.1:18790/bot/v1/chat"assert forwarded["json"]["openviking_connection"] == {- "api_key": "active-user-key",+ "api_key": "active-root-key","account_id": "acct","user_id": "alice","agent_id": "web-playground",@@ -167,69 +169,6 @@ async def test_chat_proxy_attaches_authenticated_openviking_connection(monkeypatassert forwarded["timeout"] == 300.0-async def test_chat_proxy_forwards_trusted_request_without_root_api_key(monkeypatch):- forwarded = {}-- class FakeResponse:- status_code = 200- text = '{"session_id": "session-1", "message": "ok"}'-- def raise_for_status(self):- return None-- def json(self):- return {"session_id": "session-1", "message": "ok"}-- class FakeClient:- async def __aenter__(self):- return self-- async def __aexit__(self, exc_type, exc, tb):- return None-- async def post(self, url, json, headers, timeout):- forwarded["url"] = url- forwarded["json"] = json- forwarded["headers"] = headers- forwarded["timeout"] = timeout- return FakeResponse()-- monkeypatch.setattr(bot_router_module, "BOT_API_URL", "http://127.0.0.1:18790")- monkeypatch.setattr(bot_router_module, "BOT_API_KEY", "")- monkeypatch.setattr(bot_router_module, "_create_bot_proxy_client", lambda: FakeClient())-- app = FastAPI()- app.state.config = ServerConfig(auth_mode="trusted", host="127.0.0.1", port=1955)- app.state.auth_plugin = TrustedAuthPlugin()- app.include_router(bot_router_module.router, prefix="/bot/v1")- transport = httpx.ASGITransport(app=app)-- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:- response = await client.post(- "/bot/v1/chat",- headers={- "X-OpenViking-Account": "acct",- "X-OpenViking-User": "alice",- },- json={"message": "hello"},- )-- assert response.status_code == 200- assert forwarded["url"] == "http://127.0.0.1:18790/bot/v1/chat"- assert "api_key" not in forwarded["json"]["openviking_connection"]- assert forwarded["json"]["openviking_connection"] == {- "account_id": "acct",- "user_id": "alice",- "agent_id": "web-playground",- "role": "user",- "api_key_type": "root",- "server_url": "http://127.0.0.1:1955",- }- assert "X-Gateway-Token" not in forwarded["headers"]- assert forwarded["timeout"] == 300.0--@pytest.mark.asyncio@pytest.mark.parametrize("request_id", [None, "compile-request-123"])async def test_compile_route_uses_ov_owned_task_and_rejects_legacy_routes(monkeypatch, request_id):@@ -255,13 +194,15 @@ async def test_compile_route_uses_ov_owned_task_and_rejects_legacy_routes(monkeymonkeypatch.setattr(compile_router_module, "get_service", lambda: service)app = FastAPI()- app.state.config = ServerConfig(auth_mode="trusted", host="127.0.0.1", port=1944)+ app.state.config = ServerConfig(+ auth_mode="trusted", root_api_key="active-root-key", host="127.0.0.1", port=1944+ )app.state.auth_plugin = TrustedAuthPlugin()app.include_router(compile_router_module.router)app.include_router(bot_router_module.router, prefix="/bot/v1")transport = httpx.ASGITransport(app=app)headers = {- "X-API-Key": "active-user-key",+ "X-API-Key": "active-root-key","X-OpenViking-Account": "acct","X-OpenViking-User": "alice",}@@ -294,7 +235,7 @@ async def test_compile_route_uses_ov_owned_task_and_rejects_legacy_routes(monkeyassert legacy_cancel.status_code == 400assert "POST /api/v1/tasks/{task_id}/cancel" in legacy_cancel.json()["detail"]assert calls["connection"] == {- "api_key": "active-user-key",+ "api_key": "active-root-key","account_id": "acct","user_id": "alice",**({"request_id": request_id} if request_id else {}),diff --git a/tests/server/test_server_health.py b/tests/server/test_server_health.pyindex cf6c724c8..66ec8927f 100644--- a/tests/server/test_server_health.py+++ b/tests/server/test_server_health.py@@ -103,13 +103,12 @@ async def test_health_endpoint_without_api_key():assert "role" not in body[email protected]("root_key", [None, "test-root-key"])@pytest.mark.parametrize("credentials", ["anonymous", "partial", "trusted", "keyed", "malformed", "asserted-root"])-async def test_health_trusted_identity_contract(root_key, credentials, caplog, service):+async def test_health_trusted_identity_contract(credentials, caplog, service):app = create_app(- config=ServerConfig(auth_mode="trusted", host="127.0.0.1", root_api_key=root_key),+ config=ServerConfig(auth_mode="trusted", host="127.0.0.1", root_api_key="test-root-key"),service=service,)await _initialize_auth_plugin(app, service, app.state.config)@@ -129,16 +128,16 @@ async def test_health_trusted_identity_contract(root_key, credentials, caplog, s) as client:response = await client.get("/health", headers=headers)body = response.json()- expected_status = 401 if root_key and credentials in ("trusted", "malformed") else 200+ expected_status = 401 if credentials in ("trusted", "malformed") else 200assert response.status_code == expected_statusif expected_status == 401:assert body["error"]["code"] == "UNAUTHENTICATED"return- if credentials == "keyed" or (credentials == "trusted" and not root_key):+ if credentials == "keyed":assert (body["account_id"], body["user_id"], body["role"]) == ("account-a", "alice", "user")else:assert "role" not in body- assert body["root_api_key_required"] is bool(root_key)+ assert body["root_api_key_required"] is Trueif credentials in ("anonymous", "partial"):assert "Failed to resolve identity" not in caplog.textdiff --git a/web-studio/src/hooks/use-app-connection.bootstrap.test.tsx b/web-studio/src/hooks/use-app-connection.bootstrap.test.tsxindex 4dd63379b..22c649099 100644--- a/web-studio/src/hooks/use-app-connection.bootstrap.test.tsx+++ b/web-studio/src/hooks/use-app-connection.bootstrap.test.tsx@@ -15,73 +15,91 @@ vi.mock('@tanstack/react-router', () => ({afterEach(cleanup)function Identity() {- const { connectionRole, isConnectionRoleLoading } = useAppConnection()+ const { connectionRole, isConnectionRoleLoading, serverMode } =+ useAppConnection()return (<output data-testid="identity">- {isConnectionRoleLoading ? 'loading' : connectionRole}+ {serverMode}:{isConnectionRoleLoading ? 'loading' : connectionRole}</output>)}-it('resolves a keyless trusted user on cold startup through the health transport', async () => {- const observed: Array<[string | undefined, string | undefined]> = []- const server = createServer((req, res) => {- res.setHeader('Access-Control-Allow-Origin', '*')- res.setHeader(- 'Access-Control-Allow-Headers',- 'X-OpenViking-Account, X-OpenViking-User, X-API-Key',- )- if (req.method === 'OPTIONS') {- res.end()- return- }- const account = req.headers['x-openviking-account'] as string | undefined- const user = req.headers['x-openviking-user'] as string | undefined- observed.push([account, user])- res.setHeader('Content-Type', 'application/json')- res.end(+it.each(['', 'root-key'])(+ 'detects trusted mode on cold startup and resolves identity only with a key: %s',+ async (rootKey) => {+ const observed: Array<+ [string | undefined, string | undefined, string | undefined]+ > = []+ const server = createServer((req, res) => {+ res.setHeader('Access-Control-Allow-Origin', '*')+ res.setHeader(+ 'Access-Control-Allow-Headers',+ 'X-OpenViking-Account, X-OpenViking-User, X-API-Key',+ )+ if (req.method === 'OPTIONS') {+ res.end()+ return+ }+ const account = req.headers['x-openviking-account'] as string | undefined+ const user = req.headers['x-openviking-user'] as string | undefined+ const apiKey = req.headers['x-api-key'] as string | undefined+ observed.push([account, user, apiKey])+ res.setHeader('Content-Type', 'application/json')+ if (account && user && apiKey !== 'root-key') {+ res.statusCode = 401+ res.end(JSON.stringify({ error: { code: 'UNAUTHENTICATED' } }))+ return+ }+ res.end(+ JSON.stringify({+ status: 'ok',+ auth_mode: 'trusted',+ root_api_key_required: true,+ ...(account && user && apiKey === 'root-key'+ ? { account_id: account, user_id: user, role: 'user' }+ : {}),+ }),+ )+ })+ server.listen(0, '127.0.0.1')+ await once(server, 'listening')+ const address = server.address() as { port: number }+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ localStorage.setItem(+ 'ov_console_connection',JSON.stringify({- status: 'ok',- auth_mode: 'trusted',- root_api_key_required: false,- ...(account && user- ? { account_id: account, user_id: user, role: 'user' }- : {}),+ baseUrl: `http://127.0.0.1:${address.port}`,+ accountId: 'account-a',+ userId: 'alice',+ apiKey: '',+ adminApiKey: rootKey,}),)- })- server.listen(0, '127.0.0.1')- await once(server, 'listening')- const address = server.address() as { port: number }- const queryClient = new QueryClient({- defaultOptions: { queries: { retry: false } },- })- localStorage.setItem(- 'ov_console_connection',- JSON.stringify({- baseUrl: `http://127.0.0.1:${address.port}`,- accountId: 'account-a',- userId: 'alice',- apiKey: '',- adminApiKey: '',- }),- )- try {- render(- <QueryClientProvider client={queryClient}>- <AppConnectionProvider>- <Identity />- </AppConnectionProvider>- </QueryClientProvider>,- )- await waitFor(() =>- expect(screen.getByTestId('identity').textContent).toBe('user'),- )- expect(observed).toEqual([['account-a', 'alice']])- } finally {- cleanup()- queryClient.clear()- localStorage.removeItem('ov_console_connection')- await new Promise<void>((resolve) => server.close(() => resolve()))- }-})+ try {+ render(+ <QueryClientProvider client={queryClient}>+ <AppConnectionProvider>+ <Identity />+ </AppConnectionProvider>+ </QueryClientProvider>,+ )+ await waitFor(() =>+ expect(screen.getByTestId('identity').textContent).toBe(+ rootKey ? 'trusted:user' : 'trusted:unknown',+ ),+ )+ if (rootKey) {+ expect(observed).toContainEqual(['account-a', 'alice', rootKey])+ } else {+ expect(observed).toEqual([[undefined, undefined, undefined]])+ }+ } finally {+ cleanup()+ queryClient.clear()+ localStorage.removeItem('ov_console_connection')+ await new Promise<void>((resolve) => server.close(() => resolve()))+ }+ },+)diff --git a/web-studio/src/hooks/use-app-connection.test.ts b/web-studio/src/hooks/use-app-connection.test.tsindex f3687d4b7..8bcfa3281 100644--- a/web-studio/src/hooks/use-app-connection.test.ts+++ b/web-studio/src/hooks/use-app-connection.test.ts@@ -294,33 +294,39 @@ describe('resolveConnectionRoleProbeState', () => {})})- it('keeps non-dev no-key connections unknown without probing', () => {- expect(- resolveConnectionRoleProbeState({- apiKey: '',- baseUrl: 'http://localhost:3000',- serverMode: 'api_key',- }),- ).toEqual({- isLoading: false,- role: 'unknown',- shouldProbe: false,- })- })-- it('probes non-dev keyed connections through /health', () => {- expect(- resolveConnectionRoleProbeState({- apiKey: 'root-key',- baseUrl: 'http://localhost:3000',- serverMode: 'api_key',- }),- ).toEqual({- isLoading: true,- role: 'unknown',- shouldProbe: true,- })- })+ it.each(['api_key', 'trusted'] as const)(+ 'keeps non-dev no-key connections unknown without probing: %s',+ (serverMode) => {+ expect(+ resolveConnectionRoleProbeState({+ apiKey: '',+ baseUrl: 'http://localhost:3000',+ serverMode,+ }),+ ).toEqual({+ isLoading: false,+ role: 'unknown',+ shouldProbe: false,+ })+ },+ )++ it.each(['api_key', 'trusted'] as const)(+ 'probes non-dev keyed connections through /health: %s',+ (serverMode) => {+ expect(+ resolveConnectionRoleProbeState({+ apiKey: 'root-key',+ baseUrl: 'http://localhost:3000',+ serverMode,+ }),+ ).toEqual({+ isLoading: true,+ role: 'unknown',+ shouldProbe: true,+ })+ },+ )})describe('shouldRedirectToLoginOnApiError', () => {diff --git a/web-studio/src/hooks/use-app-connection.tsx b/web-studio/src/hooks/use-app-connection.tsxindex 4304d50c3..591b8caad 100644--- a/web-studio/src/hooks/use-app-connection.tsx+++ b/web-studio/src/hooks/use-app-connection.tsx@@ -225,17 +225,13 @@ export function resolveInitialApiKey({}export function resolveConnectionRoleProbeState({- accountId = '',apiKey,baseUrl,serverMode,- userId = '',}: {- accountId?: stringapiKey: stringbaseUrl: stringserverMode: ServerMode- userId?: string}): {isLoading: booleanrole: ConnectionRole@@ -250,9 +246,7 @@ export function resolveConnectionRoleProbeState({if (serverMode === 'dev') {return { isLoading: false, role: 'root', shouldProbe: false }}- const hasTrustedIdentity =- serverMode === 'trusted' && Boolean(accountId.trim() && userId.trim())- if (!apiKey && !hasTrustedIdentity) {+ if (!apiKey) {return { isLoading: false, role: 'unknown', shouldProbe: false }}return { isLoading: true, role: 'unknown', shouldProbe: true }@@ -316,9 +310,10 @@ function createConnectionHealthHeaders(credential === 'data'? connection.apiKey || connection.adminApiKey: connection.adminApiKey || connection.apiKey- if (apiKey) {- headers['X-API-Key'] = apiKey+ if (!apiKey) {+ return headers}+ headers['X-API-Key'] = apiKeyif (connection.accountId) {headers['X-OpenViking-Account'] = connection.accountId}@@ -572,11 +567,9 @@ export function AppConnectionProvider({const isCancelled = () => cancelledconst apiKey = connection.adminApiKey || connection.apiKeyconst roleProbe = resolveConnectionRoleProbeState({- accountId: connection.accountId,apiKey,baseUrl: connection.baseUrl,serverMode,- userId: connection.userId,})const probeKey = createConnectionRoleProbeKey(connection, serverMode)const synchronizedProbe = synchronizedRoleProbeRef.currentdiff --git a/web-studio/src/i18n/locales/en/workspace.ts b/web-studio/src/i18n/locales/en/workspace.tsindex 270fa01fb..aa5430b39 100644--- a/web-studio/src/i18n/locales/en/workspace.ts+++ b/web-studio/src/i18n/locales/en/workspace.ts@@ -1174,9 +1174,9 @@ const workspace = {learnMore: 'Learn how to get an API Key',trusted: {primary:- 'This trusted server enforces Root Key validation. The browser needs the same Root API Key for management and tenant data requests.',+ "Trusted mode requires a Root API Key, including on localhost. Enter the server's root key in the “Root or Admin API Key” field above.",secondary:- 'Request the Root Key from the deployment admin; it is stored at server.root_api_key in the server-side ov.conf. Trusted-mode data identity comes from Account/User assertions and does not need a User API Key.',+ 'Request the key from the deployment admin. If the server has no key yet, set a non-empty server.root_api_key in its ov.conf, restart the server, and enter the same value here. No separate User API Key is needed.',title: 'This trusted server requires a Root API Key',},},@@ -1188,6 +1188,10 @@ const workspace = {primary: 'This server is configured with {{mode}} authentication.',title: 'Unsupported authentication mode',},+ trustedRootHint:+ 'Use server.root_api_key from the server-side ov.conf for both management and data access in trusted mode.',+ trustedUserHint:+ 'Trusted mode needs no separate User API Key; Account and User identify whose data to access.',userHint: 'Used by the Filesystem and tenant data APIs.',},connectionPage: {@@ -1260,6 +1264,8 @@ const workspace = {dataKeyRequired: 'A user or account-admin API key is required',rootAvailable: 'Root admin control available',tenantDataAvailable: 'Tenant data access available',+ trustedKeyRequired:+ 'A Root API Key is required. Use server.root_api_key from the server-side ov.conf',trustedIdentityRequired:'Trusted mode data access requires account and user',},diff --git a/web-studio/src/i18n/locales/zh-CN/workspace.ts b/web-studio/src/i18n/locales/zh-CN/workspace.tsindex 5b1cd9508..e19f9d0fa 100644--- a/web-studio/src/i18n/locales/zh-CN/workspace.ts+++ b/web-studio/src/i18n/locales/zh-CN/workspace.ts@@ -1122,9 +1122,9 @@ const workspace = {learnMore: '查看 API 密钥获取方式',trusted: {primary:- '当前 Trusted 服务启用了 Root API 密钥校验。浏览器需要配置相同的密钥,才能访问管理接口和租户数据接口。',+ 'Trusted 模式必须使用 Root API 密钥,localhost 也不例外。请在上方“Root 或管理员 API 密钥”中填入服务端的 root key。',secondary:- '请向部署管理员索取 Root API 密钥;它位于服务端 ov.conf 的 server.root_api_key。Trusted 模式的数据身份由账号和用户断言确定,不需要用户 API 密钥。',+ '请向部署管理员索取密钥。如果服务端还没配置,请在服务端 ov.conf 中设置非空的 server.root_api_key,然后重启服务,并在这里填写同一个值。无需另外生成用户 API 密钥。',title: 'Trusted 服务需要 Root API 密钥',},},@@ -1136,6 +1136,10 @@ const workspace = {primary: '该服务器配置了 {{mode}} 认证。',title: '不支持的认证模式',},+ trustedRootHint:+ '填写服务端 ov.conf 中的 server.root_api_key;Trusted 模式的管理和数据访问都使用它。',+ trustedUserHint:+ 'Trusted 模式无需单独的用户 API 密钥,数据身份由账号和用户名决定。',userHint: '供文件系统和租户数据 API 使用。',},connectionPage: {@@ -1206,6 +1210,8 @@ const workspace = {dataKeyRequired: '需要用户或账号管理员 API 密钥',rootAvailable: 'Root 管理权限可用',tenantDataAvailable: '租户数据访问可用',+ trustedKeyRequired:+ '需要 Root API 密钥,请填写服务端 ov.conf 中的 server.root_api_key',trustedIdentityRequired: 'Trusted 模式的数据访问需要账号和用户信息',},state: {diff --git a/web-studio/src/lib/admin-probe.test.ts b/web-studio/src/lib/admin-probe.test.tsindex 84aaee97a..8e154db0e 100644--- a/web-studio/src/lib/admin-probe.test.ts+++ b/web-studio/src/lib/admin-probe.test.ts@@ -4,21 +4,17 @@ import { once } from 'node:events'import { probeStudioConnection } from './admin'describe('trusted connection probes', () => {- it.each([false, true, undefined])(- 'uses explicit Root key requirement metadata: %s',- async (required) => {- const requests: string[] = []+ it.each(['', 'root-key'])(+ 'requires a key for trusted data access and preserves server errors: %s',+ async (apiKey) => {+ const requests: Array<[string, string | undefined]> = []const server = createServer((req, res) => {- requests.push(req.url || '')+ requests.push([+ req.url || '',+ req.headers['x-api-key'] as string | undefined,+ ])res.setHeader('Content-Type', 'application/json')- if (req.url === '/health') {- res.end(- JSON.stringify({- auth_mode: 'trusted',- root_api_key_required: required,- }),- )- } else if (req.url?.startsWith('/api/v1/fs/ls')) {+ if (req.url?.startsWith('/api/v1/fs/ls')) {res.statusCode = 403res.end(JSON.stringify({@@ -46,22 +42,29 @@ describe('trusted connection probes', () => {serverMode: 'trusted',accountId: 'account-a',userId: 'alice',- apiKey: '',+ apiKey,adminApiKey: '',})- expect(result.rootApiKeyRequired).toBe(required)expect(result.admin).toMatchObject({state: 'skipped',- detailCode: 'controlKeyRequired',+ detailCode: 'trustedKeyRequired',})- expect(result.data).toMatchObject({- state: 'error',- statusCode: 403,- errorCode: 'PERMISSION_DENIED',- })- expect(requests.some((path) => path.startsWith('/api/v1/admin'))).toBe(- false,- )+ if (apiKey) {+ expect(result.data).toMatchObject({+ state: 'error',+ statusCode: 403,+ errorCode: 'PERMISSION_DENIED',+ })+ expect(requests).toEqual([+ [expect.stringContaining('/api/v1/fs/ls'), apiKey],+ ])+ } else {+ expect(result.data).toMatchObject({+ state: 'skipped',+ detailCode: 'trustedKeyRequired',+ })+ expect(requests).toEqual([])+ }} finally {await new Promise<void>((resolve) => server.close(() => resolve()))}diff --git a/web-studio/src/lib/admin.ts b/web-studio/src/lib/admin.tsindex 280eb0e7f..cc508e5bb 100644--- a/web-studio/src/lib/admin.ts+++ b/web-studio/src/lib/admin.ts@@ -1,5 +1,4 @@import axios from 'axios'-import { fetchServerHealth } from '#/hooks/use-server-mode'import { createClient } from '#/gen/ov-client/client'import {@@ -72,6 +71,7 @@ export type CapabilityDetailCode =| 'rootAvailable'| 'tenantDataAvailable'| 'trustedIdentityRequired'+ | 'trustedKeyRequired'export type CapabilityProbeResult = {detail?: string@@ -84,7 +84,6 @@ export type CapabilityProbeResult = {export type StudioConnectionProbe = {admin: CapabilityProbeResultdata: CapabilityProbeResult- rootApiKeyRequired?: boolean}export type ProbeConnectionInput = {@@ -204,7 +203,10 @@ async function probeAdminAccess(const controlKey = input.adminApiKey.trim()if (!controlKey) {return {- detailCode: 'controlKeyRequired',+ detailCode:+ input.serverMode === 'trusted'+ ? 'trustedKeyRequired'+ : 'controlKeyRequired',state: 'skipped',}}@@ -252,9 +254,14 @@ async function probeDataAccess(if (input.serverMode === 'checking' || input.serverMode === 'offline') {return { state: 'skipped' }}- if (input.serverMode === 'api_key' && !input.apiKey) {+ const apiKey =+ input.apiKey || (input.serverMode === 'trusted' ? input.adminApiKey : '')+ if (input.serverMode !== 'dev' && !apiKey) {return {- detailCode: 'dataKeyRequired',+ detailCode:+ input.serverMode === 'trusted'+ ? 'trustedKeyRequired'+ : 'dataKeyRequired',state: 'skipped',}}@@ -270,10 +277,7 @@ async function probeDataAccess(const client = createProbeClient(input.baseUrl)const headers: Record<string, string> = {}- setApiKeyHeader(- headers,- input.apiKey || (input.serverMode === 'trusted' ? input.adminApiKey : ''),- )+ setApiKeyHeader(headers, apiKey)if (input.serverMode === 'trusted') {setOptionalHeader(headers, 'X-OpenViking-Account', input.accountId)@@ -301,29 +305,11 @@ async function probeDataAccess(export async function probeStudioConnection(input: ProbeConnectionInput,): Promise<StudioConnectionProbe> {- const headers: Record<string, string> = {}- setApiKeyHeader(headers, input.adminApiKey || input.apiKey)- setOptionalHeader(headers, 'X-OpenViking-Account', input.accountId)- setOptionalHeader(headers, 'X-OpenViking-User', input.userId)- const [admin, data, health] = await Promise.all([+ const [admin, data] = await Promise.all([probeAdminAccess(input),probeDataAccess(input),- Promise.allSettled(- input.serverMode === 'trusted'- ? [fetchServerHealth(input.baseUrl, headers)]- : [],- ),])- const metadata =- health[0]?.status === 'fulfilled' ? health[0].value : undefined- return {- admin,- data,- rootApiKeyRequired:- typeof metadata?.root_api_key_required === 'boolean'- ? metadata.root_api_key_required- : undefined,- }+ return { admin, data }}function normalizeAccount(value: unknown): AdminAccount | null {diff --git a/web-studio/src/routes/settings/-lib/localize-capability-probe.test.ts b/web-studio/src/routes/settings/-lib/localize-capability-probe.test.tsindex f3be37913..d0b8b2c07 100644--- a/web-studio/src/routes/settings/-lib/localize-capability-probe.test.ts+++ b/web-studio/src/routes/settings/-lib/localize-capability-probe.test.ts@@ -12,6 +12,7 @@ const translations: Record<string, string> = {'health.detail.rootAvailable': 'Root 管理权限可用','health.detail.tenantDataAvailable': '租户数据访问可用','health.detail.trustedIdentityRequired': '需要账号和用户信息',+ 'health.detail.trustedKeyRequired': '需要 Root API 密钥,请配置 server.root_api_key',}const t = ((key: string) => translations[key] ?? key) as TFunction<'settings'>diff --git a/web-studio/src/routes/settings/-lib/localize-capability-probe.ts b/web-studio/src/routes/settings/-lib/localize-capability-probe.tsindex 90f59de5e..2d6868f67 100644--- a/web-studio/src/routes/settings/-lib/localize-capability-probe.ts+++ b/web-studio/src/routes/settings/-lib/localize-capability-probe.ts@@ -12,6 +12,7 @@ const detailKeys = {rootAvailable: 'health.detail.rootAvailable',tenantDataAvailable: 'health.detail.tenantDataAvailable',trustedIdentityRequired: 'health.detail.trustedIdentityRequired',+ trustedKeyRequired: 'health.detail.trustedKeyRequired',} as const satisfies Record<CapabilityDetailCode, string>export function localizeCapabilityDetail(diff --git a/web-studio/src/routes/settings/route.test.tsx b/web-studio/src/routes/settings/route.test.tsxindex 895fbe4ec..ff6efe3a4 100644--- a/web-studio/src/routes/settings/route.test.tsx+++ b/web-studio/src/routes/settings/route.test.tsx@@ -29,37 +29,33 @@ vi.mock('react-i18next', () => ({}))afterEach(cleanup)-it.each([false, undefined, true])(- 'bases the Root key guide on server metadata: %s',- async (required) => {- probe.mockResolvedValue({- admin: {- state: 'error',- statusCode: 403,- detail: 'Management unavailable',- },- data: { state: 'ok', detailCode: 'tenantDataAvailable' },- rootApiKeyRequired: required,- })- const client = new QueryClient({- defaultOptions: { queries: { retry: false } },- })- const Settings = Route.options.component as ComponentType & {- preload?: () => Promise<unknown>- }- await Settings.preload?.()- render(- <QueryClientProvider client={client}>- <Settings />- </QueryClientProvider>,- )- await waitFor(- () => expect(screen.getByText('Management unavailable')).toBeTruthy(),- { timeout: 5000 },- )- expect(- Boolean(screen.queryByText('connection.keyGuide.trusted.title')),- ).toBe(required === true)- client.clear()- },-)+it('shows the Root key guide for trusted mode even when a capability probe fails', async () => {+ probe.mockResolvedValue({+ admin: {+ state: 'error',+ statusCode: 403,+ detail: 'Management unavailable',+ },+ data: { state: 'ok', detailCode: 'tenantDataAvailable' },+ })+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ const Settings = Route.options.component as ComponentType & {+ preload?: () => Promise<unknown>+ }+ await Settings.preload?.()+ render(+ <QueryClientProvider client={client}>+ <Settings />+ </QueryClientProvider>,+ )+ await waitFor(+ () => expect(screen.getByText('Management unavailable')).toBeTruthy(),+ { timeout: 5000 },+ )+ expect(Boolean(screen.queryByText('connection.keyGuide.trusted.title'))).toBe(+ true,+ )+ client.clear()+})diff --git a/web-studio/src/routes/settings/route.tsx b/web-studio/src/routes/settings/route.tsxindex 2434f77ef..b61cda17d 100644--- a/web-studio/src/routes/settings/route.tsx+++ b/web-studio/src/routes/settings/route.tsx@@ -232,10 +232,7 @@ function ConnectionSettingsPanel() {? 'https://docs.openviking.ai/zh/guides/04-authentication': 'https://docs.openviking.ai/en/guides/04-authentication'const trustedCredentialRequired =- serverMode === 'trusted' &&- !probeQuery.isFetching &&- !hasControlCredential &&- probeQuery.data?.rootApiKeyRequired === true+ serverMode === 'trusted' && !probeQuery.isFetching && !hasControlCredentialconst keyGuide =serverMode === 'trusted'? trustedCredentialRequired@@ -352,7 +349,11 @@ function ConnectionSettingsPanel() {{...PLAIN_INPUT_PROPS}/><FieldDescription>- {t('connection.rootHint')}+ {t(+ serverMode === 'trusted'+ ? 'connection.trustedRootHint'+ : 'connection.rootHint',+ )}</FieldDescription></FieldContent></Field>@@ -370,7 +371,11 @@ function ConnectionSettingsPanel() {placeholder={t('placeholders.userApiKey')}/><FieldDescription>- {t('connection.userHint')}+ {t(+ serverMode === 'trusted'+ ? 'connection.trustedUserHint'+ : 'connection.userHint',+ )}</FieldDescription></FieldContent></Field>