Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(studio): resolve keyless trusted connection identity (#5219)

Xinmin Zengcf9c40db1f8b
diff --git a/docs/en/api/07-system.md b/docs/en/api/07-system.md
index 8338c6a7d..894ce920e 100644
--- a/docs/en/api/07-system.md
+++ b/docs/en/api/07-system.md
@@ -10,6 +10,13 @@ The OpenViking System API provides health, readiness, consistency, and multi-wri
Basic health check endpoint. No authentication required. Returns service version and health status. If authentication is provided, also returns auth mode and identity information.
+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.
+
**Code Entry Points**:
- `openviking/server/routers/system.py:health_check` - HTTP route
- `openviking_cli/client/sync_http.py:SyncHTTPClient.health` - SDK entry
diff --git a/docs/zh/api/07-system.md b/docs/zh/api/07-system.md
index 32a8f7114..4d625a061 100644
--- a/docs/zh/api/07-system.md
+++ b/docs/zh/api/07-system.md
@@ -10,6 +10,11 @@ OpenViking 系统 API 提供健康检查、就绪检查、一致性检查和多
基础健康检查端点,无需认证。返回服务版本号和健康状态。如果提供认证信息,还会返回认证模式和身份信息。
+Trusted 模式下,完整的 `X-OpenViking-Account` 和 `X-OpenViking-User` 请求头会触发身份解析,
+包括省略 `root_api_key` 的 localhost 部署。配置了 Root 密钥的服务继续校验认证请求中的密钥。
+可选布尔字段 `root_api_key_required` 表示 Trusted 服务配置的密钥要求,解析得到的 `role`
+表示调用者权限。较早版本可能省略该字段。匿名健康探测返回基础存活信息。
+
**代码入口**:
- `openviking/server/routers/system.py:health_check` - HTTP 路由
- `openviking_cli/client/sync_http.py:SyncHTTPClient.health` - SDK 入口
diff --git a/openviking/server/routers/system.py b/openviking/server/routers/system.py
index 3800ac764..8bc19c8d0 100644
--- a/openviking/server/routers/system.py
+++ b/openviking/server/routers/system.py
@@ -12,7 +12,7 @@ from pydantic import BaseModel
from openviking.core.path_variables import resolve_path_variables
from openviking.core.uri_validation import validate_request_viking_uri
from openviking.pyagfs.exceptions import AGFSInvalidOperationError, AGFSNotSupportedError
-from openviking.server.auth import get_request_context, require_role
+from openviking.server.auth import _configured_root_api_key, get_request_context, require_role
from openviking.server.dependencies import get_service
from openviking.server.identity import AuthMode, RequestContext, Role
from openviking.server.models import Response
@@ -80,12 +80,16 @@ async def health_check(request: Request):
if config is not None and hasattr(config, "get_effective_auth_mode"):
effective_auth_mode = config.get_effective_auth_mode()
result["auth_mode"] = effective_auth_mode
+ if effective_auth_mode == AuthMode.TRUSTED.value:
+ result["root_api_key_required"] = bool(_configured_root_api_key(request))
- # Resolve identity when API key is provided
x_api_key = request.headers.get("X-API-Key")
authorization = request.headers.get("Authorization")
+ account = request.headers.get("X-OpenViking-Account")
+ user = request.headers.get("X-OpenViking-User")
+ trusted_identity = effective_auth_mode == AuthMode.TRUSTED.value and account and user
- if x_api_key or authorization:
+ if x_api_key or authorization or trusted_identity:
try:
from openviking.server.auth import resolve_identity
@@ -93,8 +97,8 @@ async def health_check(request: Request):
request,
x_api_key=x_api_key,
authorization=authorization,
- x_openviking_account=request.headers.get("X-OpenViking-Account"),
- x_openviking_user=request.headers.get("X-OpenViking-User"),
+ x_openviking_account=account,
+ x_openviking_user=user,
)
result["account_id"] = str(identity.account_id)
result["user_id"] = str(identity.user_id)
diff --git a/tests/server/test_server_health.py b/tests/server/test_server_health.py
index 1a41644f5..003133cb5 100644
--- a/tests/server/test_server_health.py
+++ b/tests/server/test_server_health.py
@@ -8,8 +8,9 @@ import time
from types import SimpleNamespace
import httpx
+import pytest
-from openviking.server.app import _initialize_runtime_state, create_app
+from openviking.server.app import _initialize_auth_plugin, _initialize_runtime_state, create_app
from openviking.server.config import ServerConfig
@@ -20,7 +21,7 @@ async def test_health_endpoint(client: httpx.AsyncClient):
assert body["status"] == "ok"
-async def test_health_endpoint_resolves_identity_with_api_key(caplog):
+async def test_health_endpoint_resolves_identity_with_api_key(caplog, service):
"""When an API key is provided, /health should return identity information."""
app = create_app(
config=ServerConfig(
@@ -28,8 +29,9 @@ async def test_health_endpoint_resolves_identity_with_api_key(caplog):
host="127.0.0.1",
root_api_key="test-root-key",
),
- service=SimpleNamespace(),
+ service=service,
)
+ await _initialize_auth_plugin(app, service, app.state.config)
transport = httpx.ASGITransport(app=app)
with caplog.at_level("WARNING", logger="openviking.server.routers.system"):
@@ -70,6 +72,42 @@ async def test_health_endpoint_without_api_key():
assert "role" not in body
[email protected]("root_key", [None, "test-root-key"])
+ "credentials", ["anonymous", "partial", "trusted", "keyed", "malformed", "asserted-root"]
+)
+async def test_health_trusted_identity_contract(root_key, credentials, caplog, service):
+ app = create_app(
+ config=ServerConfig(auth_mode="trusted", host="127.0.0.1", root_api_key=root_key),
+ service=service,
+ )
+ await _initialize_auth_plugin(app, service, app.state.config)
+ headers = {}
+ if credentials != "anonymous":
+ headers["X-OpenViking-Account"] = "account-a"
+ if credentials in ("trusted", "keyed", "malformed", "asserted-root"):
+ headers["X-OpenViking-User"] = "alice"
+ if credentials in ("keyed", "asserted-root"):
+ headers["X-API-Key"] = "test-root-key"
+ if credentials == "malformed":
+ headers["X-OpenViking-User"] = "alice/../root"
+ if credentials == "asserted-root":
+ headers["X-OpenViking-Role"] = "root"
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ response = await client.get("/health", headers=headers)
+ body = response.json()
+ assert response.status_code == 200
+ if credentials == "keyed" or (credentials == "trusted" and not root_key):
+ 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)
+ if credentials in ("anonymous", "partial"):
+ assert "Failed to resolve identity" not in caplog.text
+
+
async def test_system_status(client: httpx.AsyncClient):
resp = await client.get("/api/v1/system/status")
assert resp.status_code == 200
diff --git a/web-studio/src/hooks/use-app-connection.bootstrap.test.tsx b/web-studio/src/hooks/use-app-connection.bootstrap.test.tsx
new file mode 100644
index 000000000..4dd63379b
--- /dev/null
+++ b/web-studio/src/hooks/use-app-connection.bootstrap.test.tsx
@@ -0,0 +1,87 @@
+// @vitest-environment jsdom
+import { createServer } from 'node:http'
+import { once } from 'node:events'
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { afterEach, expect, it, vi } from 'vitest'
+
+import { AppConnectionProvider, useAppConnection } from './use-app-connection'
+
+vi.mock('@tanstack/react-router', () => ({
+ useNavigate: () => vi.fn(),
+ useRouterState: () => '/home',
+}))
+
+afterEach(cleanup)
+
+function Identity() {
+ const { connectionRole, isConnectionRoleLoading } = useAppConnection()
+ return (
+ <output data-testid="identity">
+ {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(
+ JSON.stringify({
+ status: 'ok',
+ auth_mode: 'trusted',
+ root_api_key_required: false,
+ ...(account && user
+ ? { 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({
+ 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()))
+ }
+})
diff --git a/web-studio/src/hooks/use-app-connection.tsx b/web-studio/src/hooks/use-app-connection.tsx
index 10eca5b21..40b1c9356 100644
--- a/web-studio/src/hooks/use-app-connection.tsx
+++ b/web-studio/src/hooks/use-app-connection.tsx
@@ -225,25 +225,34 @@ export function resolveInitialApiKey({
}
export function resolveConnectionRoleProbeState({
+ accountId = '',
apiKey,
baseUrl,
serverMode,
+ userId = '',
}: {
+ accountId?: string
apiKey: string
baseUrl: string
serverMode: ServerMode
+ userId?: string
}): {
isLoading: boolean
role: ConnectionRole
shouldProbe: boolean
} {
- if (!baseUrl) {
+ if (!baseUrl || serverMode === 'offline') {
return { isLoading: false, role: 'unknown', shouldProbe: false }
}
+ if (serverMode === 'checking') {
+ return { isLoading: true, role: 'unknown', shouldProbe: false }
+ }
if (serverMode === 'dev') {
return { isLoading: false, role: 'root', shouldProbe: false }
}
- if (!apiKey) {
+ const hasTrustedIdentity =
+ serverMode === 'trusted' && Boolean(accountId.trim() && userId.trim())
+ if (!apiKey && !hasTrustedIdentity) {
return { isLoading: false, role: 'unknown', shouldProbe: false }
}
return { isLoading: true, role: 'unknown', shouldProbe: true }
@@ -563,9 +572,11 @@ export function AppConnectionProvider({
const isCancelled = () => cancelled
const apiKey = connection.adminApiKey || connection.apiKey
const roleProbe = resolveConnectionRoleProbeState({
+ accountId: connection.accountId,
apiKey,
baseUrl: connection.baseUrl,
serverMode,
+ userId: connection.userId,
})
const probeKey = createConnectionRoleProbeKey(connection, serverMode)
const synchronizedProbe = synchronizedRoleProbeRef.current
diff --git a/web-studio/src/hooks/use-server-mode.ts b/web-studio/src/hooks/use-server-mode.ts
index 5f657ac44..d151b7bcc 100644
--- a/web-studio/src/hooks/use-server-mode.ts
+++ b/web-studio/src/hooks/use-server-mode.ts
@@ -1,10 +1,18 @@
import { getHealth } from '#/lib/ov-client'
+import { createClient } from '#/gen/ov-client/client'
export type ServerAuthMode = 'api_key' | 'trusted' | 'dev' | 'oidc' | 'ldap'
export type ServerMode = ServerAuthMode | 'checking' | 'offline'
-const SERVER_AUTH_MODES = new Set<ServerAuthMode>(['api_key', 'trusted', 'dev', 'oidc', 'ldap'])
+const SERVER_AUTH_MODES = new Set<ServerAuthMode>([
+ 'api_key',
+ 'trusted',
+ 'dev',
+ 'oidc',
+ 'ldap',
+])
const HEALTH_REQUEST_REUSE_MS = 1_000
+const healthClient = createClient()
let recentHealthRequest:
| {
@@ -45,6 +53,7 @@ export async function fetchServerHealth(
}
const promise = getHealth({
+ client: healthClient,
baseURL: normalizedBaseUrl,
headers: {
Accept: 'application/json',
diff --git a/web-studio/src/lib/admin-probe.test.ts b/web-studio/src/lib/admin-probe.test.ts
new file mode 100644
index 000000000..84aaee97a
--- /dev/null
+++ b/web-studio/src/lib/admin-probe.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from 'vitest'
+import { createServer } from 'node:http'
+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[] = []
+ const server = createServer((req, res) => {
+ requests.push(req.url || '')
+ 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')) {
+ res.statusCode = 403
+ res.end(
+ JSON.stringify({
+ error: {
+ code: 'PERMISSION_DENIED',
+ message: 'Data access denied',
+ },
+ }),
+ )
+ } else {
+ res.statusCode = 400
+ res.end(
+ JSON.stringify({
+ error: { code: 'INVALID_ARGUMENT', message: 'Missing identity' },
+ }),
+ )
+ }
+ })
+ server.listen(0, '127.0.0.1')
+ await once(server, 'listening')
+ const { port } = server.address() as { port: number }
+ try {
+ const result = await probeStudioConnection({
+ baseUrl: `http://127.0.0.1:${port}`,
+ serverMode: 'trusted',
+ accountId: 'account-a',
+ userId: 'alice',
+ apiKey: '',
+ adminApiKey: '',
+ })
+ expect(result.rootApiKeyRequired).toBe(required)
+ expect(result.admin).toMatchObject({
+ state: 'skipped',
+ detailCode: 'controlKeyRequired',
+ })
+ expect(result.data).toMatchObject({
+ state: 'error',
+ statusCode: 403,
+ errorCode: 'PERMISSION_DENIED',
+ })
+ expect(requests.some((path) => path.startsWith('/api/v1/admin'))).toBe(
+ false,
+ )
+ } finally {
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ }
+ },
+ )
+})
diff --git a/web-studio/src/lib/admin.ts b/web-studio/src/lib/admin.ts
index f3799d404..e37eb3641 100644
--- a/web-studio/src/lib/admin.ts
+++ b/web-studio/src/lib/admin.ts
@@ -1,4 +1,5 @@
import axios from 'axios'
+import { fetchServerHealth } from '#/hooks/use-server-mode'
import { createClient } from '#/gen/ov-client/client'
import {
@@ -75,12 +76,15 @@ export type CapabilityDetailCode =
export type CapabilityProbeResult = {
detail?: string
detailCode?: CapabilityDetailCode
+ errorCode?: string
+ statusCode?: number
state: ProbeState
}
export type StudioConnectionProbe = {
admin: CapabilityProbeResult
data: CapabilityProbeResult
+ rootApiKeyRequired?: boolean
}
export type ProbeConnectionInput = {
@@ -167,6 +171,20 @@ function setApiKeyHeader(
setOptionalHeader(headers, 'X-API-Key', apiKey)
}
+function probeError(error: unknown): CapabilityProbeResult {
+ const response = axios.isAxiosError(error) ? error.response : undefined
+ const payload: unknown = response?.data
+ return {
+ detail: getErrorMessage(error),
+ errorCode:
+ isRecord(payload) && isRecord(payload.error)
+ ? asString(payload.error.code)
+ : undefined,
+ statusCode: response?.status,
+ state: 'error',
+ }
+}
+
async function probeAdminAccess(
input: ProbeConnectionInput,
): Promise<CapabilityProbeResult> {
@@ -184,7 +202,7 @@ async function probeAdminAccess(
// never promoted to admin access, so management stays gated behind the root
// or account-admin key alone.
const controlKey = input.adminApiKey.trim()
- if (input.serverMode === 'api_key' && !controlKey) {
+ if (!controlKey) {
return {
detailCode: 'controlKeyRequired',
state: 'skipped',
@@ -207,10 +225,7 @@ async function probeAdminAccess(
accountsError.response?.status !== 403 ||
!input.accountId
) {
- return {
- detail: getErrorMessage(accountsError),
- state: 'error',
- }
+ return probeError(accountsError)
}
try {
@@ -226,10 +241,7 @@ async function probeAdminAccess(
state: 'ok',
}
} catch (usersError) {
- return {
- detail: getErrorMessage(usersError),
- state: 'error',
- }
+ return probeError(usersError)
}
}
}
@@ -258,7 +270,10 @@ async function probeDataAccess(
const client = createProbeClient(input.baseUrl)
const headers: Record<string, string> = {}
- setApiKeyHeader(headers, input.apiKey)
+ setApiKeyHeader(
+ headers,
+ input.apiKey || (input.serverMode === 'trusted' ? input.adminApiKey : ''),
+ )
if (input.serverMode === 'trusted') {
setOptionalHeader(headers, 'X-OpenViking-Account', input.accountId)
@@ -279,22 +294,36 @@ async function probeDataAccess(
state: 'ok',
}
} catch (error) {
- return {
- detail: getErrorMessage(error),
- state: 'error',
- }
+ return probeError(error)
}
}
export async function probeStudioConnection(
input: ProbeConnectionInput,
): Promise<StudioConnectionProbe> {
- const [admin, data] = await Promise.all([
+ 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([
probeAdminAccess(input),
probeDataAccess(input),
+ Promise.allSettled(
+ input.serverMode === 'trusted'
+ ? [fetchServerHealth(input.baseUrl, headers)]
+ : [],
+ ),
])
-
- return { admin, data }
+ 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,
+ }
}
function normalizeAccount(value: unknown): AdminAccount | null {
diff --git a/web-studio/src/routes/settings/route.test.tsx b/web-studio/src/routes/settings/route.test.tsx
new file mode 100644
index 000000000..895fbe4ec
--- /dev/null
+++ b/web-studio/src/routes/settings/route.test.tsx
@@ -0,0 +1,65 @@
+// @vitest-environment jsdom
+import type { ComponentType } from 'react'
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { afterEach, expect, it, vi } from 'vitest'
+
+import { Route } from './route'
+
+const { probe } = vi.hoisted(() => ({ probe: vi.fn() }))
+vi.mock('#/lib/admin', () => ({ probeStudioConnection: probe }))
+vi.mock('#/hooks/use-app-connection', () => ({
+ useAppConnection: () => ({
+ connection: {
+ baseUrl: 'http://localhost:1933',
+ accountId: 'account-a',
+ userId: 'alice',
+ adminApiKey: '',
+ apiKey: '',
+ },
+ serverMode: 'trusted',
+ saveConnection: vi.fn(),
+ }),
+}))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ i18n: { resolvedLanguage: 'en' },
+ }),
+}))
+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()
+ },
+)
diff --git a/web-studio/src/routes/settings/route.tsx b/web-studio/src/routes/settings/route.tsx
index 91d06cd1e..df59ba226 100644
--- a/web-studio/src/routes/settings/route.tsx
+++ b/web-studio/src/routes/settings/route.tsx
@@ -209,7 +209,7 @@ function ConnectionSettingsRoute() {
serverMode === 'trusted' &&
!probeQuery.isFetching &&
!hasControlCredential &&
- (adminProbe?.state === 'error' || dataProbe?.state === 'error')
+ probeQuery.data?.rootApiKeyRequired === true
const keyGuide =
serverMode === 'trusted'
? trustedCredentialRequired