Skip to content

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

fix: require server api key in trusted auth mode (#924)

Jiahui Zhouf9ccea0de08d
diff --git a/openviking/server/app.py b/openviking/server/app.py
index 6d84da38e..cebd15add 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -85,11 +85,19 @@ def create_app(
)
elif config.auth_mode == "trusted":
app.state.api_key_manager = None
- logger.warning(
- "Trusted mode enabled: authentication uses X-OpenViking-Account/User/Agent "
- "headers without API keys. Only expose this server behind a trusted "
- "network boundary or identity-injecting gateway."
- )
+ if config.root_api_key:
+ logger.info(
+ "Trusted mode enabled: authentication trusts X-OpenViking-Account/User/Agent "
+ "headers and requires the configured server API key on each request. "
+ "Only expose this server behind a trusted network boundary or "
+ "identity-injecting gateway."
+ )
+ else:
+ logger.warning(
+ "Trusted mode enabled: authentication uses X-OpenViking-Account/User/Agent "
+ "headers without API keys. Only expose this server behind a trusted "
+ "network boundary or identity-injecting gateway."
+ )
else:
app.state.api_key_manager = None
logger.warning(
diff --git a/openviking/server/auth.py b/openviking/server/auth.py
index 213506dc0..f7d897901 100644
--- a/openviking/server/auth.py
+++ b/openviking/server/auth.py
@@ -2,6 +2,7 @@
# SPDX-License-Identifier: Apache-2.0
"""Authentication and authorization middleware for OpenViking multi-tenant HTTP Server."""
+import hmac
from typing import Optional
from fastapi import Depends, Header, Request
@@ -44,6 +45,23 @@ def _root_request_requires_explicit_tenant(path: str) -> bool:
return True
+def _configured_root_api_key(request: Request) -> Optional[str]:
+ config = getattr(request.app.state, "config", None)
+ return getattr(config, "root_api_key", 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 = None
+ if not isinstance(authorization, str):
+ authorization = None
+ if x_api_key:
+ return x_api_key
+ if authorization and authorization.startswith("Bearer "):
+ return authorization[7:]
+ return None
+
+
async def resolve_identity(
request: Request,
x_api_key: Optional[str] = Header(None),
@@ -61,8 +79,15 @@ async def resolve_identity(
"""
auth_mode = _auth_mode(request)
api_key_manager = getattr(request.app.state, "api_key_manager", None)
+ api_key = _extract_api_key(x_api_key, authorization)
if auth_mode == "trusted":
+ configured_root_api_key = _configured_root_api_key(request)
+ if configured_root_api_key:
+ if not api_key:
+ raise UnauthenticatedError("Missing API Key")
+ if not hmac.compare_digest(api_key, configured_root_api_key):
+ raise UnauthenticatedError("Invalid API Key")
if not x_openviking_account or not x_openviking_user:
raise InvalidArgumentError(
"Trusted mode requests must include X-OpenViking-Account and X-OpenViking-User."
@@ -82,12 +107,6 @@ async def resolve_identity(
agent_id=x_openviking_agent or "default",
)
- # Extract API key from request
- api_key = x_api_key
- if not api_key and authorization:
- if authorization.startswith("Bearer "):
- api_key = authorization[7:]
-
if not api_key:
raise UnauthenticatedError("Missing API Key")
diff --git a/openviking/storage/vectordb/collection/volcengine_collection.py b/openviking/storage/vectordb/collection/volcengine_collection.py
index 8ae7c0745..18cfa86cb 100644
--- a/openviking/storage/vectordb/collection/volcengine_collection.py
+++ b/openviking/storage/vectordb/collection/volcengine_collection.py
@@ -117,7 +117,7 @@ class VolcengineCollection(ICollection):
@staticmethod
def _sanitize_uri_value(v: Any) -> Any:
- """Remove viking:// prefix and normalize to /.../ format; return None for empty values"""
+ """Remove viking:// prefix and normalize to /... format; return None for empty values"""
if not isinstance(v, str):
return v
s = v.strip()
@@ -128,7 +128,7 @@ class VolcengineCollection(ICollection):
s = s.strip("/")
if not s:
return None
- return f"/{s}/"
+ return f"/{s}"
@classmethod
def _sanitize_payload(cls, obj: Any) -> Any:
diff --git a/tests/server/test_auth.py b/tests/server/test_auth.py
index b9fc1297a..943309de3 100644
--- a/tests/server/test_auth.py
+++ b/tests/server/test_auth.py
@@ -3,6 +3,8 @@
"""Tests for multi-tenant authentication (openviking/server/auth.py)."""
+import io
+import logging
import uuid
import httpx
@@ -13,6 +15,7 @@ from fastapi import Request as FastAPIRequest
from fastapi.responses import JSONResponse
from starlette.requests import Request
+from openviking.server import app as server_app_module
from openviking.server.app import create_app
from openviking.server.auth import get_request_context, resolve_identity
from openviking.server.config import ServerConfig, _is_localhost, validate_server_config
@@ -36,13 +39,14 @@ def _make_request(
headers: dict[str, str] | None = None,
auth_enabled: bool = True,
auth_mode: str = "api_key",
+ root_api_key: str | None = None,
) -> Request:
"""Create a minimal Starlette request for auth dependency tests."""
raw_headers = []
for key, value in (headers or {}).items():
raw_headers.append((key.lower().encode("latin-1"), value.encode("latin-1")))
app = FastAPI()
- app.state.config = ServerConfig(auth_mode=auth_mode)
+ app.state.config = ServerConfig(auth_mode=auth_mode, root_api_key=root_api_key)
if auth_enabled:
# Non-empty api_key_manager means the server is in authenticated mode.
app.state.api_key_manager = object()
@@ -59,6 +63,7 @@ def _build_auth_http_test_app(
identity: ResolvedIdentity | None,
auth_enabled: bool = True,
auth_mode: str = "api_key",
+ root_api_key: str | None = None,
) -> FastAPI:
"""Create a lightweight app that exercises auth dependency wiring.
@@ -66,7 +71,7 @@ def _build_auth_http_test_app(
the test focused on request auth behavior and the structured HTTP error body.
"""
app = FastAPI()
- app.state.config = ServerConfig(auth_mode=auth_mode)
+ app.state.config = ServerConfig(auth_mode=auth_mode, root_api_key=root_api_key)
if auth_enabled:
# Match production auth mode so get_request_context enters the guard path.
app.state.api_key_manager = object()
@@ -511,6 +516,56 @@ async def test_trusted_mode_allows_header_identity_without_api_key():
assert identity.agent_id == "assistant-1"
+async def test_trusted_mode_with_root_api_key_requires_matching_api_key():
+ """Trusted mode should require the configured server API key when present."""
+ request = _make_request(
+ "/api/v1/resources",
+ headers={
+ "X-OpenViking-Account": "acme",
+ "X-OpenViking-User": "alice",
+ },
+ auth_enabled=False,
+ auth_mode="trusted",
+ root_api_key=ROOT_KEY,
+ )
+
+ with pytest.raises(OpenVikingError, match="Missing API Key"):
+ await resolve_identity(
+ request,
+ x_openviking_account="acme",
+ x_openviking_user="alice",
+ )
+
+
+async def test_trusted_mode_with_root_api_key_accepts_matching_api_key():
+ """Trusted mode should accept explicit identity headers plus the configured server API key."""
+ request = _make_request(
+ "/api/v1/resources",
+ headers={
+ "X-API-Key": ROOT_KEY,
+ "X-OpenViking-Account": "acme",
+ "X-OpenViking-User": "alice",
+ "X-OpenViking-Agent": "assistant-1",
+ },
+ 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",
+ x_openviking_agent="assistant-1",
+ )
+
+ assert identity.role == Role.USER
+ assert identity.account_id == "acme"
+ assert identity.user_id == "alice"
+ assert identity.agent_id == "assistant-1"
+
+
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(
@@ -550,6 +605,75 @@ async def test_trusted_mode_tenant_http_routes_accept_explicit_identity_headers(
assert response.json()["result"] == {"account_id": "acme", "user_id": "alice"}
+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."""
+ 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-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",
+ "X-OpenViking-Agent": "assistant-1",
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json()["result"] == {"account_id": "acme", "user_id": "alice"}
+
+
+async def test_trusted_mode_startup_log_mentions_root_key_requirement_when_configured(
+ auth_service,
+):
+ """Trusted mode startup warning should mention the configured server API key requirement."""
+ config = ServerConfig(auth_mode="trusted", root_api_key=ROOT_KEY)
+ app = create_app(config=config, service=auth_service)
+ log_stream = io.StringIO()
+ handler = logging.StreamHandler(log_stream)
+ handler.setFormatter(logging.Formatter("%(message)s"))
+ server_app_module.logger.addHandler(handler)
+
+ try:
+ async with app.router.lifespan_context(app):
+ pass
+ finally:
+ server_app_module.logger.removeHandler(handler)
+
+ assert "configured server API key" in log_stream.getvalue()
+
+
# ---- _is_localhost tests ----