Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(server): add trusted auth mode for tenant headers (#868)
Jiahui Zhou7398c660dbde
diff --git a/openviking/server/app.py b/openviking/server/app.pyindex b7a68cf3a..6d84da38e 100644--- a/openviking/server/app.py+++ b/openviking/server/app.py@@ -72,7 +72,7 @@ def create_app(set_service(service)# Initialize APIKeyManager after service (needs VikingFS)- if config.root_api_key:+ if config.auth_mode == "api_key" and config.root_api_key:api_key_manager = APIKeyManager(root_key=config.root_api_key,viking_fs=service.viking_fs,@@ -83,6 +83,13 @@ def create_app(logger.info("APIKeyManager initialized with encryption_enabled=%s", config.encryption_enabled)+ 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."+ )else:app.state.api_key_manager = Nonelogger.warning(diff --git a/openviking/server/auth.py b/openviking/server/auth.pyindex 0abd7117e..213506dc0 100644--- a/openviking/server/auth.py+++ b/openviking/server/auth.py@@ -25,6 +25,11 @@ _ROOT_IMPLICIT_TENANT_ALLOWED_PREFIXES = ()+def _auth_mode(request: Request) -> str:+ config = getattr(request.app.state, "config", None)+ return getattr(config, "auth_mode", "api_key")++def _root_request_requires_explicit_tenant(path: str) -> bool:"""Return True when a ROOT request targets tenant-scoped data APIs.@@ -50,11 +55,25 @@ async def resolve_identity("""Resolve API key to identity.Strategy:- - If api_key_manager is None (dev mode): return ROOT with default identity- - Otherwise: resolve via APIKeyManager (root key first, then user key index)+ - trusted mode: trust explicit account/user headers and return USER identity+ - api_key mode without manager: dev mode, return implicit ROOT/default identity+ - api_key mode with manager: resolve via APIKeyManager (root key first, then user key index)"""+ auth_mode = _auth_mode(request)api_key_manager = getattr(request.app.state, "api_key_manager", None)+ if auth_mode == "trusted":+ if not x_openviking_account or not x_openviking_user:+ raise InvalidArgumentError(+ "Trusted mode requests must include X-OpenViking-Account and X-OpenViking-User."+ )+ return ResolvedIdentity(+ role=Role.USER,+ account_id=x_openviking_account,+ user_id=x_openviking_user,+ agent_id=x_openviking_agent or "default",+ )+if api_key_manager is None:return ResolvedIdentity(role=Role.ROOT,@@ -86,9 +105,11 @@ async def get_request_context() -> RequestContext:"""Convert ResolvedIdentity to RequestContext."""path = request.url.path+ auth_mode = _auth_mode(request)api_key_manager = getattr(request.app.state, "api_key_manager", None)if (- api_key_manager is not None+ auth_mode == "api_key"+ and api_key_manager is not Noneand identity.role == Role.ROOTand _root_request_requires_explicit_tenant(path)):@@ -100,6 +121,11 @@ async def get_request_context("and X-OpenViking-User headers. Use a user key for regular data access.")+ if auth_mode == "trusted" and not identity.account_id:+ raise InvalidArgumentError("Trusted mode requests must include X-OpenViking-Account.")+ if auth_mode == "trusted" and not identity.user_id:+ raise InvalidArgumentError("Trusted mode requests must include X-OpenViking-User.")+return RequestContext(user=UserIdentifier(identity.account_id or "default",diff --git a/openviking/server/config.py b/openviking/server/config.pyindex baf058190..e50649f7a 100644--- a/openviking/server/config.py+++ b/openviking/server/config.py@@ -42,6 +42,7 @@ class ServerConfig:host: str = "127.0.0.1"port: int = 1933workers: int = 1+ auth_mode: str = "api_key"root_api_key: Optional[str] = Nonecors_origins: List[str] = field(default_factory=lambda: ["*"])with_bot: bool = False # Enable Bot API proxy to Vikingbot@@ -93,6 +94,7 @@ def load_server_config(config_path: Optional[str] = None) -> ServerConfig:host=server_data.get("host", "127.0.0.1"),port=server_data.get("port", 1933),workers=server_data.get("workers", 1),+ auth_mode=server_data.get("auth_mode", "api_key"),root_api_key=server_data.get("root_api_key"),cors_origins=server_data.get("cors_origins", ["*"]),encryption_enabled=encryption_enabled,@@ -117,14 +119,30 @@ def _is_localhost(host: str) -> bool:def validate_server_config(config: ServerConfig) -> None:"""Validate server config for safe startup.- When ``root_api_key`` is not set, authentication is disabled (dev mode).- This is only acceptable when the server binds to localhost. Binding to a- non-loopback address without authentication exposes an unauthenticated ROOT- endpoint to the network.+ In ``api_key`` mode, when ``root_api_key`` is not set, authentication is+ disabled (dev mode). This is only acceptable when the server binds to+ localhost. Binding to a non-loopback address without authentication+ exposes an unauthenticated ROOT endpoint to the network.Raises:SystemExit: If the configuration is unsafe."""+ if config.auth_mode not in {"api_key", "trusted"}:+ logger.error(+ "Invalid server.auth_mode=%r. Expected one of: 'api_key', 'trusted'.",+ config.auth_mode,+ )+ sys.exit(1)++ if config.auth_mode == "trusted":+ if not _is_localhost(config.host):+ logger.warning(+ "SECURITY: server.auth_mode='trusted' on non-localhost host '%s'. "+ "Only use this behind a trusted network boundary or identity-injecting gateway.",+ config.host,+ )+ return+if config.root_api_key:returndiff --git a/tests/server/test_auth.py b/tests/server/test_auth.pyindex 78a02e83e..b9fc1297a 100644--- a/tests/server/test_auth.py+++ b/tests/server/test_auth.py@@ -35,12 +35,14 @@ def _make_request(path: str,headers: dict[str, str] | None = None,auth_enabled: bool = True,+ auth_mode: str = "api_key",) -> 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)if auth_enabled:# Non-empty api_key_manager means the server is in authenticated mode.app.state.api_key_manager = object()@@ -54,8 +56,9 @@ def _make_request(def _build_auth_http_test_app(- identity: ResolvedIdentity,+ identity: ResolvedIdentity | None,auth_enabled: bool = True,+ auth_mode: str = "api_key",) -> FastAPI:"""Create a lightweight app that exercises auth dependency wiring.@@ -63,6 +66,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)if auth_enabled:# Match production auth mode so get_request_context enters the guard path.app.state.api_key_manager = object()@@ -87,7 +91,8 @@ def _build_auth_http_test_app("""Return a fixed identity so tests can isolate request header behavior."""return identity- app.dependency_overrides[resolve_identity] = _resolve_identity_override+ if identity is not None:+ app.dependency_overrides[resolve_identity] = _resolve_identity_override@app.get("/api/v1/fs/ls")async def fs_ls(ctx=Depends(get_request_context)):@@ -480,6 +485,71 @@ 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",+ "X-OpenViking-Agent": "assistant-1",+ },+ auth_enabled=False,+ auth_mode="trusted",+ )++ identity = await resolve_identity(+ request,+ 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(+ identity=None,+ auth_enabled=False,+ auth_mode="trusted",+ )+ 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")++ assert response.status_code == 400+ assert response.json()["error"]["code"] == "INVALID_ARGUMENT"+++async def test_trusted_mode_tenant_http_routes_accept_explicit_identity_headers():+ """Trusted mode should allow tenant-scoped routes with account/user headers."""+ app = _build_auth_http_test_app(+ identity=None,+ auth_enabled=False,+ auth_mode="trusted",+ )+ 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",+ "X-OpenViking-Agent": "assistant-1",+ },+ )++ assert response.status_code == 200+ assert response.json()["result"] == {"account_id": "acme", "user_id": "alice"}++# ---- _is_localhost tests ----@@ -515,3 +585,9 @@ def test_validate_with_key_any_host_passes():for host in ("0.0.0.0", "::", "192.168.1.1", "127.0.0.1"):config = ServerConfig(host=host, root_api_key="some-secret-key")validate_server_config(config) # should not raise+++def test_validate_trusted_mode_without_key_non_localhost_passes():+ """Trusted mode should bypass the localhost-only dev-mode restriction."""+ config = ServerConfig(host="0.0.0.0", root_api_key=None, auth_mode="trusted")+ validate_server_config(config)