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
refactor(auth): introduce plugin-based authentication architecture (#2709)
MaojiaShengab656e240d9a
diff --git a/docs/en/guides/04-authentication.md b/docs/en/guides/04-authentication.mdindex 7fca4c3a8..e2c2c3d96 100644--- a/docs/en/guides/04-authentication.md+++ b/docs/en/guides/04-authentication.md@@ -1,6 +1,6 @@# Authentication-OpenViking Server supports three authentication modes with role-based access control: `api_key`, `trusted`, and `dev`. The mode is auto-detected if not explicitly configured.+OpenViking Server supports three built-in authentication modes with role-based access control: `api_key`, `trusted`, and `dev`. The mode is auto-detected if not explicitly configured. In addition, custom authentication plugins can be registered to support arbitrary identity sources (e.g., LDAP, OIDC, mTLS).## Overview@@ -46,6 +46,57 @@ Start the server:openviking-server```+### Custom Authentication Plugins++The server uses a plugin-based auth architecture. Each `auth_mode` maps to an `AuthPlugin` implementation. Built-in plugins (`dev`, `api_key`, `trusted`) are auto-registered; third-party plugins can be added by subclassing `AuthPlugin` and registering it before startup.++**Plugin interface (`openviking.server.auth.plugin.AuthPlugin`)**++| Method | Purpose |+|--------|---------|+| `resolve_identity(request, api_key, x_openviking_account, x_openviking_user)` | Resolve credentials to a `ResolvedIdentity`. |+| `validate_config(config)` | Validate `ServerConfig` at startup; should `sys.exit(1)` on fatal misconfiguration. |+| `initialize(app, service, config)` | Initialize runtime state (e.g., `APIKeyManager`) on `app.state`. |+| `get_request_context_checks(path, identity)` | Optional post-auth path/identity checks. |+| `requires_api_key_manager()` | Whether Admin API routes need an `APIKeyManager`. |+| `can_skip_api_key_for_bot_proxy()` | Whether the bot proxy may skip API key validation (e.g., `dev` mode). |++**Register a custom plugin**++```python+from openviking.server.auth.plugin import AuthPlugin+from openviking.server.auth.registry import register_auth_plugin+from openviking.server.identity import ResolvedIdentity, Role++@register_auth_plugin+class LDAPAuthPlugin(AuthPlugin):+ auth_mode = "ldap"++ async def resolve_identity(self, request, *, api_key=None, x_openviking_account=None, x_openviking_user=None):+ # ... LDAP bind and identity resolution ...+ return ResolvedIdentity(role=Role.USER, account_id="...", user_id="...")++ def validate_config(self, config):+ pass++ async def initialize(self, app, service, config):+ pass+```++Then set `server.auth_mode = "ldap"` in `ov.conf`.++**Custom roles**++The built-in `Role` class supports dynamic registration of custom roles with privilege ranks:++```python+from openviking.server.identity import Role++Role.register("operator", rank=1) # Between USER (0) and ADMIN (1)+```++Custom roles work with `require_role()` and `require_auth_role()` decorators out of the box.+## Managing Accounts and UsersNormal requests in both `api_key` and `trusted` modes do not need Admin API as a prerequisite for ordinary reads, writes, search, or session access. Admin API is still the place to create accounts, register users, change roles, and issue user keys.diff --git a/docs/zh/guides/04-authentication.md b/docs/zh/guides/04-authentication.mdindex 4670858b2..1e27f421c 100644--- a/docs/zh/guides/04-authentication.md+++ b/docs/zh/guides/04-authentication.md@@ -1,6 +1,6 @@# 认证-OpenViking Server 支持三种认证模式,并带有基于角色的访问控制:`api_key`、`trusted` 和 `dev`。如果未显式配置,模式会自动推导。+OpenViking Server 支持三种内置认证模式,并带有基于角色的访问控制:`api_key`、`trusted` 和 `dev`。如果未显式配置,模式会自动推导。此外,系统支持自定义认证插件,可对接任意身份源(如 LDAP、OIDC、mTLS 等)。## 概述@@ -46,6 +46,57 @@ OpenViking 使用两层 API Key 体系:openviking-server```+### 自定义认证插件++服务端采用插件化认证架构。每种 `auth_mode` 对应一个 `AuthPlugin` 实现。内置插件(`dev`、`api_key`、`trusted`)会自动注册;第三方插件可通过继承 `AuthPlugin` 并在启动前注册来扩展。++**插件接口(`openviking.server.auth.plugin.AuthPlugin`)**++| 方法 | 用途 |+|------|------|+| `resolve_identity(request, api_key, x_openviking_account, x_openviking_user)` | 将凭据解析为 `ResolvedIdentity`。 |+| `validate_config(config)` | 在启动时校验 `ServerConfig`;遇到致命错误应调用 `sys.exit(1)`。 |+| `initialize(app, service, config)` | 在 `app.state` 上初始化运行时状态(如 `APIKeyManager`)。 |+| `get_request_context_checks(path, identity)` | 可选的认证后路径/身份检查。 |+| `requires_api_key_manager()` | Admin API 路由是否需要 `APIKeyManager`。 |+| `can_skip_api_key_for_bot_proxy()` | Bot 代理是否可以跳过 API Key 校验(如 `dev` 模式)。 |++**注册自定义插件**++```python+from openviking.server.auth.plugin import AuthPlugin+from openviking.server.auth.registry import register_auth_plugin+from openviking.server.identity import ResolvedIdentity, Role++@register_auth_plugin+class LDAPAuthPlugin(AuthPlugin):+ auth_mode = "ldap"++ async def resolve_identity(self, request, *, api_key=None, x_openviking_account=None, x_openviking_user=None):+ # ... LDAP 绑定与身份解析 ...+ return ResolvedIdentity(role=Role.USER, account_id="...", user_id="...")++ def validate_config(self, config):+ pass++ async def initialize(self, app, service, config):+ pass+```++然后在 `ov.conf` 中设置 `server.auth_mode = "ldap"`。++**自定义角色**++内置的 `Role` 类支持动态注册自定义角色及权限等级:++```python+from openviking.server.identity import Role++Role.register("operator", rank=1) # 权限介于 USER (0) 与 ADMIN (1) 之间+```++自定义角色可直接用于 `require_role()` 和 `require_auth_role()` 装饰器。+## 管理账户和用户普通读写、检索、会话等数据请求在 `api_key` 和 `trusted` 两种模式下都不依赖 Admin API 预注册。Admin API 仍然负责创建 account、注册用户、修改角色以及签发 user key。diff --git a/openviking/server/app.py b/openviking/server/app.pyindex f221b289b..c61bd5936 100644--- a/openviking/server/app.py+++ b/openviking/server/app.py@@ -16,7 +16,6 @@ from fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponse, JSONResponse, RedirectResponsefrom starlette.exceptions import HTTPException as StarletteHTTPException-from openviking.server.api_keys import APIKeyManagerfrom openviking.server.config import (ServerConfig,load_bot_gateway_token,@@ -25,7 +24,7 @@ from openviking.server.config import ()from openviking.server.dependencies import set_server_config, set_servicefrom openviking.server.error_mapping import map_exception-from openviking.server.identity import AuthMode, Role+from openviking.server.identity import Rolefrom openviking.server.models import ERROR_CODE_TO_HTTP_STATUS, ErrorInfo, Responsefrom openviking.server.profile_middleware import create_profile_http_middlewarefrom openviking.server.routers import (@@ -77,42 +76,45 @@ def _on_deferred_init_done(task):os._exit(1)-async def _initialize_api_key_manager(+async def _initialize_auth_plugin(app: FastAPI,service: OpenVikingService,config: ServerConfig,) -> None:- """Initialize API key state before the app serves authenticated requests."""+ """Initialize the auth plugin before the app serves authenticated requests."""+ from openviking.server.auth.registry import get_registry+effective_auth_mode = config.get_effective_auth_mode()- if config.root_api_key and config.root_api_key != "":- api_key_manager = APIKeyManager(- 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()- app.state.api_key_manager = api_key_manager- logger.info(- "APIKeyManager initialized with api_key_hashing_enabled=%s",- config.api_key_hashing_enabled,- )- if effective_auth_mode == AuthMode.TRUSTED:- logger.info(- "Trusted mode enabled: authentication trusts X-OpenViking-Account/User "- "headers and requires the configured server API key on each request. "- "Only expose this server behind a trusted network boundary or "- "identity-injecting gateway."- )- return+ registry = get_registry()- app.state.api_key_manager = None- if effective_auth_mode == AuthMode.TRUSTED:- logger.warning(- "Trusted mode enabled: authentication uses X-OpenViking-Account/User "- "headers without API keys. This is only allowed on localhost. "- "Only expose this server behind a trusted network boundary or "- "identity-injecting gateway after configuring server.root_api_key."+ # Ensure built-in plugins are registered+ from openviking.server.auth.plugins import (+ ApiKeyAuthPlugin,+ DevAuthPlugin,+ TrustedAuthPlugin,+ )++ if registry.get("dev") is None:+ registry.register(DevAuthPlugin)+ if registry.get("api_key") is None:+ registry.register(ApiKeyAuthPlugin)+ if registry.get("trusted") is None:+ registry.register(TrustedAuthPlugin)++ plugin_cls = registry.get(effective_auth_mode)+ if plugin_cls is None:+ logger.error(+ "Unknown auth_mode: %r. No auth plugin registered. "+ "Registered modes: %s.",+ effective_auth_mode,+ ", ".join(registry.list_modes()),)+ raise RuntimeError(f"Unknown auth_mode: {effective_auth_mode}")++ plugin = plugin_cls()+ app.state.auth_plugin = plugin+ await plugin.initialize(app, service, config)+ logger.info("Auth plugin initialized: %s", effective_auth_mode)async def _initialize_runtime_state(@@ -122,7 +124,7 @@ async def _initialize_runtime_state() -> None:"""Initialize service and auth dependencies before traffic is accepted."""await service.initialize()- await _initialize_api_key_manager(app, service, config)+ await _initialize_auth_plugin(app, service, config)logger.info("OpenVikingService initialization complete")diff --git a/openviking/server/auth.py b/openviking/server/auth.pydeleted file mode 100644index 86316f0e8..000000000--- a/openviking/server/auth.py+++ /dev/null@@ -1,544 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: AGPL-3.0-"""Authentication and authorization middleware for OpenViking multi-tenant HTTP Server."""--import hmac-from typing import Optional--from fastapi import Depends, Header, Request--from openviking.core.peer_id import normalize_peer_id-from openviking.server.identity import (- AuthMode,- RequestContext,- ResolvedIdentity,- Role,-)-from openviking.telemetry.span_models import update_root_span_identity-from openviking_cli.exceptions import (- InvalidArgumentError,- PermissionDeniedError,- UnauthenticatedError,-)-from openviking_cli.session.user_id import UserIdentifier--# Privilege ranking for role-downgrade detection in OAuth bearer auth. Higher-# rank ⇒ more privilege. Used to compare an OAuth token's embedded role-# against the user's current role: a token whose role outranks the current-# role is a stale token from before a `set_role` demotion and must be rejected.-_ROLE_RANK = {Role.USER: 0, Role.ADMIN: 1, Role.ROOT: 2}---_TRUSTED_RELAXED_IDENTITY_PREFIXES = ("/api/v1/admin",)-_API_KEY_ROOT_ALLOWED_PATHS = {- "/api/v1/system/status",- "/api/v1/system/wait",- "/api/v1/debug/health",-}-_API_KEY_ROOT_ALLOWED_PREFIXES = (- "/api/v1/admin",- "/api/v1/observer",- "/api/v1/console",- "/api/v1/tasks",- "/api/v1/system/backend",- "/api/v1/system/sync",-)---def _api_key_root_can_access_path(path: str) -> bool:- if path in _API_KEY_ROOT_ALLOWED_PATHS:- return True- if path.startswith(_API_KEY_ROOT_ALLOWED_PREFIXES):- return True- return False---def _auth_mode(request: Request) -> AuthMode:- config = getattr(request.app.state, "config", None)- if config is not None and hasattr(config, "get_effective_auth_mode"):- return config.get_effective_auth_mode()- return AuthMode.API_KEY---def _trusted_request_requires_explicit_identity(path: str) -> bool:- if path.startswith(_TRUSTED_RELAXED_IDENTITY_PREFIXES):- return False- return True---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 = 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---def _normalize_header_value(value: Optional[str]) -> Optional[str]:- if isinstance(value, str):- normalized = value.strip()- return normalized or None- return None---def _normalize_request_value(value: object) -> Optional[str]:- if isinstance(value, str):- normalized = value.strip()- return normalized or None- return None---def normalize_actor_peer_header(value: Optional[str]) -> Optional[str]:- normalized = _normalize_header_value(value)- if normalized and ("/" in normalized or "\\" in normalized):- raise InvalidArgumentError("actor_peer_id must not contain path separators.")- try:- return normalize_peer_id(normalized)- except ValueError as exc:- raise InvalidArgumentError(str(exc)) from exc---def _explicit_identity_from_request(request: Request) -> tuple[Optional[str], Optional[str]]:- path_params = getattr(request, "path_params", {}) or {}- query_params = request.query_params-- account_id = _normalize_request_value(path_params.get("account_id"))- if account_id is None:- account_id = _normalize_request_value(query_params.get("account_id"))-- user_id = _normalize_request_value(path_params.get("user_id"))- if user_id is None:- user_id = _normalize_request_value(query_params.get("user_id"))-- return account_id, user_id---async def _try_resolve_oauth_token(- request: Request,- api_key: str,- *,- x_openviking_account: Optional[str],- x_openviking_user: Optional[str],-) -> Optional[ResolvedIdentity]:- """Attempt to verify the bearer as an OAuth-issued opaque access token.-- Returns the resolved identity on success. Returns None when the bearer- doesn't carry the OAuth access-token prefix or when OAuth isn't enabled- (caller falls back to the API-key path). Raises UnauthenticatedError- when the bearer IS prefix-tagged but lookup fails — fail-closed.- """- from openviking.server.oauth.provider import ACCESS_TOKEN_PREFIX-- if not api_key.startswith(ACCESS_TOKEN_PREFIX):- return None- provider = getattr(request.app.state, "oauth_provider", None)- if provider is None:- return None-- record = await provider.load_access_token(api_key)- if record is None:- raise UnauthenticatedError("OAuth access token is invalid, expired, or revoked")-- # Lifecycle binding: every OAuth token carries the SHA-256 fingerprint of- # the API key that authorized it. We recompute the user's current key fp- # and demand strict equality. If the user removed (no fp) or rotated- # (different fp) the authorizing key, the token must die — this is the- # invariant "OAuth lifetime ≤ authorizing key lifetime". Tokens missing a- # recorded fp also fail closed: there is no way to validate them safely.- api_key_manager = getattr(request.app.state, "api_key_manager", None)- recorded_fp = record.authorizing_key_fp- current_fp: Optional[str] = None- if api_key_manager is not None and hasattr(api_key_manager, "get_user_key_fingerprint"):- current_fp = api_key_manager.get_user_key_fingerprint(record.account_id, record.user_id)- if not recorded_fp or not current_fp or not hmac.compare_digest(recorded_fp, current_fp):- raise UnauthenticatedError(- "OAuth token's authorizing API key has been rotated or revoked; "- "please re-authorize the client."- )-- try:- role = Role(record.role)- except ValueError as exc:- raise UnauthenticatedError(f"OAuth token has unknown role: {record.role}") from exc-- # Role downgrade protection: fp binds to the key value, but `set_role`- # changes role without rotating the key. Re-fetch the user's current- # role and reject the token if its embedded role exceeds it (demotion).- # Promotion is harmless — the embedded lower privilege is still valid —- # so only downgrades trigger rejection.- if api_key_manager is not None and hasattr(api_key_manager, "get_user_role"):- try:- current_role = api_key_manager.get_user_role(record.account_id, record.user_id)- except Exception: # noqa: BLE001- current_role = role- if _ROLE_RANK[role] > _ROLE_RANK[current_role]:- raise UnauthenticatedError(- "OAuth token's embedded role exceeds the user's current role; "- "please re-authorize the client."- )-- account_id = record.account_id- user_id = record.user_id-- # OAuth tokens are API-key-mode credentials with pinned claims. Header-based- # identity assertion belongs to trusted mode only, so headers may not change- # the effective account/user here.- if x_openviking_account:- raise PermissionDeniedError(- "X-OpenViking-Account can only assert identity in trusted mode."- )- if x_openviking_user:- raise PermissionDeniedError("X-OpenViking-User can only assert identity in trusted mode.")-- effective_account = account_id- effective_user = user_id-- return ResolvedIdentity(- role=role,- account_id=effective_account,- user_id=effective_user,- from_oauth=True,- )---async def resolve_identity(- request: Request,- x_api_key: Optional[str] = Header(None),- authorization: Optional[str] = Header(None),- x_openviking_account: Optional[str] = Header(None, alias="X-OpenViking-Account"),- x_openviking_user: Optional[str] = Header(None, alias="X-OpenViking-User"),-) -> ResolvedIdentity:- """Resolve API key to identity.-- Strategy:- - dev mode: no authentication, return implicit ROOT/default identity- - trusted mode: trust explicit account/user headers, look up role from APIKeyManager- - api_key mode: 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)- x_openviking_account = _normalize_header_value(x_openviking_account)- x_openviking_user = _normalize_header_value(x_openviking_user)- api_key = _extract_api_key(x_api_key, authorization)-- if auth_mode == AuthMode.DEV:- # Dev mode: no authentication, always return ROOT- return ResolvedIdentity(- role=Role.ROOT,- account_id=x_openviking_account or "default",- user_id=x_openviking_user or "default",- )-- if auth_mode == AuthMode.TRUSTED:- 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."- )- explicit_account_id, explicit_user_id = _explicit_identity_from_request(request)- if (- x_openviking_account- and explicit_account_id- and x_openviking_account != explicit_account_id- ):- raise InvalidArgumentError(- "Trusted mode X-OpenViking-Account must match explicit account_id in the URL."- )- if x_openviking_user and explicit_user_id and x_openviking_user != explicit_user_id:- raise InvalidArgumentError(- "Trusted mode X-OpenViking-User must match explicit user_id in the URL."- )-- effective_account_id = explicit_account_id or x_openviking_account- effective_user_id = explicit_user_id or x_openviking_user-- # Admin paths may omit identity completely, but partial identity is rejected.- is_admin_path = request.url.path.startswith(_TRUSTED_RELAXED_IDENTITY_PREFIXES)- if is_admin_path:- 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 configured_root_api_key:- return ResolvedIdentity(- role=Role.ROOT,- account_id=effective_account_id or "trusted",- user_id=effective_user_id or "trusted",- )- 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) + "."- )-- trusted_role = Role.USER- if api_key_manager and effective_account_id and effective_user_id:- trusted_role = api_key_manager.get_user_role(effective_account_id, effective_user_id)-- return ResolvedIdentity(- role=trusted_role,- account_id=effective_account_id or "trusted",- user_id=effective_user_id or "trusted",- )-- # AuthMode.API_KEY- if api_key_manager is None:- # This should not happen due to validate_server_config- raise RuntimeError("api_key_manager not initialized in api_key mode")-- if not api_key:- raise UnauthenticatedError("Missing API Key when resolving identity.")-- # OAuth 2.1 fast path: bearer tokens minted by our OAuth provider carry- # a recognizable prefix; look them up directly and skip the API-key path.- # Failure is fail-closed — a forged token claiming the prefix cannot be- # retried as a plain key. When OAuth is disabled or the bearer lacks the- # prefix, this returns None and the API-key path runs.- oauth_identity = await _try_resolve_oauth_token(- request,- api_key,- x_openviking_account=x_openviking_account,- x_openviking_user=x_openviking_user,- )- if oauth_identity is not None:- return oauth_identity-- identity = api_key_manager.resolve(api_key)- identity.account_id = identity.account_id or "default"- identity.user_id = identity.user_id or "default"-- if x_openviking_account:- raise PermissionDeniedError(- "X-OpenViking-Account can only assert identity in trusted mode."- )- if x_openviking_user:- raise PermissionDeniedError("X-OpenViking-User can only assert identity in trusted mode.")-- return identity---async def get_request_context(- request: Request,- identity: ResolvedIdentity = Depends(resolve_identity),- x_openviking_actor_peer: Optional[str] = Header(None, alias="X-OpenViking-Actor-Peer"),-) -> 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 (- auth_mode == AuthMode.API_KEY- and api_key_manager is not None- and identity.role == Role.ROOT- and not identity.from_oauth- and not _api_key_root_can_access_path(path)- ):- raise PermissionDeniedError(- "ROOT API keys cannot access tenant-scoped data APIs in api_key mode. "- "Use a user/admin API key for data access, or trusted mode for upstream "- "identity assertion."- )-- if auth_mode == AuthMode.TRUSTED:- is_admin_path = path.startswith(_TRUSTED_RELAXED_IDENTITY_PREFIXES)- if not is_admin_path:- if not identity.account_id:- raise InvalidArgumentError(- "Trusted mode requests must include X-OpenViking-Account."- )- if not identity.user_id:- raise InvalidArgumentError("Trusted mode requests must include X-OpenViking-User.")-- ctx = RequestContext(- user=UserIdentifier(- identity.account_id or "default",- identity.user_id or "default",- ),- role=identity.role,- actor_peer_id=normalize_actor_peer_header(x_openviking_actor_peer),- from_oauth=identity.from_oauth,- )- # Update the unified root observability context after authentication succeeds.- update_root_span_identity(- request_state=request.state,- account_id=identity.account_id,- user_id=identity.user_id,- )-- return ctx---def require_role(*allowed_roles: Role):- """Dependency factory that checks role permission.-- Usage:- @router.post("/admin/accounts")- async def create_account(ctx: RequestContext = Depends(require_role(Role.ROOT))):- ...- """-- async def _check(ctx: RequestContext = Depends(get_request_context)):- if ctx.role not in allowed_roles:- raise PermissionDeniedError(- f"Requires role: {', '.join(r.value for r in allowed_roles)}"- )- return ctx-- return Depends(_check)---# Convenience dependency factories for common role requirements-require_root = require_role(Role.ROOT)-require_admin = require_role(Role.ADMIN)-require_user = require_role(Role.USER)---_DEV_MODE_ADMIN_API_MESSAGE = (- "Admin API requires api_key mode with root_api_key configured. Development mode does not "- 'support account or user management. You should set server.auth_mode = "api_key" in ov.conf'-)---def require_auth_role(*allowed_roles: Role):- """Decorator for Admin API routes with mode-aware errors.-- Usage:- @router.post("/admin/accounts")- @require_auth_role(Role.ROOT)- async def create_account(body: CreateAccountRequest, request: Request, ctx: RequestContext):- ...- """- from functools import wraps-- def decorator(func):- @wraps(func)- async def wrapper(*args, **kwargs):- # Extract request and ctx from kwargs or args- request = kwargs.get("request")- ctx = kwargs.get("ctx")-- # Find request and ctx in args if not in kwargs- if request is None or ctx is None:- import inspect-- sig = inspect.signature(func)- bound_args = sig.bind(*args, **kwargs)- bound_args.apply_defaults()- request = bound_args.arguments.get("request")- ctx = bound_args.arguments.get("ctx")-- if request is None:- raise RuntimeError("require_auth_role decorator requires 'request' parameter")- if ctx is None:- raise RuntimeError("require_auth_role decorator requires 'ctx' parameter")-- # Check auth mode- auth_mode = _auth_mode(request)-- # In trusted mode, we allow access even without api_key_manager- # as long as the role requirement is satisfied- manager = getattr(request.app.state, "api_key_manager", None)- if manager is None and auth_mode != AuthMode.TRUSTED:- raise PermissionDeniedError(_DEV_MODE_ADMIN_API_MESSAGE)-- if ctx.role not in allowed_roles:- raise PermissionDeniedError(- f"Requires role: {', '.join(r.value for r in allowed_roles)}"- )-- return await func(*args, **kwargs)-- return wrapper-- return decorator---# Convenience decorators for common admin role requirements-def require_auth_root(func):- """Decorator to require ROOT role for Admin API.-- Usage:- @router.post("/admin/accounts")- @require_auth_root- async def create_account(body: CreateAccountRequest, request: Request, ctx: RequestContext):- ...- """- return require_auth_role(Role.ROOT)(func)---def require_auth_admin(func):- """Decorator to require ADMIN role for Admin API.-- Usage:- @router.post("/admin/accounts")- @require_auth_admin- async def create_account(body: CreateAccountRequest, request: Request, ctx: RequestContext):- ...- """- return require_auth_role(Role.ADMIN)(func)---def require_auth_user(func):- """Decorator to require USER role for Admin API.-- Usage:- @router.post("/admin/accounts")- @require_auth_user- async def create_account(body: CreateAccountRequest, request: Request, ctx: RequestContext):- ...- """- return require_auth_role(Role.USER)(func)---def require_auth_root_or_admin(func):- """Decorator to require ROOT or ADMIN role for Admin API.-- Usage:- @router.post("/admin/accounts")- @require_auth_root_or_admin- async def create_account(body: CreateAccountRequest, request: Request, ctx: RequestContext):- ...- """- return require_auth_role(Role.ROOT, Role.ADMIN)(func)---def get_api_key_manager_or_raise(request: Request):- """Get APIKeyManager from app state or raise appropriate error.-- Raises:- PermissionDeniedError: In dev mode without API key manager.- """- manager = getattr(request.app.state, "api_key_manager", None)- auth_mode = _auth_mode(request)- if manager is None and auth_mode != AuthMode.TRUSTED:- raise PermissionDeniedError(_DEV_MODE_ADMIN_API_MESSAGE)- return managerdiff --git a/openviking/server/auth/__init__.py b/openviking/server/auth/__init__.pynew file mode 100644index 000000000..43d3f0b4a--- /dev/null+++ b/openviking/server/auth/__init__.py@@ -0,0 +1,262 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Authentication and authorization middleware for OpenViking multi-tenant HTTP Server."""++from typing import Optional++from fastapi import Depends, Header, Request++from openviking.core.peer_id import normalize_peer_id+from openviking.server.identity import (+ AuthMode,+ RequestContext,+ ResolvedIdentity,+ Role,+)+from openviking.telemetry.span_models import update_root_span_identity+from openviking_cli.exceptions import (+ InvalidArgumentError,+ PermissionDeniedError,+ UnauthenticatedError,+)+from openviking_cli.session.user_id import UserIdentifier+++def _auth_mode(request: Request) -> str:+ config = getattr(request.app.state, "config", None)+ if config is not None and hasattr(config, "get_effective_auth_mode"):+ mode = config.get_effective_auth_mode()+ # AuthMode enum values are strings; custom modes are already strings+ return mode.value if isinstance(mode, AuthMode) else str(mode)+ 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 = 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+++def _normalize_header_value(value: Optional[str]) -> Optional[str]:+ if isinstance(value, str):+ normalized = value.strip()+ return normalized or None+ return None+++def _normalize_request_value(value: object) -> Optional[str]:+ if isinstance(value, str):+ normalized = value.strip()+ return normalized or None+ return None+++def normalize_actor_peer_header(value: Optional[str]) -> Optional[str]:+ normalized = _normalize_header_value(value)+ if normalized and ("/" in normalized or "\\" in normalized):+ raise InvalidArgumentError("actor_peer_id must not contain path separators.")+ try:+ return normalize_peer_id(normalized)+ except ValueError as exc:+ raise InvalidArgumentError(str(exc)) from exc+++def _explicit_identity_from_request(request: Request) -> tuple[Optional[str], Optional[str]]:+ path_params = getattr(request, "path_params", {}) or {}+ query_params = request.query_params++ account_id = _normalize_request_value(path_params.get("account_id"))+ if account_id is None:+ account_id = _normalize_request_value(query_params.get("account_id"))++ user_id = _normalize_request_value(path_params.get("user_id"))+ if user_id is None:+ user_id = _normalize_request_value(query_params.get("user_id"))++ return account_id, user_id+++def _get_plugin(request: Request):+ """Get the active auth plugin from app state."""+ plugin = getattr(request.app.state, "auth_plugin", None)+ if plugin is None:+ raise UnauthenticatedError("Auth plugin not initialized")+ return plugin+++async def resolve_identity(+ request: Request,+ x_api_key: Optional[str] = Header(None),+ authorization: Optional[str] = Header(None),+ x_openviking_account: Optional[str] = Header(None, alias="X-OpenViking-Account"),+ x_openviking_user: Optional[str] = Header(None, alias="X-OpenViking-User"),+) -> ResolvedIdentity:+ """Resolve API key to identity via the active auth plugin."""+ x_openviking_account = _normalize_header_value(x_openviking_account)+ x_openviking_user = _normalize_header_value(x_openviking_user)+ api_key = _extract_api_key(x_api_key, authorization)++ plugin = _get_plugin(request)+ return await plugin.resolve_identity(+ request,+ api_key=api_key,+ x_openviking_account=x_openviking_account,+ x_openviking_user=x_openviking_user,+ )+++async def get_request_context(+ request: Request,+ identity: ResolvedIdentity = Depends(resolve_identity),+ x_openviking_actor_peer: Optional[str] = Header(None, alias="X-OpenViking-Actor-Peer"),+) -> RequestContext:+ """Convert ResolvedIdentity to RequestContext."""+ path = request.url.path+ plugin = _get_plugin(request)+ plugin.get_request_context_checks(path, identity)++ ctx = RequestContext(+ user=UserIdentifier(+ identity.account_id or "default",+ identity.user_id or "default",+ ),+ role=identity.role,+ actor_peer_id=normalize_actor_peer_header(x_openviking_actor_peer),+ from_oauth=identity.from_oauth,+ )+ # Update the unified root observability context after authentication succeeds.+ update_root_span_identity(+ request_state=request.state,+ account_id=identity.account_id,+ user_id=identity.user_id,+ )++ return ctx+++def require_role(*allowed_roles: Role):+ """Dependency factory that checks role permission.++ Usage:+ @router.post("/admin/accounts")+ async def create_account(ctx: RequestContext = Depends(require_role(Role.ROOT))):+ ...+ """++ async def _check(ctx: RequestContext = Depends(get_request_context)):+ if ctx.role not in allowed_roles:+ raise PermissionDeniedError(+ f"Requires role: {', '.join(str(r) for r in allowed_roles)}"+ )+ return ctx++ return Depends(_check)+++# Convenience dependency factories for common role requirements+require_root = require_role(Role.ROOT)+require_admin = require_role(Role.ADMIN)+require_user = require_role(Role.USER)+++_DEV_MODE_ADMIN_API_MESSAGE = (+ "Admin API requires api_key mode with root_api_key configured. Development mode does not "+ 'support account or user management. You should set server.auth_mode = "api_key" in ov.conf'+)+++def require_auth_role(*allowed_roles: Role):+ """Decorator for Admin API routes with mode-aware errors.++ Usage:+ @router.post("/admin/accounts")+ @require_auth_role(Role.ROOT)+ async def create_account(body: CreateAccountRequest, request: Request, ctx: RequestContext):+ ...+ """+ from functools import wraps++ def decorator(func):+ @wraps(func)+ async def wrapper(*args, **kwargs):+ # Extract request and ctx from kwargs or args+ request = kwargs.get("request")+ ctx = kwargs.get("ctx")++ # Find request and ctx in args if not in kwargs+ if request is None or ctx is None:+ import inspect++ sig = inspect.signature(func)+ bound_args = sig.bind(*args, **kwargs)+ bound_args.apply_defaults()+ request = bound_args.arguments.get("request")+ ctx = bound_args.arguments.get("ctx")++ if request is None or ctx is None:+ raise PermissionDeniedError(+ "Admin API authentication failed: unable to resolve request context."+ )++ plugin = _get_plugin(request)+ manager = getattr(request.app.state, "api_key_manager", None)+ if manager is None and plugin.requires_api_key_manager():+ raise PermissionDeniedError(_DEV_MODE_ADMIN_API_MESSAGE)++ if ctx.role not in allowed_roles:+ raise PermissionDeniedError(+ f"Requires role: {', '.join(str(r) for r in allowed_roles)}"+ )++ return await func(*args, **kwargs)++ return wrapper++ return decorator+++# Convenience decorators for common admin role requirements+def require_auth_root(func):+ """Decorator to require ROOT role for Admin API."""+ return require_auth_role(Role.ROOT)(func)+++def require_auth_admin(func):+ """Decorator to require ADMIN role for Admin API."""+ return require_auth_role(Role.ADMIN)(func)+++def require_auth_user(func):+ """Decorator to require USER role for Admin API."""+ return require_auth_role(Role.USER)(func)+++def require_auth_root_or_admin(func):+ """Decorator to require ROOT or ADMIN role for Admin API."""+ return require_auth_role(Role.ROOT, Role.ADMIN)(func)+++def get_api_key_manager_or_raise(request: Request):+ """Get APIKeyManager from app state or raise appropriate error.++ Raises:+ PermissionDeniedError: When the current auth plugin requires an+ APIKeyManager but none is available.+ """+ manager = getattr(request.app.state, "api_key_manager", None)+ plugin = _get_plugin(request)+ if manager is None and plugin.requires_api_key_manager():+ raise PermissionDeniedError(_DEV_MODE_ADMIN_API_MESSAGE)+ return managerdiff --git a/openviking/server/auth/plugin.py b/openviking/server/auth/plugin.pynew file mode 100644index 000000000..ba77898f1--- /dev/null+++ b/openviking/server/auth/plugin.py@@ -0,0 +1,125 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Auth plugin abstract base class for OpenViking multi-tenant HTTP Server."""++from __future__ import annotations++import abc+import sys+from typing import TYPE_CHECKING, ClassVar, Optional++from fastapi import Request++from openviking.server.identity import ResolvedIdentity+from openviking_cli.exceptions import UnauthenticatedError++if TYPE_CHECKING:+ from openviking.server.config import ServerConfig+ from openviking.service.core import OpenVikingService+++class AuthPlugin(abc.ABC):+ """Authentication plugin abstract base class.++ Each ``auth_mode`` value maps to one plugin implementation.+ Third-party plugins subclass this and register via+ ``@register_auth_plugin`` or ``registry.register()``.+ """++ # Subclasses MUST define this, e.g. auth_mode = "ldap"+ auth_mode: ClassVar[str] = ""++ @abc.abstractmethod+ async def resolve_identity(+ self,+ request: Request,+ *,+ api_key: Optional[str] = None,+ x_openviking_account: Optional[str] = None,+ x_openviking_user: Optional[str] = None,+ ) -> ResolvedIdentity:+ """Resolve identity from request credentials.++ Args:+ request: FastAPI request object.+ api_key: Extracted API key from X-API-Key or Authorization header.+ x_openviking_account: Normalized X-OpenViking-Account header value.+ x_openviking_user: Normalized X-OpenViking-User header value.++ Returns:+ ResolvedIdentity with role and user identification.++ Raises:+ UnauthenticatedError: When authentication fails.+ InvalidArgumentError: When request is malformed.+ PermissionDeniedError: When identity assertion is not allowed.+ """+ ...++ @abc.abstractmethod+ def validate_config(self, config: ServerConfig) -> None:+ """Validate server configuration for this plugin.++ Called during server startup. Should exit the process (sys.exit) on+ fatal misconfiguration.++ Args:+ config: ServerConfig instance to validate.+ """+ ...++ @abc.abstractmethod+ async def initialize(+ self,+ app,+ service: OpenVikingService,+ config: ServerConfig,+ ) -> None:+ """Initialize plugin during app startup.++ Called after service initialization but before serving traffic.+ Plugins may store runtime state (e.g. APIKeyManager) on ``app.state``.++ Args:+ app: FastAPI application instance.+ service: OpenVikingService instance.+ config: ServerConfig instance.+ """+ ...++ def get_request_context_checks(+ self,+ path: str,+ identity: ResolvedIdentity,+ ) -> None:+ """Additional path/identity checks after resolving identity.++ Called by ``get_request_context()`` after ``resolve_identity()``+ succeeds. Should raise appropriate exceptions if checks fail.++ Args:+ path: Request URL path.+ identity: Resolved identity from ``resolve_identity()``.++ Raises:+ InvalidArgumentError: When identity is missing required fields.+ PermissionDeniedError: When access is denied to the path.+ """+ pass++ def requires_api_key_manager(self) -> bool:+ """Whether Admin API routes require an APIKeyManager in this mode.++ Returns:+ True if ``api_key_manager`` must be present for admin routes.+ """+ return True++ def can_skip_api_key_for_bot_proxy(self) -> bool:+ """Whether the bot proxy may skip API key validation.++ Returns:+ True if the bot proxy can forward without an API key+ (e.g. dev mode).+ """+ return Falsediff --git a/openviking/server/auth/plugins/__init__.py b/openviking/server/auth/plugins/__init__.pynew file mode 100644index 000000000..c2cb7b915--- /dev/null+++ b/openviking/server/auth/plugins/__init__.py@@ -0,0 +1,20 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Built-in authentication plugins for OpenViking."""++from openviking.server.auth.plugins.api_key import ApiKeyAuthPlugin+from openviking.server.auth.plugins.dev import DevAuthPlugin+from openviking.server.auth.plugins.trusted import TrustedAuthPlugin+from openviking.server.auth.registry import get_registry++# Register built-in plugins on import+_registry = get_registry()+_registry.register(DevAuthPlugin)+_registry.register(ApiKeyAuthPlugin)+_registry.register(TrustedAuthPlugin)++__all__ = [+ "DevAuthPlugin",+ "ApiKeyAuthPlugin",+ "TrustedAuthPlugin",+]diff --git a/openviking/server/auth/plugins/api_key.py b/openviking/server/auth/plugins/api_key.pynew file mode 100644index 000000000..da2ceae3c--- /dev/null+++ b/openviking/server/auth/plugins/api_key.py@@ -0,0 +1,233 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""API key mode authentication plugin."""++from __future__ import annotations++import sys+from typing import Optional++from fastapi import Request++from openviking.server.api_keys import APIKeyManager+from openviking.server.auth.plugin import AuthPlugin+from openviking.server.identity import ResolvedIdentity, Role+from openviking_cli.exceptions import PermissionDeniedError, UnauthenticatedError++_API_KEY_ROOT_ALLOWED_PATHS = {+ "/api/v1/system/status",+ "/api/v1/system/wait",+ "/api/v1/debug/health",+}+_API_KEY_ROOT_ALLOWED_PREFIXES = (+ "/api/v1/admin",+ "/api/v1/observer",+ "/api/v1/console",+ "/api/v1/tasks",+ "/api/v1/system/backend",+ "/api/v1/system/sync",+)+++def _api_key_root_can_access_path(path: str) -> bool:+ if path in _API_KEY_ROOT_ALLOWED_PATHS:+ return True+ if path.startswith(_API_KEY_ROOT_ALLOWED_PREFIXES):+ return True+ return False+++def _remove_header(request: Request, name: bytes) -> None:+ """Remove a header from the underlying request scope.++ Starlette's Headers object is immutable; we mutate the raw scope list+ so downstream middleware and handlers do not see the header.+ """+ scope_headers = request.scope.get("headers", [])+ request.scope["headers"] = [+ (key, value) for key, value in scope_headers if key.lower() != name.lower()+ ]+++class ApiKeyAuthPlugin(AuthPlugin):+ """API key mode: resolve identity via APIKeyManager.++ Supports OAuth bearer tokens layered on top of API keys.+ """++ auth_mode = "api_key"++ async def resolve_identity(+ self,+ request: Request,+ *,+ api_key: Optional[str] = None,+ x_openviking_account: Optional[str] = None,+ x_openviking_user: Optional[str] = None,+ ) -> ResolvedIdentity:+ api_key_manager = getattr(request.app.state, "api_key_manager", None)+ if api_key_manager is None:+ raise RuntimeError("api_key_manager not initialized in api_key mode")++ if not api_key:+ raise UnauthenticatedError("Missing API Key when resolving identity.")++ # OAuth 2.1 fast path+ oauth_identity = await self._try_resolve_oauth_token(+ request,+ api_key,+ x_openviking_account=x_openviking_account,+ x_openviking_user=x_openviking_user,+ )+ if oauth_identity is not None:+ return oauth_identity++ identity = api_key_manager.resolve(api_key)+ identity.account_id = identity.account_id or "default"+ identity.user_id = identity.user_id or "default"++ # Silently ignore identity assertion headers in api_key mode.+ # Older clients may send these headers out of habit; clearing them+ # avoids breaking compatibility without weakening security.+ if x_openviking_account:+ _remove_header(request, b"x-openviking-account")+ if x_openviking_user:+ _remove_header(request, b"x-openviking-user")++ return identity++ async def _try_resolve_oauth_token(+ self,+ request: Request,+ api_key: str,+ *,+ x_openviking_account: Optional[str],+ x_openviking_user: Optional[str],+ ) -> Optional[ResolvedIdentity]:+ """Attempt to verify the bearer as an OAuth-issued opaque access token.++ Returns the resolved identity on success. Returns None when the bearer+ doesn't carry the OAuth access-token prefix or when OAuth isn't enabled.+ Raises UnauthenticatedError when the bearer IS prefix-tagged but lookup+ fails — fail-closed.+ """+ from openviking.server.oauth.provider import ACCESS_TOKEN_PREFIX++ if not api_key.startswith(ACCESS_TOKEN_PREFIX):+ return None+ provider = getattr(request.app.state, "oauth_provider", None)+ if provider is None:+ return None++ record = await provider.load_access_token(api_key)+ if record is None:+ raise UnauthenticatedError(+ "OAuth access token is invalid, expired, or revoked"+ )++ import hmac++ api_key_manager = getattr(request.app.state, "api_key_manager", None)+ recorded_fp = record.authorizing_key_fp+ current_fp: Optional[str] = None+ if api_key_manager is not None and hasattr(+ api_key_manager, "get_user_key_fingerprint"+ ):+ current_fp = api_key_manager.get_user_key_fingerprint(+ record.account_id, record.user_id+ )+ if not recorded_fp or not current_fp or not hmac.compare_digest(+ recorded_fp, current_fp+ ):+ raise UnauthenticatedError(+ "OAuth token's authorizing API key has been rotated or revoked; "+ "please re-authorize the client."+ )++ role = Role(record.role)++ # Role downgrade protection+ if api_key_manager is not None and hasattr(api_key_manager, "get_user_role"):+ try:+ current_role = Role(api_key_manager.get_user_role(+ record.account_id, record.user_id+ ))+ except Exception:+ raise UnauthenticatedError(+ "OAuth token validation failed: unable to verify user's current role; "+ "please re-authorize the client."+ )+ if role.rank > current_role.rank:+ raise UnauthenticatedError(+ "OAuth token's embedded role exceeds the user's current role; "+ "please re-authorize the client."+ )++ # Silently ignore identity assertion headers in api_key mode.+ if x_openviking_account:+ _remove_header(request, b"x-openviking-account")+ if x_openviking_user:+ _remove_header(request, b"x-openviking-user")++ return ResolvedIdentity(+ role=role,+ account_id=record.account_id,+ user_id=record.user_id,+ from_oauth=True,+ )++ def validate_config(self, config) -> None:+ if config.root_api_key and config.root_api_key != "":+ return+ import logging++ logger = logging.getLogger(__name__)+ if _is_localhost(config.host):+ logger.error(+ "server.auth_mode='api_key' requires server.root_api_key to be configured.\n"+ 'To run without authentication on localhost, either set server.auth_mode="dev" '+ "or simply remove the server.auth_mode setting to auto-detect."+ )+ else:+ logger.error(+ "SECURITY: server.auth_mode='api_key' requires server.root_api_key "+ "to be configured when server.host is '%s' (non-localhost).",+ config.host,+ )+ logger.error(+ "To fix, either:\n"+ " 1. Set server.root_api_key in ov.conf, or\n"+ ' 2. Use server.auth_mode="dev" (localhost only)'+ )+ sys.exit(1)++ async def initialize(self, app, service, config) -> None:+ if not config.root_api_key or config.root_api_key == "":+ raise RuntimeError("api_key mode requires root_api_key")+ api_key_manager = APIKeyManager(+ 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()+ app.state.api_key_manager = api_key_manager++ def get_request_context_checks(+ self,+ path: str,+ identity: ResolvedIdentity,+ ) -> None:+ if (+ identity.role == Role.ROOT+ and not identity.from_oauth+ and not _api_key_root_can_access_path(path)+ ):+ raise PermissionDeniedError(+ "ROOT API keys cannot access tenant-scoped data APIs in api_key mode. "+ "Use a user/admin API key for data access, or trusted mode for upstream "+ "identity assertion."+ )+++def _is_localhost(host: str) -> bool:+ return host in {"127.0.0.1", "localhost", "::1"}diff --git a/openviking/server/auth/plugins/dev.py b/openviking/server/auth/plugins/dev.pynew file mode 100644index 000000000..661353dd8--- /dev/null+++ b/openviking/server/auth/plugins/dev.py@@ -0,0 +1,75 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Dev mode authentication plugin."""++from __future__ import annotations++import sys+from typing import Optional++from fastapi import Request++from openviking.server.auth.plugin import AuthPlugin+from openviking.server.identity import ResolvedIdentity, Role+from openviking_cli.exceptions import InvalidArgumentError++_LOCALHOST_HOSTS = {"127.0.0.1", "localhost", "::1"}+++def _is_localhost(host: str) -> bool:+ """Return True if *host* resolves to a loopback address."""+ return host in _LOCALHOST_HOSTS+++class DevAuthPlugin(AuthPlugin):+ """Development mode: no authentication, always ROOT.++ Only allowed when the server binds to localhost.+ """++ auth_mode = "dev"++ async def resolve_identity(+ self,+ request: Request,+ *,+ api_key: Optional[str] = None,+ x_openviking_account: Optional[str] = None,+ x_openviking_user: Optional[str] = None,+ ) -> ResolvedIdentity:+ """Dev mode: no authentication, always return ROOT."""+ return ResolvedIdentity(+ role=Role.ROOT,+ account_id=x_openviking_account or "default",+ user_id=x_openviking_user or "default",+ )++ def validate_config(self, config) -> None:+ """Dev mode is only allowed on localhost."""+ if _is_localhost(config.host):+ return+ import logging++ logger = logging.getLogger(__name__)+ logger.error(+ "SECURITY: server.auth_mode='dev' requires server.host to be localhost, "+ "but it is set to '%s'. Dev mode exposes an unauthenticated ROOT "+ "endpoint and must not be exposed to the network.",+ config.host,+ )+ logger.error(+ "To fix, either:\n"+ ' 1. Set server.auth_mode="api_key" and configure server.root_api_key, or\n'+ ' 2. Bind dev mode to localhost (server.host = "127.0.0.1")'+ )+ sys.exit(1)++ async def initialize(self, app, service, config) -> None:+ """Dev mode does not need an APIKeyManager."""+ app.state.api_key_manager = None++ def requires_api_key_manager(self) -> bool:+ return False++ def can_skip_api_key_for_bot_proxy(self) -> bool:+ return Truediff --git a/openviking/server/auth/plugins/trusted.py b/openviking/server/auth/plugins/trusted.pynew file mode 100644index 000000000..2e305103b--- /dev/null+++ b/openviking/server/auth/plugins/trusted.py@@ -0,0 +1,216 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Trusted mode authentication plugin."""++from __future__ import annotations++import hmac+import sys+from typing import Optional++from fastapi import Request++from openviking.server.api_keys import APIKeyManager+from openviking.server.auth.plugin import AuthPlugin+from openviking.server.identity import ResolvedIdentity, Role+from openviking_cli.exceptions import InvalidArgumentError, UnauthenticatedError++_LOCALHOST_HOSTS = {"127.0.0.1", "localhost", "::1"}+_TRUSTED_RELAXED_IDENTITY_PREFIXES = ("/api/v1/admin",)+++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()+ return normalized or None+ return None+++def _explicit_identity_from_request(request: Request) -> tuple[Optional[str], Optional[str]]:+ path_params = getattr(request, "path_params", {}) or {}+ query_params = request.query_params++ account_id = _normalize_request_value(path_params.get("account_id"))+ if account_id is None:+ account_id = _normalize_request_value(query_params.get("account_id"))++ user_id = _normalize_request_value(path_params.get("user_id"))+ if user_id is None:+ user_id = _normalize_request_value(query_params.get("user_id"))++ return account_id, user_id+++def _trusted_request_requires_explicit_identity(path: str) -> bool:+ if path.startswith(_TRUSTED_RELAXED_IDENTITY_PREFIXES):+ return False+ return True+++class TrustedAuthPlugin(AuthPlugin):+ """Trusted mode: trust X-OpenViking-Account/User headers.++ Optionally validates a configured root_api_key. Role is looked up from+ APIKeyManager if the user exists, otherwise defaults to USER.+ """++ auth_mode = "trusted"++ async def resolve_identity(+ self,+ request: Request,+ *,+ api_key: Optional[str] = None,+ 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."+ )++ explicit_account_id, explicit_user_id = _explicit_identity_from_request(request)+ if (+ x_openviking_account+ and explicit_account_id+ and x_openviking_account != explicit_account_id+ ):+ raise InvalidArgumentError(+ "Trusted mode X-OpenViking-Account must match explicit account_id in the URL."+ )+ if x_openviking_user and explicit_user_id and x_openviking_user != explicit_user_id:+ raise InvalidArgumentError(+ "Trusted mode X-OpenViking-User must match explicit user_id in the URL."+ )++ effective_account_id = explicit_account_id or x_openviking_account+ effective_user_id = explicit_user_id or x_openviking_user++ # Admin paths may omit identity completely, but partial identity is rejected.+ is_admin_path = request.url.path.startswith(_TRUSTED_RELAXED_IDENTITY_PREFIXES)+ if is_admin_path:+ 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 configured_root_api_key:+ return ResolvedIdentity(+ role=Role.ROOT,+ account_id=effective_account_id or "trusted",+ user_id=effective_user_id or "trusted",+ )+ 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) + "."+ )++ api_key_manager = getattr(request.app.state, "api_key_manager", None)+ trusted_role = Role.USER+ if api_key_manager and effective_account_id and effective_user_id:+ 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_role++ return ResolvedIdentity(+ role=trusted_role,+ account_id=effective_account_id or "trusted",+ user_id=effective_user_id or "trusted",+ )++ def validate_config(self, config) -> None:+ if config.root_api_key and config.root_api_key != "":+ 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")'+ )+ sys.exit(1)++ async def initialize(self, app, service, config) -> None:+ if config.root_api_key and config.root_api_key != "":+ api_key_manager = APIKeyManager(+ 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()+ app.state.api_key_manager = api_key_manager+ else:+ app.state.api_key_manager = None++ def requires_api_key_manager(self) -> bool:+ return False++ def get_request_context_checks(+ self,+ path: str,+ identity: ResolvedIdentity,+ ) -> None:+ is_admin_path = path.startswith(_TRUSTED_RELAXED_IDENTITY_PREFIXES)+ if not is_admin_path:+ if not identity.account_id:+ raise InvalidArgumentError(+ "Trusted mode requests must include X-OpenViking-Account."+ )+ if not identity.user_id:+ raise InvalidArgumentError(+ "Trusted mode requests must include X-OpenViking-User."+ )diff --git a/openviking/server/auth/registry.py b/openviking/server/auth/registry.pynew file mode 100644index 000000000..78c7b8958--- /dev/null+++ b/openviking/server/auth/registry.py@@ -0,0 +1,91 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Auth plugin registry for OpenViking multi-tenant HTTP Server."""++from __future__ import annotations++from typing import Optional, TypeVar++from openviking.server.auth.plugin import AuthPlugin+from openviking_cli.utils import get_logger++logger = get_logger(__name__)++T = TypeVar("T", bound=AuthPlugin)+++class AuthPluginRegistry:+ """Registry for authentication plugins.++ Supports decorator-based registration, programmatic registration, and+ lookup by ``auth_mode`` string.+ """++ def __init__(self) -> None:+ self._plugins: dict[str, type[AuthPlugin]] = {}++ def register(self, plugin_class: type[T]) -> type[T]:+ """Register an auth plugin class.++ Supports decorator syntax:++ @registry.register+ class MyAuthPlugin(AuthPlugin):+ auth_mode = "custom"+ ...++ Args:+ plugin_class: Concrete AuthPlugin subclass.++ Returns:+ The registered class (for decorator chaining).++ Raises:+ ValueError: If ``auth_mode`` is empty or already registered.+ """+ mode = plugin_class.auth_mode+ if not mode:+ raise ValueError(+ f"AuthPlugin {plugin_class.__name__} must define 'auth_mode'"+ )+ if mode in self._plugins:+ existing = self._plugins[mode].__name__+ raise ValueError(+ f"Auth mode {mode!r} is already registered by {existing}"+ )+ self._plugins[mode] = plugin_class+ logger.info("Registered auth plugin: %s (%s)", mode, plugin_class.__name__)+ return plugin_class++ def get(self, mode: str) -> Optional[type[AuthPlugin]]:+ """Get plugin class by auth mode string."""+ return self._plugins.get(mode)++ def list_modes(self) -> list[str]:+ """List all registered auth modes."""+ return list(self._plugins.keys())+++# Global registry instance ---------------------------------------------------++_global_registry = AuthPluginRegistry()+++def get_registry() -> AuthPluginRegistry:+ """Get the global auth plugin registry."""+ return _global_registry+++def register_auth_plugin(plugin_class: type[T]) -> type[T]:+ """Decorator to register an auth plugin in the global registry.++ Usage::++ from openviking.server.auth.registry import register_auth_plugin++ @register_auth_plugin+ class LDAPAuthPlugin(AuthPlugin):+ auth_mode = "ldap"+ ...+ """+ return _global_registry.register(plugin_class)diff --git a/openviking/server/config.py b/openviking/server/config.pyindex 88943f8f4..f063650bc 100644--- a/openviking/server/config.py+++ b/openviking/server/config.py@@ -9,6 +9,9 @@ from pydantic import BaseModel, Field, ValidationErrorfrom openviking.server.identity import AuthModefrom openviking_cli.utils import get_logger++# Import auth plugin registry for config validation+from openviking.server.auth.registry import get_registryfrom openviking_cli.utils.config.config_loader import (load_json_config,resolve_config_path,@@ -160,7 +163,7 @@ class ServerConfig(BaseModel):host: str = "127.0.0.1"port: int = 1933workers: int = 1- auth_mode: Optional[AuthMode] = None # If None, auto-detect based on root_api_key+ auth_mode: Optional[str] = None # If None, auto-detect based on root_api_keyroot_api_key: Optional[str] = Noneprofile_enabled: bool = Falsecors_origins: List[str] = Field(default_factory=lambda: ["*"])@@ -183,17 +186,17 @@ class ServerConfig(BaseModel):model_config = {"extra": "forbid"}- def get_effective_auth_mode(self) -> AuthMode:+ def get_effective_auth_mode(self) -> str:"""Get effective auth mode, auto-detecting if not explicitly set.- - If root_api_key is configured (non-empty) and auth_mode is None: API_KEY- - If root_api_key is not configured and auth_mode is None: DEV+ - If root_api_key is configured (non-empty) and auth_mode is None: api_key+ - If root_api_key is not configured and auth_mode is None: dev"""if self.auth_mode is not None:return self.auth_modeif self.root_api_key is not None and self.root_api_key != "":- return AuthMode.API_KEY- return AuthMode.DEV+ return AuthMode.API_KEY.value+ return AuthMode.DEV.valuedef load_server_config(config_path: Optional[str] = None) -> ServerConfig:@@ -234,16 +237,14 @@ def load_server_config(config_path: Optional[str] = None) -> ServerConfig:if not isinstance(server_data, dict):raise ValueError("Invalid server config: 'server' section must be an object")- # Convert auth_mode string to enum if present+ # Convert auth_mode string — built-in enums are converted to their string+ # value; custom modes are kept as-is for plugin extensibility.if "auth_mode" in server_data and isinstance(server_data["auth_mode"], str):try:- server_data["auth_mode"] = AuthMode(server_data["auth_mode"])- except ValueError as e:- valid_modes = ", ".join(repr(m.value) for m in AuthMode)- raise ValueError(- f"Invalid server.auth_mode={server_data['auth_mode']!r}. "- f"Expected one of: {valid_modes}."- ) from e+ server_data["auth_mode"] = AuthMode(server_data["auth_mode"]).value+ except ValueError:+ # Custom auth mode — keep as string for plugin registration+ pass# Get encryption enabled from config data directly (for test compatibility)encryption_enabled = data.get("encryption", {}).get("enabled", False)@@ -309,16 +310,13 @@ def load_bot_gateway_token(config_path: Optional[str] = None) -> str:def validate_server_config(config: ServerConfig) -> None:"""Validate server config for safe startup.- - **dev mode**: No authentication required, always returns ROOT identity.- Only acceptable when binding to localhost.- - **api_key mode**: Authenticates via root_api_key or user keys.- Requires root_api_key to be configured.- - **trusted mode**: Trusts X-OpenViking-Account/User headers.- Requires root_api_key when binding to non-localhost.+ Validation is delegated to the auth plugin registered for the effective+ auth_mode. Built-in plugins (dev, api_key, trusted) preserve the original+ validation behaviour.If auth_mode is not explicitly configured:- - If root_api_key is configured (non-empty): auto-select API_KEY mode- - If root_api_key is not configured: auto-select DEV mode+ - If root_api_key is configured (non-empty): auto-select api_key mode+ - If root_api_key is not configured: auto-select dev modeRaises:SystemExit: If the configuration is unsafe.@@ -333,83 +331,38 @@ def validate_server_config(config: ServerConfig) -> None:effective_auth_mode = config.get_effective_auth_mode()- if effective_auth_mode == AuthMode.DEV:- # Dev mode: no authentication, only allowed on localhost- if _is_localhost(config.host):- if config.auth_mode is None:- logger.warning(- "Dev mode (auto-detected): authentication disabled. "- "This is allowed because the server is bound to localhost (%s). "- "Do NOT expose this server to the network.",- config.host,- )- else:- logger.warning(- "Dev mode: authentication disabled. This is allowed because the "- "server is bound to localhost (%s). Do NOT expose this server "- "to the network.",- config.host,- )- return- logger.error(- "SECURITY: server.auth_mode='dev' requires server.host to be localhost, "- "but it is set to '%s'. Dev mode exposes an unauthenticated ROOT "- "endpoint and must not be exposed to the network.",- config.host,- )- logger.error(- "To fix, either:\n"- ' 1. Set server.auth_mode="api_key" and configure server.root_api_key, or\n'- ' 2. Bind dev mode to localhost (server.host = "127.0.0.1")'- )- sys.exit(1)-- if effective_auth_mode == AuthMode.TRUSTED:- if config.root_api_key and config.root_api_key != "":- return- if _is_localhost(config.host):+ # Ensure built-in plugins are registered before validation.+ # If a non-built-in plugin has already claimed a built-in mode name,+ # log a security warning and forcefully override it.+ from openviking.server.auth.plugins import DevAuthPlugin, ApiKeyAuthPlugin, TrustedAuthPlugin+ registry = get_registry()+ _BUILTIN_PLUGINS = {+ "dev": DevAuthPlugin,+ "api_key": ApiKeyAuthPlugin,+ "trusted": TrustedAuthPlugin,+ }+ for mode, plugin_cls in _BUILTIN_PLUGINS.items():+ existing = registry.get(mode)+ if existing is None:+ registry.register(plugin_cls)+ elif existing is not plugin_cls: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,+ "SECURITY: Auth mode %r was registered by %s but is being "+ "overridden by the built-in %s.",+ mode,+ existing.__name__,+ plugin_cls.__name__,)- return- 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,- )+ registry._plugins[mode] = plugin_cls++ plugin_cls = registry.get(effective_auth_mode)+ if plugin_cls is None: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")'+ "Unknown auth_mode: %r. No auth plugin registered for this mode. "+ "Registered modes: %s.",+ effective_auth_mode,+ ", ".join(registry.list_modes()),)sys.exit(1)- # AuthMode.API_KEY- if config.root_api_key and config.root_api_key != "":- if config.auth_mode is None:- logger.info("Api key mode (auto-detected): using root_api_key for authentication")- return-- # api_key mode without root_api_key is invalid - should use dev mode instead- if _is_localhost(config.host):- logger.error(- "server.auth_mode='api_key' requires server.root_api_key to be configured.\n"- 'To run without authentication on localhost, either set server.auth_mode="dev" '- "or simply remove the server.auth_mode setting to auto-detect."- )- else:- logger.error(- "SECURITY: server.auth_mode='api_key' requires server.root_api_key "- "to be configured when server.host is '%s' (non-localhost).",- config.host,- )- logger.error(- "To fix, either:\n"- " 1. Set server.root_api_key in ov.conf, or\n"- ' 2. Use server.auth_mode="dev" (localhost only)'- )- sys.exit(1)+ plugin_cls().validate_config(config)diff --git a/openviking/server/identity.py b/openviking/server/identity.pyindex c8e3621c7..277d10b59 100644--- a/openviking/server/identity.py+++ b/openviking/server/identity.py@@ -14,14 +14,60 @@ if TYPE_CHECKING:from openviking_cli.session.user_id import UserIdentifier-class Role(str, Enum):+class Role(str):+ """Role type — supports built-in roles and custom plugin-defined roles.++ Built-in roles (root/admin/user) are available as class attributes.+ Custom roles can be registered via ``Role.register(name, rank)``.++ Role comparison is string-based, so ``Role.ROOT == "root"`` and+ ``Role("custom") == "custom"`` both work.+ """+ROOT = "root"ADMIN = "admin"USER = "user"+ # Privilege ranking for role-downgrade detection.+ # Higher rank => more privilege.+ _BUILTIN_RANK: dict[str, int] = {+ USER: 0,+ ADMIN: 1,+ ROOT: 2,+ }+ _CUSTOM_RANK: dict[str, int] = {}++ @classmethod+ def register(cls, name: str, rank: int) -> None:+ """Register a custom role with a privilege rank.++ Args:+ name: Role identifier string.+ rank: Privilege rank — higher = more privilege.+ """+ cls._CUSTOM_RANK[name] = rank++ @property+ def rank(self) -> int:+ """Return the privilege rank for this role."""+ return self._BUILTIN_RANK.get(self, self._CUSTOM_RANK.get(self, 0))++ def __eq__(self, other: object) -> bool:+ if isinstance(other, Role):+ return str(self) == str(other)+ if isinstance(other, str):+ return str(self) == other+ return NotImplemented++ def __hash__(self) -> int:+ return hash(str(self))+class AuthMode(str, Enum):- """Authentication modes for OpenViking server."""+ """Authentication modes for OpenViking server.++ Built-in modes. Custom modes are plain strings not in this enum.+ """API_KEY = "api_key"TRUSTED = "trusted"diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.pyindex 3a7cc027c..e6ce66b5c 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -643,7 +643,7 @@ async def list_watches() -> str:tasks = await wm.get_all_tasks(ctx.account_id,ctx.user.user_id,- ctx.role.value,+ str(ctx.role),active_only=False,)if not tasks:@@ -679,7 +679,7 @@ async def cancel_watch(to_uri: str) -> str:to_uri,ctx.account_id,ctx.user.user_id,- ctx.role.value,+ str(ctx.role),)if task is None:return f"No watch task found for {to_uri}"@@ -694,7 +694,7 @@ async def cancel_watch(to_uri: str) -> str:task.task_id,ctx.account_id,ctx.user.user_id,- ctx.role.value,+ str(ctx.role),)except _wm_mod.PermissionDeniedError:return f"Permission denied for {to_uri}"diff --git a/openviking/server/oauth/provider.py b/openviking/server/oauth/provider.pyindex 7edbff06b..cb8055c3e 100644--- a/openviking/server/oauth/provider.py+++ b/openviking/server/oauth/provider.py@@ -33,10 +33,6 @@ from openviking.server.oauth.otp import generate_otpfrom openviking.server.oauth.storage import OAuthStorefrom openviking_cli.utils import get_logger-# Mirrors auth.py:_ROLE_RANK; duplicated here to avoid the import cycle-# (auth.py already depends on this module via the Provider Protocol).-_ROLE_RANK = {Role.USER: 0, Role.ADMIN: 1, Role.ROOT: 2}-logger = get_logger(__name__)# Access tokens carry this prefix so the auth.py bearer router can cheaply@@ -285,14 +281,14 @@ class OpenVikingOAuthProvider(if self._role_resolver is not None:try:token_role = Role(refresh_token.role)- current_role = self._role_resolver(refresh_token.account_id, refresh_token.user_id)+ current_role = Role(self._role_resolver(refresh_token.account_id, refresh_token.user_id))except (ValueError, Exception): # noqa: BLE001token_role = Nonecurrent_role = Noneif (token_role is not Noneand current_role is not None- and _ROLE_RANK[token_role] > _ROLE_RANK[current_role]+ and token_role.rank > current_role.rank):raise TokenError(error="invalid_grant",diff --git a/openviking/server/oauth/router.py b/openviking/server/oauth/router.pyindex 56e71ff1f..d40761709 100644--- a/openviking/server/oauth/router.py+++ b/openviking/server/oauth/router.py@@ -488,7 +488,7 @@ async def oauth_verify(pending_id=record["pending_id"],account_id=ctx.user.account_id,user_id=ctx.user.user_id,- role=ctx.role.value,+ role=str(ctx.role),verified_key_fp=verifier_fp,)if not ok:diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.pyindex 5776482b6..646139c1a 100644--- a/openviking/server/routers/admin.py+++ b/openviking/server/routers/admin.py@@ -83,10 +83,7 @@ def _validate_register_user_role(ctx: RequestContext, role: str) -> Role:- ADMIN may create USER or ADMIN accounts in their own account.- ROOT role assignment must go through the dedicated ROOT-only set_role endpoint."""- try:- resolved_role = Role(role)- except ValueError as exc:- raise InvalidArgumentError(f"Unsupported role for register_user: {role}") from exc+ resolved_role = Role(role)if resolved_role == Role.ROOT:raise PermissionDeniedError(@@ -268,7 +265,7 @@ async def register_user(_check_account_access(ctx, account_id)resolved_role = _validate_register_user_role(ctx, body.role)manager = _get_api_key_manager(request)- user_key = await manager.register_user(account_id, body.user_id, resolved_role.value)+ user_key = await manager.register_user(account_id, body.user_id, str(resolved_role))service = get_service()user_ctx = RequestContext(user=UserIdentifier(account_id, body.user_id),diff --git a/openviking/server/routers/bot.py b/openviking/server/routers/bot.pyindex c5c0134ba..e99d04255 100644--- a/openviking/server/routers/bot.py+++ b/openviking/server/routers/bot.py@@ -12,7 +12,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request, statusfrom fastapi.responses import StreamingResponsefrom openviking.server.auth import get_request_context-from openviking.server.identity import AuthMode, RequestContext+from openviking.server.identity import RequestContextfrom openviking_cli.utils.logger import get_loggerrouter = APIRouter(prefix="", tags=["bot"])@@ -84,12 +84,10 @@ def _attach_openviking_connection("""enriched = dict(body)api_key = _extract_forward_api_key(request)- auth_mode = AuthMode.API_KEYconfig = getattr(request.app.state, "config", None)- if config is not None and hasattr(config, "get_effective_auth_mode"):- auth_mode = config.get_effective_auth_mode()+ plugin = getattr(request.app.state, "auth_plugin", None)if not api_key:- if auth_mode == AuthMode.DEV:+ if plugin is not None and plugin.can_skip_api_key_for_bot_proxy():enriched.setdefault("user_id", ctx.user.user_id)return enrichedraise HTTPException(diff --git a/openviking/server/routers/sessions.py b/openviking/server/routers/sessions.pyindex bc173b98a..bb86b4e56 100644--- a/openviking/server/routers/sessions.py+++ b/openviking/server/routers/sessions.py@@ -12,7 +12,7 @@ from openviking.core.peer_id import normalize_peer_selectorfrom openviking.message.part import Part, TextPart, part_from_dictfrom openviking.server.auth import get_request_contextfrom openviking.server.dependencies import get_service-from openviking.server.identity import AuthMode, RequestContext+from openviking.server.identity import RequestContextfrom openviking.server.models import ErrorInfo, Responsefrom openviking.server.responses import error_responsefrom openviking.server.telemetry import run_operation@@ -172,11 +172,11 @@ def _to_jsonable(value: Any) -> Any:return value-def _request_auth_mode(request: Request) -> AuthMode:+def _request_auth_mode(request: Request) -> str:config = getattr(request.app.state, "config", None)if config is not None and hasattr(config, "get_effective_auth_mode"):return config.get_effective_auth_mode()- return AuthMode.API_KEY+ return "api_key"@router.post("")diff --git a/openviking/server/routers/system.py b/openviking/server/routers/system.pyindex 12af14117..da8952c51 100644--- a/openviking/server/routers/system.py+++ b/openviking/server/routers/system.py@@ -83,11 +83,11 @@ async def health_check(request: Request):x_openviking_user = request.headers.get("X-OpenViking-User")# Get effective auth mode from config- effective_auth_mode = AuthMode.API_KEY+ effective_auth_mode = AuthMode.API_KEY.valueconfig = getattr(request.app.state, "config", None)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.value+ result["auth_mode"] = effective_auth_modeif x_api_key or authorization:try:@@ -100,7 +100,7 @@ async def health_check(request: Request):)result["account_id"] = str(identity.account_id)result["user_id"] = str(identity.user_id)- result["role"] = identity.role.value+ result["role"] = str(identity.role)except Exception as e:logger.warning(f"Failed to resolve identity: {e}")except Exception as e:diff --git a/openviking/server/routers/watches.py b/openviking/server/routers/watches.pyindex 32ce94e9d..eb08d1d7a 100644--- a/openviking/server/routers/watches.py+++ b/openviking/server/routers/watches.py@@ -90,7 +90,7 @@ def _scheduler():def _identity(ctx: RequestContext):- return (ctx.account_id, ctx.user.user_id, ctx.role.value)+ return (ctx.account_id, ctx.user.user_id, str(ctx.role))async def _resolve_task(diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.pyindex 92edbe3a8..945b382d3 100644--- a/openviking/service/fs_service.py+++ b/openviking/service/fs_service.py@@ -318,7 +318,11 @@ class FSService:context_type: str,ctx: RequestContext,) -> None:- queue_manager = get_queue_manager()+ try:+ queue_manager = get_queue_manager()+ except RuntimeError as exc:+ logger.warning("QueueManager not available, skipping delete refresh: %s", exc)+ returnsemantic_queue = queue_manager.get_queue(queue_manager.SEMANTIC, allow_create=True)telemetry_id = get_current_telemetry().telemetry_idmsg = SemanticMsg(diff --git a/tests/server/conftest.py b/tests/server/conftest.pyindex 18ad2c5de..a2ea73576 100644--- a/tests/server/conftest.py+++ b/tests/server/conftest.py@@ -155,11 +155,20 @@ async def service(temp_dir: Path, monkeypatch):async def app(service: OpenVikingService):"""Create FastAPI app with pre-initialized service (no auth)."""from openviking.server.dependencies import set_service+ from openviking.server.auth.plugins import DevAuthPlugin+ from openviking.server.auth.registry import get_registryconfig = ServerConfig()fastapi_app = create_app(config=config, service=service)# ASGITransport doesn't trigger lifespan, so wire up the service manuallyset_service(service)+ # Manually initialize auth plugin (lifespan not triggered in ASGI tests)+ registry = get_registry()+ if registry.get("dev") is None:+ registry.register(DevAuthPlugin)+ plugin_cls = registry.get("dev")+ if plugin_cls is not None:+ fastapi_app.state.auth_plugin = plugin_cls()return fastapi_appdiff --git a/tests/server/oauth/test_auth_integration.py b/tests/server/oauth/test_auth_integration.pyindex ca52f8f3e..0108adf97 100644--- a/tests/server/oauth/test_auth_integration.py+++ b/tests/server/oauth/test_auth_integration.py@@ -30,6 +30,9 @@ def _make_request(extra_headers: Optional[dict[str, str]] = None,path: str = "/api/v1/system/status",) -> Request:+ from openviking.server.auth.plugins import ApiKeyAuthPlugin+ from openviking.server.auth.registry import get_registry+raw_headers = []if bearer:raw_headers.append((b"authorization", f"Bearer {bearer}".encode()))@@ -40,6 +43,11 @@ def _make_request(app.state.api_key_manager = api_key_managerif oauth_provider is not None:app.state.oauth_provider = oauth_provider+ # Set auth plugin (lifespan not triggered in ASGI tests)+ registry = get_registry()+ if registry.get("api_key") is None:+ registry.register(ApiKeyAuthPlugin)+ app.state.auth_plugin = registry.get("api_key")()scope = {"type": "http","path": path,diff --git a/tests/server/oauth/test_mcp_www_authenticate.py b/tests/server/oauth/test_mcp_www_authenticate.pyindex 4bb52b9b8..e2f012621 100644--- a/tests/server/oauth/test_mcp_www_authenticate.py+++ b/tests/server/oauth/test_mcp_www_authenticate.py@@ -24,9 +24,17 @@ async def _noop_app(scope, receive, send):def _build_test_app(*, oauth_enabled: bool, tmp_path=None) -> FastAPI:+ from openviking.server.auth.plugins import ApiKeyAuthPlugin+ from openviking.server.auth.registry import get_registry+app = FastAPI()app.state.config = ServerConfig(auth_mode="api_key", root_api_key="root-test-1234567890abcd")app.state.api_key_manager = object() # presence triggers API_KEY auth path+ # Set auth plugin (lifespan not triggered in ASGI tests)+ registry = get_registry()+ if registry.get("api_key") is None:+ registry.register(ApiKeyAuthPlugin)+ app.state.auth_plugin = registry.get("api_key")()if oauth_enabled:# Provider just needs to exist on app.state to flag oauth as enabled —# the bearer middleware emits WWW-Authenticate based on its presence,diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.pyindex 3a7edec2e..ffb225499 100644--- a/tests/server/test_admin_api.py+++ b/tests/server/test_admin_api.py@@ -82,6 +82,8 @@ class _FakeService:def _build_lightweight_admin_test_app() -> FastAPI:from openviking.server.routers import admin as admin_router+ from openviking.server.auth.plugins import ApiKeyAuthPlugin+ from openviking.server.auth.registry import get_registryapp = FastAPI()app.state.config = ServerConfig(root_api_key=ROOT_KEY)@@ -101,6 +103,13 @@ def _build_lightweight_admin_test_app() -> FastAPI:manager = APIKeyManager(root_key=ROOT_KEY, viking_fs=fake_service.viking_fs)app.state.api_key_manager = manager++ # Set auth plugin (lifespan not triggered in ASGI tests)+ registry = get_registry()+ if registry.get("api_key") is None:+ registry.register(ApiKeyAuthPlugin)+ app.state.auth_plugin = registry.get("api_key")()+app.include_router(admin_router.router)return app@@ -131,6 +140,9 @@ async def admin_service(temp_dir):@pytest_asyncio.fixture(scope="function")async def admin_app(admin_service):+ from openviking.server.auth.plugins import ApiKeyAuthPlugin+ from openviking.server.auth.registry import get_registry+config = ServerConfig(root_api_key=ROOT_KEY)app = create_app(config=config, service=admin_service)set_service(admin_service)@@ -139,6 +151,12 @@ async def admin_app(admin_service):await manager.load()app.state.api_key_manager = manager+ # Set auth plugin (lifespan not triggered in ASGI tests)+ registry = get_registry()+ if registry.get("api_key") is None:+ registry.register(ApiKeyAuthPlugin)+ app.state.auth_plugin = registry.get("api_key")()+return app@@ -1035,6 +1053,9 @@ async def test_legacy_agent_and_session_uri_reads_are_read_only(@pytest_asyncio.fixture(scope="function")async def trusted_admin_app(admin_service):+ from openviking.server.auth.plugins import TrustedAuthPlugin+ from openviking.server.auth.registry import get_registry+config = ServerConfig(auth_mode="trusted", root_api_key=ROOT_KEY)app = create_app(config=config, service=admin_service)set_service(admin_service)@@ -1044,6 +1065,13 @@ async def trusted_admin_app(admin_service):if "platform" not in manager._accounts:await manager.create_account("platform", "gateway-admin")app.state.api_key_manager = manager++ # Set auth plugin (lifespan not triggered in ASGI tests)+ registry = get_registry()+ if registry.get("trusted") is None:+ registry.register(TrustedAuthPlugin)+ app.state.auth_plugin = registry.get("trusted")()+return appdiff --git a/tests/server/test_auth.py b/tests/server/test_auth.pyindex 9ffbf2b08..ad4375ea1 100644--- a/tests/server/test_auth.py+++ b/tests/server/test_auth.py@@ -15,6 +15,7 @@ from starlette.requests import Requestfrom openviking.server.app import create_appfrom openviking.server.auth import get_request_context, resolve_identity+from openviking.server.auth.registry import get_registryfrom openviking.server.config import ServerConfig, _is_localhost, validate_server_configfrom openviking.server.dependencies import set_servicefrom openviking.server.identity import ResolvedIdentity, Role@@ -88,14 +89,24 @@ def _make_request(api_key_manager=None,) -> Request:"""Create a minimal Starlette request for auth dependency tests."""+ # Ensure built-in plugins are registered+ from openviking.server.auth.plugins import DevAuthPlugin, ApiKeyAuthPlugin, TrustedAuthPlugin+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, root_api_key=root_api_key)+ # When auth is disabled and mode is the default api_key, fall back to dev mode+ effective_auth_mode = auth_mode if auth_enabled or auth_mode != "api_key" else "dev"+ app.state.config = ServerConfig(auth_mode=effective_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 = api_key_manager if api_key_manager is not None else object()+ # Set auth plugin based on mode+ registry = get_registry()+ plugin_cls = registry.get(effective_auth_mode)+ if plugin_cls is not None:+ app.state.auth_plugin = plugin_cls()scope = {"type": "http","path": path,@@ -117,11 +128,21 @@ def _build_auth_http_test_app(The full server fixture depends on AGFS native libraries. This helper keepsthe test focused on request auth behavior and the structured HTTP error body."""+ # Ensure built-in plugins are registered+ from openviking.server.auth.plugins import DevAuthPlugin, ApiKeyAuthPlugin, TrustedAuthPlugin+app = FastAPI()- app.state.config = ServerConfig(auth_mode=auth_mode, root_api_key=root_api_key)+ # When auth is disabled and mode is the default api_key, fall back to dev mode+ effective_auth_mode = auth_mode if auth_enabled or auth_mode != "api_key" else "dev"+ app.state.config = ServerConfig(auth_mode=effective_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()+ # Set auth plugin based on mode+ registry = get_registry()+ plugin_cls = registry.get(effective_auth_mode)+ if plugin_cls is not None:+ app.state.auth_plugin = plugin_cls()@app.exception_handler(OpenVikingError)async def openviking_error_handler(request: FastAPIRequest, exc: OpenVikingError):@@ -160,17 +181,17 @@ def _build_auth_http_test_app(@app.get("/api/v1/observer/system")async def observer_system(ctx=Depends(get_request_context)):"""Expose a monitoring route that should keep implicit ROOT behavior."""- return {"status": "ok", "result": {"role": ctx.role.value}}+ return {"status": "ok", "result": {"role": str(ctx.role)}}@app.post("/api/v1/system/wait")async def system_wait(ctx=Depends(get_request_context)):"""Expose a non-tenant system route for auth regression tests."""- return {"status": "ok", "result": {"role": ctx.role.value}}+ return {"status": "ok", "result": {"role": str(ctx.role)}}@app.get("/api/v1/debug/vector/scroll")async def debug_vector_scroll(ctx=Depends(get_request_context)):"""Expose a tenant-scoped debug route for auth regression tests."""- return {"status": "ok", "result": {"role": ctx.role.value}}+ return {"status": "ok", "result": {"role": str(ctx.role)}}@app.get("/api/v1/test/accounts/{account_id}/users/{user_id}")async def trusted_identity_from_url(@@ -214,6 +235,8 @@ async def auth_service(temp_dir):async def auth_app(auth_service):"""App with root_api_key configured and APIKeyManager loaded."""from openviking.server.api_keys import APIKeyManager+ from openviking.server.auth.plugins import ApiKeyAuthPlugin+ from openviking.server.auth.registry import get_registryconfig = ServerConfig(root_api_key=ROOT_KEY)app = create_app(config=config, service=auth_service)@@ -224,6 +247,14 @@ async def auth_app(auth_service):await manager.load()app.state.api_key_manager = manager+ # Manually initialize auth plugin (lifespan not triggered in ASGI tests)+ registry = get_registry()+ if registry.get("api_key") is None:+ registry.register(ApiKeyAuthPlugin)+ plugin_cls = registry.get("api_key")+ plugin = plugin_cls()+ app.state.auth_plugin = plugin+return app@@ -1326,7 +1357,7 @@ async def test_trusted_mode_admin_api_http_route_without_identity():return {"status": "ok","result": {- "role": ctx.role.value,+ "role": str(ctx.role),"account_id": ctx.user.account_id,"user_id": ctx.user.user_id,},