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/account store provider (#5933)
runyunzhou90df1454744f
diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.mdindex 628ccc24f..d396b9a0d 100644--- a/docs/en/api/08-admin.md+++ b/docs/en/api/08-admin.md@@ -1487,7 +1487,7 @@ List active users in a workspace. Users with deletion in progress are omitted.| role | str | No | null | Filter by role || query | str | No | null | HTTP-only, case-insensitive literal substring match on user IDs || include_summary | bool | No | false | HTTP-only, return paginated users and account statistics in an object |-| include_credentials | bool | No | true | HTTP-only. Set false to return `user_id`, `role`, and `api_key_available` without credentials or key prefixes. The default preserves the existing mode-dependent response. |+| include_credentials | bool | No | true | HTTP-only. Set false to return `user_id`, `role`, and `api_key_available` without credentials or key prefixes. `api_key_available` is true only when the server can read the complete key for a server-side binding; hash-only credentials return false. The default preserves the existing mode-dependent response. || limit | int | No | null | Page size (≥1). Omit to return all matches || page | int | No | 1 | 1-based page number; only applies when `limit` is set |diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.mdindex 932557caf..0d47386b3 100644--- a/docs/en/guides/01-configuration.md+++ b/docs/en/guides/01-configuration.md@@ -1891,6 +1891,10 @@ When running OpenViking as an HTTP service, add a `server` section to `ov.conf`:"port": 1933,"auth_mode": "api_key","root_api_key": "your-secret-root-key",+ "account_store": {+ "provider": "file",+ "params": {}+ },"profile_enabled": false,"cors_origins": ["*"],"public_base_url": "https://ov.example.com",@@ -1922,6 +1926,8 @@ When running OpenViking as an HTTP service, add a `server` section to `ov.conf`:| `port` | int | Bind port | `1933` || `auth_mode` | str / null | Built-in modes: `"dev"`, `"api_key"`, `"trusted"`, `"oidc"`, `"ldap"`. When omitted/null, infer `api_key` from a non-empty `root_api_key`; otherwise infer `dev`. | `null` || `root_api_key` | str | Root API key for multi-tenant auth in `api_key` mode. In `trusted` mode it is required on every deployment, including localhost; it does not become the source of user identity | `null` |+| `account_store.provider` | str | Complete Account store provider. The built-in `"file"` provider owns account, user, group, and API-key records while preserving the existing AGFS JSON registry and process-local lookup indexes. | `"file"` |+| `account_store.params` | object | Provider-specific startup parameters. Framework-owned filesystem and File-provider API-key hashing dependencies cannot be overridden here. | `{}` || `profile_enabled` | bool | Whether to allow request-scoped cProfile via `profile=1` on HTTP requests. When disabled, the server ignores that query parameter. When enabled, the CLI can display the returned `profile`, while the Python HTTP client currently triggers profiling but does not automatically attach the top-level `profile` field to most SDK return values. | `false` || `cors_origins` | list | Allowed CORS origins | `["*"]` || `public_base_url` | str | Public-facing base URL emitted in MCP-issued upload instructions. Resolution order: env var `OPENVIKING_PUBLIC_BASE_URL` → this field → `X-Forwarded-Host`/`X-Forwarded-Proto` request headers → `Host` request header → listen-address fallback. Set this (or the env var) when the server runs behind a reverse proxy that does not forward `X-Forwarded-*` headers. | `null` |@@ -1937,7 +1943,7 @@ When running OpenViking as an HTTP service, add a `server` section to `ov.conf`:Omitting `auth_mode` (or setting it to `null`) selects `api_key` when a non-empty `root_api_key` is configured, and `dev` otherwise. `dev` is allowed only on localhost and accepts requests without authentication. An empty-string `root_api_key` is invalid.-Explicit `auth_mode: "api_key"` requires a non-empty `root_api_key`, including on localhost; without it, startup fails instead of falling back to development mode. Use the root key with the Admin API to create accounts and user/admin keys; use those tenant-bound keys for data access. `trusted` mode accepts account/user identity headers from a trusted gateway and does not require user-key provisioning first. Its non-empty root key is required for startup and authenticated requests on every bind address, including localhost. For role resolution, OIDC/LDAP setup, and gateway requirements, see [Authentication](04-authentication.md).+Explicit `auth_mode: "api_key"` requires a non-empty `root_api_key`, including on localhost; without it, startup fails instead of falling back to development mode. Use the root key with the Admin API to create accounts and user/admin keys; use those tenant-bound keys for data access. `trusted` mode accepts account/user identity headers from a trusted gateway and does not require user-key provisioning first. Its root key is required for startup and every authenticated request, including on localhost. For role resolution, OIDC/LDAP setup, and gateway requirements, see [Authentication](04-authentication.md).`user_config_defaults` provides deployment defaults for add targets and memory extraction. For add operations, explicit request targets still win: `add_resource.to` / `add_resource.parent` take precedence over user defaults, and `add_skill.target_uri` takes precedence over user defaults. Memory policy precedence is Session policy > User `settings/user_config.json` policy > `server.user_config_defaults.memory_policy` > kernel default. `server.agent_evolution.enabled` supplies the startup default. Runtime resolution is Account override > Cluster runtime override > that startup value. Use the Admin settings APIs for changes without restarting; editing `ov.conf` directly takes effect after restart.@@ -2105,7 +2111,7 @@ At-rest encryption protects newly written files with account-specific keys throu|-----------|------|-------------|---------|| `enabled` | bool | Whether encryption is enabled | `false` || `provider` | str | Key provider: `"local"`, `"vault"`, or `"volcengine_kms"` | - |-| `api_key_hashing.enabled` | bool | Whether to apply Argon2id one-way hashing to API key values (independent of file-level `enabled`); see [Encryption Guide](./08-encryption.md) | `false` |+| `api_key_hashing.enabled` | bool | File-provider only: whether to apply Argon2id one-way hashing to API key values (independent of file-level `enabled`); see [Encryption Guide](./08-encryption.md) | `false` |### Local (File)@@ -2263,6 +2269,10 @@ This illustrates the main sections, not a complete runnable configuration or JSO"host": "127.0.0.1","port": 1933,"root_api_key": "string",+ "account_store": {+ "provider": "file",+ "params": {}+ },"cors_origins": ["*"]}}diff --git a/docs/en/guides/04-authentication.md b/docs/en/guides/04-authentication.mdindex 9622ccd2b..151b681c7 100644--- a/docs/en/guides/04-authentication.md+++ b/docs/en/guides/04-authentication.md@@ -660,7 +660,6 @@ The server uses a plugin-based auth architecture. Each `auth_mode` maps to an `A| `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 Plugindiff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.mdindex 5ca2c911e..005b3b567 100644--- a/docs/zh/api/08-admin.md+++ b/docs/zh/api/08-admin.md@@ -1356,7 +1356,7 @@ ov admin register-user acme bob-private --role user \| role | str | 否 | null | 按角色过滤 || query | str | 否 | null | 仅 HTTP,按用户 ID 做不区分大小写的字面包含匹配 || include_summary | bool | 否 | false | 仅 HTTP,以对象返回分页用户和账号统计 |-| include_credentials | bool | 否 | true | 仅 HTTP。设为 false 时仅返回 `user_id`、`role` 和 `api_key_available`,不返回密钥或前缀;默认保持现有按鉴权模式返回字段的行为。 |+| include_credentials | bool | 否 | true | 仅 HTTP。设为 false 时仅返回 `user_id`、`role` 和 `api_key_available`,不返回密钥或前缀;仅当服务端能读取完整 key 并用于服务端绑定时 `api_key_available` 才为 true,仅存哈希的凭据返回 false;默认保持现有按鉴权模式返回字段的行为。 || limit | int | 否 | null | 每页数量(≥1)。省略则返回所有匹配项 || page | int | 否 | 1 | 从 1 开始的页码;仅在设置了 `limit` 时生效 |diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.mdindex 59324bb0a..12dd465be 100644--- a/docs/zh/guides/01-configuration.md+++ b/docs/zh/guides/01-configuration.md@@ -1881,6 +1881,10 @@ ov add-resource ./docs --exclude "*.tmp""port": 1933,"auth_mode": "api_key","root_api_key": "your-secret-root-key",+ "account_store": {+ "provider": "file",+ "params": {}+ },"profile_enabled": false,"cors_origins": ["*"],"public_base_url": "https://ov.example.com",@@ -1912,6 +1916,8 @@ ov add-resource ./docs --exclude "*.tmp"| `port` | int | 绑定端口 | `1933` || `auth_mode` | str / null | 内置模式:`"dev"`、`"api_key"`、`"trusted"`、`"oidc"`、`"ldap"`。省略或设为 null 时,有非空 `root_api_key` 则推导为 `api_key`,否则为 `dev`。 | `null` || `root_api_key` | str | `api_key` 模式必填的 Root API Key;`trusted` 模式在所有部署中均必填,包括 localhost,不负责解析普通用户身份 | `null` |+| `account_store.provider` | str | 完整 Account Store Provider。内置 `"file"` Provider,统一持久化 Account、User、Group 和 API Key,兼容现有 AGFS JSON 注册表并维护进程内查询索引。 | `"file"` |+| `account_store.params` | object | Provider 启动参数。不能通过这里覆盖框架注入的 VikingFS 和 File Provider API Key Hash 配置。 | `{}` || `profile_enabled` | bool | 是否允许 HTTP 请求通过 `profile=1` 开启请求级 cProfile。关闭时服务端会忽略该请求参数;开启后,CLI 可以显示返回的 `profile`,而 Python HTTP client 默认只触发服务端 profile,不会把顶层 `profile` 字段自动附着到大多数 SDK 返回值上。 | `false` || `cors_origins` | list | CORS 允许的来源 | `["*"]` || `public_base_url` | str | MCP `add_resource` 和 `add_skill` 工具向客户端返回的上传指令里使用的对外可见 base URL。解析顺序:环境变量 `OPENVIKING_PUBLIC_BASE_URL` → 本字段 → 请求头 `X-Forwarded-Host` / `X-Forwarded-Proto` → 请求头 `Host` → 监听地址兜底。当 server 部署在反向代理后且代理不转发 `X-Forwarded-*` 时,请显式设置本字段(或环境变量)。 | `null` |@@ -1927,7 +1933,7 @@ ov add-resource ./docs --exclude "*.tmp"省略 `auth_mode`(或设为 `null`)时,配置了非空 `root_api_key` 则选择 `api_key`,否则选择 `dev`。`dev` 仅允许监听 localhost,不进行身份认证。`root_api_key` 不能配置为空字符串。-显式设置 `auth_mode: "api_key"` 时,包括 localhost 在内都必须提供非空 `root_api_key`;缺少该 key 会导致启动失败,不会回退到开发模式。使用 root key 调用 Admin API 创建 account 和 user/admin key,数据访问使用这些绑定租户身份的 key。`trusted` 模式接受可信网关注入的 account/user 身份头,无需预先创建 user key;其非空 root key 是启动和认证请求的必要条件,包括 localhost。角色解析、OIDC/LDAP 配置与网关要求参见 [身份认证](04-authentication.md)。+显式设置 `auth_mode: "api_key"` 时,包括 localhost 在内都必须提供非空 `root_api_key`;缺少该 key 会导致启动失败,不会回退到开发模式。使用 root key 调用 Admin API 创建 account 和 user/admin key,数据访问使用这些绑定租户身份的 key。`trusted` 模式接受可信网关注入的 account/user 身份头,无需预先创建 user key;其 root key 在启动和每个认证请求中均必填,包括 localhost。角色解析、OIDC/LDAP 配置与网关要求参见 [身份认证](04-authentication.md)。`user_config_defaults` 提供添加目标和记忆抽取的部署级默认配置。添加操作中,显式请求目标仍然优先:`add_resource.to` / `add_resource.parent` 优先于用户默认值,`add_skill.target_uri` 优先于用户默认值。记忆策略优先级为 Session 策略 > User `settings/user_config.json` 策略 > `server.user_config_defaults.memory_policy` > 内核默认策略。`server.agent_evolution.enabled` 提供启动默认值,运行时优先级为 Account 覆盖 > Cluster 运行时覆盖 > 启动值。无需重启的修改应使用 Admin settings 接口;直接编辑 `ov.conf` 需要重启后生效。@@ -2043,7 +2049,7 @@ ov add-resource ./docs --exclude "*.tmp"|------|------|------|--------|| `enabled` | bool | 是否启用加密 | `false` || `provider` | str | 密钥提供程序:`"local"`、`"vault"` 或 `"volcengine_kms"` | - |-| `api_key_hashing.enabled` | bool | 是否对 API key 字段启用 Argon2id 单向哈希(与文件级 `enabled` 独立控制),详见 [加密指南](./08-encryption.md) | `false` |+| `api_key_hashing.enabled` | bool | 仅 File Provider:是否对 API key 字段启用 Argon2id 单向哈希(与文件级 `enabled` 独立控制),详见 [加密指南](./08-encryption.md) | `false` |### Local(本地文件)@@ -2252,6 +2258,10 @@ Task 记录文件位于所属账号的系统目录:"host": "string","port": 1933,"root_api_key": "string",+ "account_store": {+ "provider": "file",+ "params": {}+ },"cors_origins": ["string"]}}diff --git a/docs/zh/guides/04-authentication.md b/docs/zh/guides/04-authentication.mdindex 2e03456c7..1dcbbc416 100644--- a/docs/zh/guides/04-authentication.md+++ b/docs/zh/guides/04-authentication.md@@ -400,7 +400,6 @@ OIDC Claims: {| `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` 模式) |### 注册自定义插件示例diff --git a/openviking/server/account_stores/__init__.py b/openviking/server/account_stores/__init__.pynew file mode 100644index 000000000..bbe694789--- /dev/null+++ b/openviking/server/account_stores/__init__.py@@ -0,0 +1,7 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Storage contracts for account and API key data."""++from openviking.server.account_stores.base import AccountStore++__all__ = ["AccountStore"]diff --git a/openviking/server/account_stores/base.py b/openviking/server/account_stores/base.pynew file mode 100644index 000000000..8cb5dc627--- /dev/null+++ b/openviking/server/account_stores/base.py@@ -0,0 +1,187 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Asynchronous account and API key persistence contract."""++from abc import ABC, abstractmethod++from typing_extensions import deprecated++from openviking.server.account_stores.models import (+ AccountSummary,+ DeletionRecord,+ GroupSummary,+ UsersPage,+ UserSummary,+)+++class AccountStore(ABC):+ """Nominal contract implemented by every complete account store provider."""++ @abstractmethod+ async def load(self) -> None: ...++ @abstractmethod+ async def close(self) -> None: ...++ # Account+ @abstractmethod+ async def get_account(self, account_id: str) -> AccountSummary | None: ...++ @abstractmethod+ async def create_account(+ self,+ account_id: str,+ admin_user_id: str,+ ) -> None: ...++ @abstractmethod+ async def create_account_with_api_key(+ self,+ account_id: str,+ admin_user_id: str,+ api_key: str,+ ) -> None: ...++ @abstractmethod+ async def delete_account(self, account_id: str) -> None: ...++ @abstractmethod+ async def list_accounts(+ self,+ name_filter: str | None = None,+ limit: int | None = None,+ page: int = 1,+ query_filter: str | None = None,+ ) -> list[AccountSummary]: ...++ # User+ @abstractmethod+ async def get_user(self, account_id: str, user_id: str) -> UserSummary | None: ...++ @deprecated(+ "get_user_for_management is a FileStore compatibility path and will be removed.",+ category=None,+ )+ async def get_user_for_management(+ self, account_id: str, user_id: str+ ) -> UserSummary | None:+ """Return one user for an explicit management read."""+ return await self.get_user(account_id, user_id)++ @abstractmethod+ async def create_user(self, account_id: str, user_id: str, role: str) -> None: ...++ @abstractmethod+ async def create_user_with_api_key(+ self,+ account_id: str,+ user_id: str,+ role: str,+ api_key: str,+ ) -> None: ...++ @abstractmethod+ async def list_users_page(+ self,+ account_id: str,+ limit: int | None = 100,+ name_filter: str | None = None,+ role_filter: str | None = None,+ page: int = 1,+ query_filter: str | None = None,+ fresh: bool = False,+ ) -> UsersPage: ...++ @abstractmethod+ async def set_role(self, account_id: str, user_id: str, role: str) -> None: ...++ # Group+ @abstractmethod+ async def create_group(self, account_id: str, group_id: str) -> GroupSummary: ...++ @abstractmethod+ async def get_groups(self, account_id: str) -> list[GroupSummary]: ...++ @abstractmethod+ async def get_group_members(self, account_id: str, group_id: str) -> list[str]: ...++ @abstractmethod+ async def get_user_group_ids(self, account_id: str, user_id: str) -> tuple[str, ...]: ...++ @abstractmethod+ async def add_group_member(self, account_id: str, group_id: str, user_id: str) -> bool: ...++ @abstractmethod+ async def remove_group_member(self, account_id: str, group_id: str, user_id: str) -> bool: ...++ @abstractmethod+ async def delete_group(self, account_id: str, group_id: str) -> None: ...++ # Provisioning+ @abstractmethod+ async def ensure_trusted_identities(+ self, identities: dict[str, set[str]]+ ) -> dict[str, int]: ...++ # Deletion+ @abstractmethod+ async def begin_deletion(+ self,+ account_id: str,+ user_id: str | None,+ *,+ task_id: str,+ owner_account_id: str,+ owner_user_id: str,+ ) -> tuple[DeletionRecord, bool]: ...++ @abstractmethod+ async def replace_deletion_task(+ self,+ account_id: str,+ user_id: str | None,+ *,+ expected_task_id: str,+ task_id: str,+ owner_account_id: str,+ owner_user_id: str,+ ) -> DeletionRecord: ...++ @abstractmethod+ async def finish_deletion(self, account_id: str, user_id: str | None, task_id: str) -> bool: ...++ @abstractmethod+ async def get_deletion(+ self, account_id: str, user_id: str | None = None+ ) -> DeletionRecord | None: ...++ @abstractmethod+ async def iter_deletions(+ self,+ ) -> list[tuple[str, str | None, DeletionRecord]]: ...++ # Authentication+ @abstractmethod+ async def verify_api_key(+ self,+ api_key: str,+ *,+ account_id_hint: str | None = None,+ user_id_hint: str | None = None,+ ) -> tuple[str, str] | None: ...++ # Credentials+ @abstractmethod+ async def replace_active_user_api_key(+ self,+ account_id: str,+ user_id: str,+ api_key: str,+ ) -> None: ...++ @abstractmethod+ async def revoke_active_api_keys(self, account_id: str, user_id: str | None = None) -> None: ...++ @abstractmethod+ async def get_user_key_fingerprint(self, account_id: str, user_id: str) -> str | None: ...diff --git a/openviking/server/account_stores/models.py b/openviking/server/account_stores/models.pynew file mode 100644index 000000000..360da34f4--- /dev/null+++ b/openviking/server/account_stores/models.py@@ -0,0 +1,38 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Data structures returned by account storage operations."""+from typing import TypedDict+++class DeletionRecord(TypedDict, total=False):+ task_id: str+ owner_account_id: str+ owner_user_id: str+++class AccountSummary(TypedDict, total=False):+ account_id: str+ created_at: str+ user_count: int+ status: str+ task_id: str+++class UserSummary(TypedDict, total=False):+ user_id: str+ role: str+ api_key: str+ key_prefix: str+++class UsersPage(TypedDict):+ users: list[UserSummary]+ total: int+ account_total: int+ manager_count: int+ key_count: int+++class GroupSummary(TypedDict):+ group_id: str+ member_count: intdiff --git a/openviking/server/account_user_keys.py b/openviking/server/account_user_keys.pyindex a91d4c09a..af84ba246 100644--- a/openviking/server/account_user_keys.py+++ b/openviking/server/account_user_keys.py@@ -6,9 +6,15 @@ from fastapi import HTTPExceptionasync def list_account_users(registry, account_id, role=None, *, expose_key=True):- """Refresh account users, exposing readable keys only when requested."""- await registry.refresh_account_users_from_store(account_id)- return registry.get_users(account_id, limit=None, role_filter=role, expose_key=expose_key)+ """List users from the authoritative store, exposing readable keys when requested."""+ page = await registry.list_users_page(+ account_id,+ limit=None,+ role_filter=role,+ expose_key=expose_key,+ fresh=True,+ )+ return page["users"]def pick_account_user(rows, user_id, *, missing, unreadable, require_key=True):diff --git a/openviking/server/api_keys/__init__.py b/openviking/server/api_keys/__init__.pyindex 1ae104348..0d39d1c35 100644--- a/openviking/server/api_keys/__init__.py+++ b/openviking/server/api_keys/__init__.py@@ -1,19 +1,9 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""Unified API Key management with support for both legacy and new formats.+"""API key management facade over complete account stores."""-This module exports APIKeyManager which internally uses NewAPIKeyManager that:-- Generates new keys in the new format: base64url(account_id).base64url(user_id).base64url(secret)-- Can resolve both legacy and new format keys-- Maintains full backward compatibility-"""--# Also export legacy components for reference-from openviking.server.api_keys.legacy import LegacyAPIKeyManager-from openviking.server.api_keys.new import (- NewAPIKeyManager as APIKeyManager,-)from openviking.server.api_keys.new import (+ APIKeyManager,generate_api_key,is_new_format_key,parse_api_key,@@ -21,7 +11,6 @@ from openviking.server.api_keys.new import (__all__ = ["APIKeyManager",- "LegacyAPIKeyManager","is_new_format_key","parse_api_key","generate_api_key",diff --git a/openviking/server/api_keys/legacy.py b/openviking/server/api_keys/legacy.pyindex c5ddcaa38..32eef5169 100644--- a/openviking/server/api_keys/legacy.py+++ b/openviking/server/api_keys/legacy.py@@ -1,6 +1,6 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""Legacy API Key management (original implementation)."""+"""File-backed account and API key store over the AGFS registry layout."""import asyncioimport copy@@ -8,21 +8,29 @@ import fnmatchimport hashlibimport hmacimport json-import secretsfrom datetime import datetime, timezonefrom typing import Dict, Optionalfrom argon2 import PasswordHasher-from argon2.exceptions import VerifyMismatchError+from argon2.exceptions import VerificationError+from typing_extensions import deprecatedfrom openviking.pyagfs import AGFSAlreadyExistsError, AGFSNotFoundError, AsyncAGFSClientfrom openviking.pyagfs.async_client import fs_ctx_from_agfs_path+from openviking.server.account_stores.base import AccountStore+from openviking.server.account_stores.models import (+ AccountSummary,+ DeletionRecord,+ GroupSummary,+ UsersPage,+ UserSummary,+)from openviking.server.api_keys.models import (AccountInfo,UserKeyEntry,validate_account_user_role,)-from openviking.server.identity import ResolvedIdentity, Role+from openviking.server.identity import Rolefrom openviking.storage.errors import LockAcquisitionError, ResourceBusyErrorfrom openviking.storage.viking_fs import VikingFSfrom openviking_cli.exceptions import (@@ -30,7 +38,6 @@ from openviking_cli.exceptions import (FailedPreconditionError,InvalidArgumentError,NotFoundError,- UnauthenticatedError,)from openviking_cli.session.user_id import (validate_account_id,@@ -79,43 +86,62 @@ def _paginate(items: list, limit: int | None, page: int) -> list:return items[start : start + limit]-class LegacyAPIKeyManager:- """Manages API keys for multi-tenant authentication (legacy implementation)."""+class FileStore(AccountStore):+ """File-backed account and API key store over the legacy AGFS layout."""def __init__(self,- root_key: str,viking_fs: VikingFS,+ *,+ params: dict[str, object] | None = None,api_key_hashing_enabled: bool = False,+ watch_enabled: bool = False,+ watch_interval_seconds: float = 30.0,):- """Initialize APIKeyManager.+ params = dict(params or {})+ reserved = {+ "viking_fs",+ "api_key_hashing_enabled",+ }+ if overridden := reserved.intersection(params):+ names = ", ".join(sorted(overridden))+ raise InvalidArgumentError(+ f"account_store.params cannot override framework parameters: {names}"+ )+ configured_watch_enabled = params.pop("watch_enabled", watch_enabled)+ configured_watch_interval = params.pop(+ "watch_interval_seconds", watch_interval_seconds+ )+ if not isinstance(configured_watch_enabled, bool):+ raise InvalidArgumentError("watch_enabled must be a boolean")+ if not isinstance(configured_watch_interval, (int, float)):+ raise InvalidArgumentError("watch_interval_seconds must be a number")+ if params:+ raise InvalidArgumentError(+ f"Unknown file account store parameters: {', '.join(sorted(params))}"+ )- Args:- root_key: Global root API key for administrative access.- viking_fs: VikingFS client for persistent storage of user keys.- api_key_hashing_enabled: Whether API key Argon2id hashing is enabled.- Default: false - rely on file-level AES encryption for protection.- """- self._root_key = root_keyself._viking_fs = viking_fsself._async_agfs = AsyncAGFSClient(viking_fs.agfs)self._api_key_hashing_enabled = api_key_hashing_enabled+ self._watch_enabled = configured_watch_enabled+ self._watch_interval_seconds = (+ float(configured_watch_interval)+ if configured_watch_interval > 0+ else 30.0+ )+ self._watch_task: Optional[asyncio.Task] = Noneself._accounts: Dict[str, AccountInfo] = {}# Prefix index: key_prefix -> list[UserKeyEntry]self._prefix_index: Dict[str, list[UserKeyEntry]] = {}self._user_group_ids: Dict[tuple[str, str], tuple[str, ...]] = {}- self._identity_registry_signatures: dict[str | None, tuple] = {}- # Serializes reload() so overlapping refreshes can't interleave.+ # Serializes internal refreshes so overlapping reloads can't interleave.self._reload_lock = asyncio.Lock()# Serializes all mutations made by the unified manager in this process.# File locks remain responsible for inter-instance coordination.self._mutation_lock = asyncio.Lock()self._deletion_lock = asyncio.Lock()- @property- def mutation_lock(self) -> asyncio.Lock:- return self._mutation_lock-def _discard_account_state(self, account_id: str) -> None:"""Remove an account and its key index entries from in-memory state."""account = self._accounts.pop(account_id, None)@@ -169,15 +195,59 @@ class LegacyAPIKeyManager:self._accounts = accountsself._prefix_index = prefix_indexself._user_group_ids = user_group_ids- await self._update_identity_registry_signatures()-logger.info(- "LegacyAPIKeyManager loaded: %d accounts, %d user keys",+ "FileStore loaded: %d accounts, %d user keys",len(self._accounts),sum(len(info.users) for info in self._accounts.values()),)+ self._start_watcher()++ def _start_watcher(self) -> None:+ if not self._watch_enabled or self._watch_task is not None:+ return+ self._watch_task = asyncio.create_task(self._watch_store())+ logger.info(+ "FileStore watcher started (interval=%.1fs)",+ self._watch_interval_seconds,+ )++ async def close(self) -> None:+ if self._watch_task is None:+ return+ self._watch_task.cancel()+ try:+ await self._watch_task+ except asyncio.CancelledError:+ pass+ finally:+ self._watch_task = None++ async def _watch_store(self) -> None:+ try:+ last_signature = await self._compute_store_signature()+ except Exception:+ logger.warning(+ "Initial account store signature failed; watcher will retry", exc_info=True+ )+ last_signature = None- async def reload(self) -> None:+ while True:+ await asyncio.sleep(self._watch_interval_seconds)+ try:+ signature = await self._compute_store_signature()+ except Exception:+ logger.debug("Account store signature check failed", exc_info=True)+ continue+ if signature == last_signature:+ continue+ try:+ await self._reload()+ last_signature = signature+ logger.info("Account store change detected; provider cache reloaded")+ except Exception:+ logger.warning("Account store reload failed; will retry", exc_info=True)++ async def _reload(self) -> None:"""Read-only refresh: re-read store and atomically swap state (never writes/migrates)."""async with self._mutation_lock:await self._reload_unlocked()@@ -197,31 +267,12 @@ class LegacyAPIKeyManager:self._accounts = accountsself._prefix_index = prefix_indexself._user_group_ids = user_group_ids- await self._update_identity_registry_signatures()-logger.debug(- "LegacyAPIKeyManager reloaded: %d accounts, %d user keys",+ "FileStore reloaded: %d accounts, %d user keys",len(self._accounts),sum(len(info.users) for info in self._accounts.values()),)- async def refresh_identity_registry_if_changed(- self, account_id: str | None = None- ) -> bool:- """Reload registry state only when the management read target has changed."""- async with self._mutation_lock:- scope = account_id- signature = await self._identity_registry_signature(account_id)- if self._identity_registry_signatures.get(scope) == signature:- return False- await self._reload_unlocked()- return True-- async def refresh_accounts_from_store(self) -> None:- """Refresh account metadata without reading user or group registries."""- async with self._mutation_lock, self._reload_lock:- await self._refresh_accounts_from_store_unlocked()-async def _refresh_accounts_from_store_unlocked(self) -> None:accounts_data = await self._read_json(ACCOUNTS_PATH)if accounts_data is None:@@ -246,11 +297,6 @@ class LegacyAPIKeyManager:account.created_at = created_ataccount.deletion = info.get("deletion")- async def refresh_account_users_from_store(self, account_id: str) -> None:- """Refresh one account's users without reading unrelated registries."""- async with self._mutation_lock, self._reload_lock:- await self._refresh_account_users_from_store_unlocked(account_id)-async def _refresh_account_users_from_store_unlocked(self, account_id: str) -> None:users_path = USERS_PATH_TEMPLATE.format(account_id=account_id)users_data = await self._read_json(users_path)@@ -264,9 +310,7 @@ class LegacyAPIKeyManager:key_or_hash = user_info.get("key", "")if not key_or_hash:continue- key_prefix = user_info.get("key_prefix", "") or self._get_key_prefix(- key_or_hash- )+ key_prefix = user_info.get("key_prefix", "") or self._get_key_prefix(key_or_hash)if key_prefix:prefix_entries.append((@@ -293,31 +337,6 @@ class LegacyAPIKeyManager:self._prefix_index.setdefault(key_prefix, []).append(entry)self._rebuild_account_group_index(account_id)- async def _update_identity_registry_signatures(- self, account_ids: set[str] | None = None- ) -> None:- accounts_signature = await self._stat_signature(ACCOUNTS_PATH)- target_account_ids = self._accounts if account_ids is None else account_ids- signatures = {None: (accounts_signature,)}- for account_id in target_account_ids:- users_path = USERS_PATH_TEMPLATE.format(account_id=account_id)- signatures[account_id] = (- accounts_signature,- await self._stat_signature(users_path),- )-- if account_ids is None:- self._identity_registry_signatures = signatures- else:- self._identity_registry_signatures.update(signatures)-- async def _identity_registry_signature(self, account_id: str | None = None) -> tuple:- accounts_signature = await self._stat_signature(ACCOUNTS_PATH)- if account_id is not None:- users_path = USERS_PATH_TEMPLATE.format(account_id=account_id)- return (accounts_signature, await self._stat_signature(users_path))- return (accounts_signature,)-async def _build_state(self, accounts_data: dict, *, allow_migration: bool) -> tuple[@@ -344,10 +363,12 @@ class LegacyAPIKeyManager:groups=groups,deletion=info.get("deletion"),)- user_group_ids.update({- (account_id, user_id): group_ids- for user_id, group_ids in self._group_memberships(users, groups).items()- })+ user_group_ids.update(+ {+ (account_id, user_id): group_ids+ for user_id, group_ids in self._group_memberships(users, groups).items()+ }+ )for user_id, user_info in users.items():key_or_hash = user_info.get("key", "")@@ -390,7 +411,7 @@ class LegacyAPIKeyManager:return accounts, prefix_index, user_group_ids- async def compute_store_signature(self) -> tuple:+ async def _compute_store_signature(self) -> tuple:"""Return a cheap (path, size, modTime) signature over accounts.json + all users.json."""signature: list[tuple] = []@@ -425,123 +446,55 @@ class LegacyAPIKeyManager:mod_time = info.get("modTime", info.get("mod_time", info.get("mtime")))return (path, size, mod_time)- def resolve(self, api_key: str) -> ResolvedIdentity:- """Resolve an API key to identity. Sequential matching: root key first, then user key index."""- if not api_key:- raise UnauthenticatedError("Missing API Key")-- if hmac.compare_digest(api_key, self._root_key):- return ResolvedIdentity(role=Role.ROOT)-- # Use prefix index to quickly locate candidate keys- key_prefix = self._get_key_prefix(api_key)- candidates = self._prefix_index.get(key_prefix, [])-- for entry in candidates:- if self.get_deletion(entry.account_id) is not None:- continue- if entry.is_hashed:- # Verify hashed key- if self._verify_api_key(api_key, entry.key_or_hash):- return ResolvedIdentity(- role=entry.role,- account_id=entry.account_id,- user_id=entry.user_id,- )- else:- # Verify plaintext key- if hmac.compare_digest(api_key, entry.key_or_hash):- return ResolvedIdentity(- role=entry.role,- account_id=entry.account_id,- user_id=entry.user_id,- )-- raise UnauthenticatedError("Invalid API Key")-- async def create_account(+ async def _create_account_identity(self,account_id: str,admin_user_id: str,- seed: Optional[str] = None,- ) -> str:- """Create a new account (workspace) with its first admin user.-- Returns the admin user's API key (legacy format).- """- # Validate account_id and user_id format- verr = validate_account_id(account_id)- if verr:- raise InvalidArgumentError(verr)- verr = validate_user_id(admin_user_id)- if verr:- raise InvalidArgumentError(verr)-+ api_key: str | None = None,+ ) -> None:+ """Create an account and its first admin, optionally with a credential."""+ if error := validate_account_id(account_id):+ raise InvalidArgumentError(error)+ if error := validate_user_id(admin_user_id):+ raise InvalidArgumentError(error)if account_id in self._accounts:raise AlreadyExistsError(account_id, "account")now = datetime.now(timezone.utc).isoformat()- key = (- derive_seeded_api_key_secret(admin_user_id, seed)- if seed is not None- else self._generate_api_key()- )-- if self._api_key_hashing_enabled:- stored_key = self._hash_api_key(key)- is_hashed = True- key_prefix = self._get_key_prefix(key)- else:- stored_key = key- is_hashed = False- key_prefix = self._get_key_prefix(key)-- user_info = {- "role": "admin",- "key": stored_key,- }- if self._api_key_hashing_enabled:- user_info["key_prefix"] = key_prefix-+ user_info = {"role": "admin"}+ if api_key is not None:+ user_info["key"] = (+ self._hash_api_key(api_key)+ if self._api_key_hashing_enabled+ else api_key+ )+ if self._api_key_hashing_enabled:+ user_info["key_prefix"] = self._get_key_prefix(api_key)self._accounts[account_id] = AccountInfo(created_at=now,users={admin_user_id: user_info},groups={},)-- entry = UserKeyEntry(- account_id=account_id,- user_id=admin_user_id,- role=Role.ADMIN,- key_or_hash=stored_key,- is_hashed=is_hashed,- )-- # Add to prefix index- if key_prefix:- if key_prefix not in self._prefix_index:- self._prefix_index[key_prefix] = []- self._prefix_index[key_prefix].append(entry)-account_was_created = Falsetry:- created_account_ids = await self._save_accounts_json(+ created = await self._save_accounts_json(updated_account_ids={account_id},reject_existing_account_ids={account_id},)- account_was_created = account_id in created_account_ids+ account_was_created = account_id in createdawait self._save_users_json(account_id,{admin_user_id: user_info},- replace_existing=account_id in created_account_ids,+ replace_existing=account_was_created,)await self._write_groups_json(account_id, {})except Exception:- await self._rollback_create_account(account_id, account_was_created=account_was_created)+ await self._rollback_create_account(+ account_id, account_was_created=account_was_created+ )raise- return key- async def delete_account(self, account_id: str) -> None:+ async def _delete_account_identity(self, account_id: str) -> None:"""Delete an account and remove all its user keys from the index."""if account_id not in self._accounts:raise NotFoundError(account_id, "account")@@ -549,74 +502,112 @@ class LegacyAPIKeyManager:await self._save_accounts_json(delete_account_ids={account_id})self._discard_account_state(account_id)- async def register_user(+ async def _create_user_identity(self,account_id: str,user_id: str,role: str = "user",- seed: Optional[str] = None,- ) -> str:- """Register a new user in an account. Returns the user's API key (legacy format)."""+ *,+ api_key: str | None = None,+ ) -> None:+ """Create a user, optionally including its initial API key."""resolved_role = validate_account_user_role(role)- # Validate user_id format- verr = validate_user_id(user_id)- if verr:- raise InvalidArgumentError(verr)-- self.ensure_account_active(account_id)+ if error := validate_user_id(user_id):+ raise InvalidArgumentError(error)+ self._ensure_account_active(account_id)account = self._accounts.get(account_id)if account is None:raise NotFoundError(account_id, "account")if user_id in account.users:raise AlreadyExistsError(user_id, "user")- key = (- derive_seeded_api_key_secret(user_id, seed)- if seed is not None- else self._generate_api_key()- )-- if self._api_key_hashing_enabled:- stored_key = self._hash_api_key(key)- is_hashed = True- key_prefix = self._get_key_prefix(key)- else:- stored_key = key- is_hashed = False- key_prefix = self._get_key_prefix(key)-- user_info = {- "role": resolved_role,- "key": stored_key,- }- if self._api_key_hashing_enabled:- user_info["key_prefix"] = key_prefix-+ user_info = {"role": resolved_role}+ if api_key is not None:+ stored_key = (+ self._hash_api_key(api_key)+ if self._api_key_hashing_enabled+ else api_key+ )+ user_info["key"] = stored_key+ if self._api_key_hashing_enabled:+ user_info["key_prefix"] = self._get_key_prefix(api_key)account.users[user_id] = user_info-- entry = UserKeyEntry(- account_id=account_id,- user_id=user_id,- role=resolved_role,- key_or_hash=stored_key,- is_hashed=is_hashed,- )-- # Add to prefix index- if key_prefix:- if key_prefix not in self._prefix_index:- self._prefix_index[key_prefix] = []- self._prefix_index[key_prefix].append(entry)-try:await self._save_users_json(- account_id, {user_id: user_info}, reject_existing_user_ids={user_id}+ account_id,+ {user_id: user_info},+ reject_existing_user_ids={user_id},)except Exception:account.users.pop(user_id, None)- self._remove_key_index_entry(account_id, user_id, user_info)raise- return key++ async def _set_user_key(+ self,+ account_id: str,+ user_id: str,+ api_key: str,+ *,+ rotate: bool,+ ) -> None:+ """Persist one credential in the legacy user record."""+ self._ensure_account_active(account_id)+ account = self._accounts.get(account_id)+ if account is None:+ raise NotFoundError(account_id, "account")+ user_info = account.users.get(user_id)+ if user_info is None:+ raise NotFoundError(user_id, "user")+ if user_info.get("deletion"):+ raise FailedPreconditionError("User deletion is in progress")+ if user_info.get("key") and not rotate:+ raise AlreadyExistsError(user_id, "API key")++ material = (+ self._hash_api_key(api_key)+ if self._api_key_hashing_enabled+ else api_key+ )+ old_user_info = copy.deepcopy(user_info)+ self._remove_key_index_entry(account_id, user_id, old_user_info)+ user_info["key"] = material+ if material.startswith("$argon2"):+ user_info["key_prefix"] = self._get_key_prefix(api_key)+ else:+ user_info.pop("key_prefix", None)+ try:+ await self._save_users_json(account_id, {user_id: user_info})+ except Exception:+ account.users[user_id] = old_user_info+ self._rebuild_prefix_index()+ raise++ async def _revoke_user_keys(+ self, account_id: str, user_id: str | None = None+ ) -> None:+ """Remove matching credentials from legacy user records."""+ account = self._accounts.get(account_id)+ if account is None:+ return+ targets = [user_id] if user_id is not None else list(account.users)+ updates = {}+ originals = {}+ for target in targets:+ user_info = account.users.get(target)+ if user_info is None or not user_info.get("key"):+ continue+ originals[target] = copy.deepcopy(user_info)+ self._remove_key_index_entry(account_id, target, user_info)+ user_info["key"] = ""+ user_info.pop("key_prefix", None)+ updates[target] = user_info+ if updates:+ try:+ await self._save_users_json(account_id, updates)+ except Exception:+ account.users.update(originals)+ self._rebuild_prefix_index()+ raiseasync def ensure_trusted_identities(self, identities: Dict[str, set[str]]) -> dict[str, int]:"""Merge trusted identities into the registry without creating API keys."""@@ -629,7 +620,7 @@ class LegacyAPIKeyManager:normalized = {account_id: set(user_ids)for account_id, user_ids in identities.items()- if user_ids and self.get_deletion(account_id) is None+ if user_ids}if not normalized:return {"created_accounts": 0, "created_users": 0}@@ -660,6 +651,11 @@ class LegacyAPIKeyManager:try:accounts_data = await self._read_accounts_for_update()persisted_accounts = accounts_data.setdefault("accounts", {})+ normalized = {+ account_id: user_ids+ for account_id, user_ids in normalized.items()+ if not (persisted_accounts.get(account_id) or {}).get("deletion")+ }for account_id in normalized:if account_id not in persisted_accounts:persisted_accounts[account_id] = {"created_at": now}@@ -682,7 +678,9 @@ class LegacyAPIKeyManager:try:users_data = await self._read_json(path) or {"users": {}}persisted_users = users_data.setdefault("users", {})- new_users = sorted(user_id for user_id in user_ids if user_id not in persisted_users)+ new_users = sorted(+ user_id for user_id in user_ids if user_id not in persisted_users+ )for user_id in new_users:persisted_users[user_id] = {"role": "user"}if new_users:@@ -696,15 +694,13 @@ class LegacyAPIKeyManager:account = self._accounts.get(account_id)if account is None:- created_at = (- (accounts_data.get("accounts", {}).get(account_id) or {}).get("created_at")- or now- )+ account_info = persisted_accounts[account_id]account = AccountInfo(- created_at=created_at,+ created_at=account_info.get("created_at", now),users={},groups={},groups_loaded=False,+ deletion=account_info.get("deletion"),)self._accounts[account_id] = accountfor user_id, user_info in persisted_users.items():@@ -712,10 +708,9 @@ class LegacyAPIKeyManager:finally:await self._async_agfs.pathlock_release(users_lease)- await self._update_identity_registry_signatures(set(normalized))return {"created_accounts": created_accounts, "created_users": created_users}- async def begin_deletion(+ async def _begin_deletion(self,account_id: str,user_id: str | None,@@ -743,7 +738,7 @@ class LegacyAPIKeyManager:account.deletion = Noneraisereturn dict(account.deletion), True- self.ensure_account_active(account_id)+ self._ensure_account_active(account_id)user_info = account.users.get(user_id)if user_info is None:raise NotFoundError(user_id, "user")@@ -777,7 +772,7 @@ class LegacyAPIKeyManager:self._remove_key_index_entry(account_id, user_id, original)return dict(deletion), True- async def replace_deletion_task(+ async def _replace_deletion_task(self,account_id: str,user_id: str | None,@@ -807,7 +802,7 @@ class LegacyAPIKeyManager:account.deletion = currentraisereturn dict(account.deletion)- self.ensure_account_active(account_id)+ self._ensure_account_active(account_id)user_info = account.users.get(user_id)if user_info is None:raise NotFoundError(user_id, "user")@@ -828,7 +823,9 @@ class LegacyAPIKeyManager:raisereturn dict(replacement)- async def finish_deletion(self, account_id: str, user_id: str | None, task_id: str) -> bool:+ async def _finish_deletion(+ self, account_id: str, user_id: str | None, task_id: str+ ) -> bool:"""Remove the identity only when this task still owns its deletion fence."""async with self._reload_lock, self._deletion_lock:account = self._accounts.get(account_id)@@ -837,7 +834,7 @@ class LegacyAPIKeyManager:if user_id is None:if account.deletion is None or account.deletion["task_id"] != task_id:return False- await self.delete_account(account_id)+ await self._delete_account_identity(account_id)return Trueuser_info = account.users.get(user_id)if user_info is None:@@ -853,6 +850,7 @@ class LegacyAPIKeyManager:members = group.get("members", [])if user_id in members:group["members"] = [member for member in members if member != user_id]+ self._remove_key_index_entry(account_id, user_id, user_info)account.users.pop(user_id)try:await self._save_users_json(account_id, deleted_user_ids={user_id})@@ -861,6 +859,7 @@ class LegacyAPIKeyManager:except Exception:account.users[user_id] = user_infoaccount.groups = old_groups+ self._rebuild_prefix_index()self._rebuild_account_group_index(account_id)raiseif groups != old_groups:@@ -868,7 +867,9 @@ class LegacyAPIKeyManager:self._rebuild_account_group_index(account_id)return True- def get_deletion(self, account_id: str, user_id: str | None = None) -> Optional[dict]:+ def _get_deletion(+ self, account_id: str, user_id: str | None = None+ ) -> Optional[dict]:account = self._accounts.get(account_id)if account is None:return None@@ -878,7 +879,7 @@ class LegacyAPIKeyManager:deletion = user_info.get("deletion") if user_info else Nonereturn dict(deletion) if isinstance(deletion, dict) else None- def iter_deletions(self) -> list[tuple[str, str | None, dict]]:+ def _iter_deletions(self) -> list[tuple[str, str | None, dict]]:return [(account_id, user_id, dict(deletion))for account_id, account in self._accounts.items()@@ -890,89 +891,10 @@ class LegacyAPIKeyManager:if account.deletion is not None]- def is_deleting(self, account_id: str, user_id: str | None = None) -> bool:- return (- self.get_deletion(account_id) is not None- or self.get_deletion(account_id, user_id) is not None- )-- async def regenerate_key(- self, account_id: str, user_id: str, seed: Optional[str] = None- ) -> str:- """Regenerate a user's API key. Old key is immediately invalidated."""- self.ensure_account_active(account_id)- account = self._accounts.get(account_id)- if account is None:- raise NotFoundError(account_id, "account")- if user_id not in account.users:- raise NotFoundError(user_id, "user")- if account.users[user_id].get("deletion"):- raise FailedPreconditionError("User deletion is in progress")-- old_user_info = account.users[user_id]- old_key_or_hash = old_user_info.get("key", "")-- # Get old key_prefix - if not in user_info, compute from key- old_key_prefix = old_user_info.get("key_prefix", "")- if not old_key_prefix and old_key_or_hash:- old_key_prefix = self._get_key_prefix(old_key_or_hash)-- # Remove old key from prefix index- if old_key_prefix in self._prefix_index:- self._prefix_index[old_key_prefix] = [- entry- for entry in self._prefix_index[old_key_prefix]- if not (entry.account_id == account_id and entry.user_id == user_id)- ]- if not self._prefix_index[old_key_prefix]:- del self._prefix_index[old_key_prefix]-- # Generate new key- new_key = (- derive_seeded_api_key_secret(user_id, seed)- if seed is not None- else self._generate_api_key()- )-- if self._api_key_hashing_enabled:- new_stored_key = self._hash_api_key(new_key)- new_is_hashed = True- new_key_prefix = self._get_key_prefix(new_key)- else:- new_stored_key = new_key- new_is_hashed = False- new_key_prefix = self._get_key_prefix(new_key)-- # Update user info- account.users[user_id]["key"] = new_stored_key- if self._api_key_hashing_enabled:- account.users[user_id]["key_prefix"] = new_key_prefix- else:- # Remove key_prefix if API key hashing is disabled- if "key_prefix" in account.users[user_id]:- del account.users[user_id]["key_prefix"]-- # Add new key to prefix index- entry = UserKeyEntry(- account_id=account_id,- user_id=user_id,- role=Role(account.users[user_id]["role"]),- key_or_hash=new_stored_key,- is_hashed=new_is_hashed,- )-- if new_key_prefix:- if new_key_prefix not in self._prefix_index:- self._prefix_index[new_key_prefix] = []- self._prefix_index[new_key_prefix].append(entry)-- await self._save_users_json(account_id, {user_id: account.users[user_id]})- return new_key-- async def set_role(self, account_id: str, user_id: str, role: str) -> None:+ async def _set_role(self, account_id: str, user_id: str, role: str) -> None:"""Update a user's role."""resolved_role = validate_account_user_role(role)- self.ensure_account_active(account_id)+ self._ensure_account_active(account_id)account = self._accounts.get(account_id)if account is None:raise NotFoundError(account_id, "account")@@ -1000,7 +922,7 @@ class LegacyAPIKeyManager:await self._save_users_json(account_id, {user_id: account.users[user_id]})- def get_accounts(+ def _get_accounts(self,name_filter: str | None = None,limit: int | None = None,@@ -1036,7 +958,7 @@ class LegacyAPIKeyManager:)return _paginate(result, limit, page)- def get_users(+ def _get_users(self,account_id: str,limit: int | None = 100,@@ -1044,22 +966,24 @@ class LegacyAPIKeyManager:role_filter: str | None = None,expose_key: bool = True,page: int = 1,+ query_filter: str | None = None,) -> list:"""List users in an account in creation (insertion) order.Pagination is opt-in via ``limit``/``page`` (1-based); ``limit=None``returns every matching user."""- return self.get_users_page(+ return self._get_users_page(account_id,limit=limit,name_filter=name_filter,role_filter=role_filter,expose_key=expose_key,page=page,+ query_filter=query_filter,)["users"]- def get_users_page(+ def _get_users_page(self,account_id: str,limit: int | None = 100,@@ -1121,31 +1045,11 @@ class LegacyAPIKeyManager:"key_count": key_count,}- def has_user(self, account_id: str, user_id: str) -> bool:- """Return True when the account registry contains the given user."""- account = self._accounts.get(account_id)- if account is None:- return False- return user_id in account.users-- def get_user_role(self, account_id: str, user_id: str) -> Role:- """Return the role of the given user in the given account.-- Returns Role.USER if the account or user doesn't exist.- """- account = self._accounts.get(account_id)- if account is None:- return Role.USER- user = account.users.get(user_id)- if user is None:- return Role.USER- return Role(user.get("role", "user"))-- def get_user_group_ids(self, account_id: str, user_id: str) -> tuple[str, ...]:+ def _get_user_group_ids(self, account_id: str, user_id: str) -> tuple[str, ...]:"""Return the account-scoped groups currently containing the user."""return self._user_group_ids.get((account_id, user_id), ())- async def create_group(self, account_id: str, group_id: str) -> dict:+ async def _create_group(self, account_id: str, group_id: str) -> dict:error = validate_identifier_part(group_id, "group_id")if error:raise InvalidArgumentError(error)@@ -1159,18 +1063,20 @@ class LegacyAPIKeyManager:await self._replace_groups(account_id, account, groups)return self._group_result(group_id, groups[group_id])- def get_groups(self, account_id: str) -> list[dict]:+ def _get_groups(self, account_id: str) -> list[dict]:account = self._require_account(account_id)return [self._group_result(group_id, group)for group_id, group in sorted(account.groups.items())]- def get_group_members(self, account_id: str, group_id: str) -> list[str]:+ def _get_group_members(self, account_id: str, group_id: str) -> list[str]:group = self._require_group(account_id, group_id)return sorted(set(group.get("members", [])))- async def add_group_member(self, account_id: str, group_id: str, user_id: str) -> bool:+ async def _add_group_member(+ self, account_id: str, group_id: str, user_id: str+ ) -> bool:async with self._reload_lock:account = self._require_account(account_id)await self._load_account_groups_if_needed(account_id, account)@@ -1185,7 +1091,9 @@ class LegacyAPIKeyManager:await self._replace_groups(account_id, account, groups)return True- async def remove_group_member(self, account_id: str, group_id: str, user_id: str) -> bool:+ async def _remove_group_member(+ self, account_id: str, group_id: str, user_id: str+ ) -> bool:async with self._reload_lock:account = self._require_account(account_id)await self._load_account_groups_if_needed(account_id, account)@@ -1199,7 +1107,7 @@ class LegacyAPIKeyManager:await self._replace_groups(account_id, account, groups)return True- async def delete_group(self, account_id: str, group_id: str) -> None:+ async def _delete_group(self, account_id: str, group_id: str) -> None:async with self._reload_lock:account = self._require_account(account_id)await self._load_account_groups_if_needed(account_id, account)@@ -1210,39 +1118,10 @@ class LegacyAPIKeyManager:del groups[group_id]await self._replace_groups(account_id, account, groups)- def get_user_key_fingerprint(self, account_id: str, user_id: str) -> Optional[str]:- """Return SHA-256 hex digest of the user's stored API key value, or None.-- The "stored value" is whatever is persisted in ``user_info["key"]``:- either the plaintext API key (when hashing is disabled) or its- Argon2id hash (when hashing is enabled). Both are stable per- key-generation — they are written once on create / regenerate and- never mutate in place — so the fingerprint is stable as long as the- key is unchanged, and changes the moment ``regenerate_key`` runs.-- Used by OAuth to bind issued tokens to the API key that authorized- them: at OTP / authorize time we record this fingerprint; at every- OAuth bearer auth we recompute and compare. Mismatch (rotation) or- ``None`` (user removed) fails the request closed.-- Returns None when the account or user does not exist, or when the- stored value is empty (no fingerprint to bind to).- """- account = self._accounts.get(account_id)- if account is None or account.deletion is not None:- return None- user = account.users.get(user_id)- if user is None:- return None- stored = user.get("key", "")- if not stored:- return None- return hashlib.sha256(stored.encode("utf-8")).hexdigest()-# ---- internal helpers ----- def ensure_account_active(self, account_id: str) -> None:- deletion = self.get_deletion(account_id)+ def _ensure_account_active(self, account_id: str) -> None:+ deletion = self._get_deletion(account_id)if deletion is not None:raise FailedPreconditionError("Account deletion is in progress",@@ -1250,7 +1129,7 @@ class LegacyAPIKeyManager:)def _require_account(self, account_id: str) -> AccountInfo:- self.ensure_account_active(account_id)+ self._ensure_account_active(account_id)account = self._accounts.get(account_id)if account is None:raise NotFoundError(account_id, "account")@@ -1263,15 +1142,13 @@ class LegacyAPIKeyManager:raise NotFoundError(group_id, "group")return group- async def ensure_account_groups_loaded(self, account_id: str) -> None:+ async def _ensure_account_groups_loaded(self, account_id: str) -> None:"""Load one account's groups when its account metadata was discovered alone."""async with self._reload_lock:account = self._require_account(account_id)await self._load_account_groups_if_needed(account_id, account)- async def _load_account_groups_if_needed(- self, account_id: str, account: AccountInfo- ) -> None:+ async def _load_account_groups_if_needed(self, account_id: str, account: AccountInfo) -> None:if account.groups_loaded:returngroups_path = GROUPS_PATH_TEMPLATE.format(account_id=account_id)@@ -1296,12 +1173,14 @@ class LegacyAPIKeyManager:account = self._accounts.get(account_id)if account is None:return- self._user_group_ids.update({- (account_id, user_id): group_ids- for user_id, group_ids in self._group_memberships(- account.users, account.groups- ).items()- })+ self._user_group_ids.update(+ {+ (account_id, user_id): group_ids+ for user_id, group_ids in self._group_memberships(+ account.users, account.groups+ ).items()+ }+ )@staticmethoddef _group_memberships(@@ -1340,10 +1219,6 @@ class LegacyAPIKeyManager:if not self._prefix_index[key_prefix]:del self._prefix_index[key_prefix]- def _generate_api_key(self) -> str:- """Generate new API Key (legacy format - hex)."""- return secrets.token_hex(32)-def _get_key_prefix(self, api_key: str) -> str:"""Extract API Key prefix for indexing."""if api_key:@@ -1361,15 +1236,6 @@ class LegacyAPIKeyManager:)return ph.hash(api_key)- def _verify_api_key(self, api_key: str, hashed_key: str) -> bool:- """Verify if API Key matches the hash."""- ph = PasswordHasher()- try:- ph.verify(hashed_key, api_key)- return True- except VerifyMismatchError:- return False-async def _read_json(self, path: str) -> Optional[dict]:"""Read a JSON file from AGFS with encryption support. Returns None if not found."""try:@@ -1539,3 +1405,321 @@ class LegacyAPIKeyManager:async def _write_groups_json(self, account_id: str, groups: dict) -> None:path = GROUPS_PATH_TEMPLATE.format(account_id=account_id)await self._write_json(path, {"groups": groups})++ def _watcher_running(self) -> bool:+ return self._watch_task is not None and not self._watch_task.done()++ async def _refresh_accounts_for_management_read(self) -> None:+ async with self._mutation_lock:+ await self._refresh_accounts_for_management_read_unlocked()++ async def _refresh_users_for_management_read(self, account_id: str) -> None:+ async with self._mutation_lock:+ await self._refresh_users_for_management_read_unlocked(account_id)++ async def _refresh_accounts_for_management_read_unlocked(self) -> None:+ """Refresh account state while the caller holds ``_mutation_lock``."""+ if not self._watcher_running():+ async with self._reload_lock:+ await self._refresh_accounts_from_store_unlocked()++ async def _refresh_users_for_management_read_unlocked(+ self, account_id: str+ ) -> None:+ """Refresh user state while the caller holds ``_mutation_lock``."""+ if not self._watcher_running():+ async with self._reload_lock:+ await self._refresh_account_users_from_store_unlocked(account_id)++ async def get_account(self, account_id: str) -> AccountSummary | None:+ await self._refresh_accounts_for_management_read()+ return next(+ (+ account+ for account in self._get_accounts()+ if account["account_id"] == account_id+ ),+ None,+ )++ async def get_user(self, account_id: str, user_id: str) -> UserSummary | None:+ account = self._accounts.get(account_id)+ if account is None:+ return None+ user = account.users.get(user_id)+ return (+ UserSummary(user_id=user_id, role=user.get("role", Role.USER))+ if user+ else None+ )++ @deprecated(+ "get_user_for_management is a FileStore compatibility path and will be removed.",+ category=None,+ )+ async def get_user_for_management(+ self, account_id: str, user_id: str+ ) -> UserSummary | None:+ await self._refresh_users_for_management_read(account_id)+ return await self.get_user(account_id, user_id)++ async def create_account_with_api_key(+ self,+ account_id: str,+ admin_user_id: str,+ api_key: str,+ ) -> None:+ async with self._mutation_lock:+ await self._refresh_accounts_for_management_read_unlocked()+ await self._create_account_identity(+ account_id,+ admin_user_id,+ api_key,+ )++ async def create_account(+ self,+ account_id: str,+ admin_user_id: str,+ ) -> None:+ async with self._mutation_lock:+ await self._refresh_accounts_for_management_read_unlocked()+ await self._create_account_identity(account_id, admin_user_id)++ async def create_user(self, account_id: str, user_id: str, role: str) -> None:+ async with self._mutation_lock:+ await self._create_user_identity(account_id, user_id, role)++ async def create_user_with_api_key(+ self,+ account_id: str,+ user_id: str,+ role: str,+ api_key: str,+ ) -> None:+ async with self._mutation_lock:+ await self._create_user_identity(+ account_id,+ user_id,+ role,+ api_key=api_key,+ )++ async def delete_account(self, account_id: str) -> None:+ async with self._mutation_lock:+ await self._refresh_accounts_for_management_read_unlocked()+ await self._delete_account_identity(account_id)++ async def list_accounts(+ self,+ name_filter: str | None = None,+ limit: int | None = None,+ page: int = 1,+ query_filter: str | None = None,+ ) -> list[AccountSummary]:+ await self._refresh_accounts_for_management_read()+ return self._get_accounts(+ name_filter=name_filter,+ limit=limit,+ page=page,+ query_filter=query_filter,+ )++ async def list_users_page(+ self,+ account_id: str,+ limit: int | None = 100,+ name_filter: str | None = None,+ role_filter: str | None = None,+ page: int = 1,+ query_filter: str | None = None,+ fresh: bool = False,+ ) -> UsersPage:+ if fresh:+ async with self._mutation_lock:+ async with self._reload_lock:+ await self._refresh_account_users_from_store_unlocked(account_id)+ else:+ await self._refresh_users_for_management_read(account_id)+ return self._get_users_page(+ account_id,+ limit=limit,+ name_filter=name_filter,+ role_filter=role_filter,+ expose_key=True,+ page=page,+ query_filter=query_filter,+ )++ async def set_role(self, account_id: str, user_id: str, role: str) -> None:+ async with self._mutation_lock:+ await self._refresh_accounts_for_management_read_unlocked()+ await self._refresh_users_for_management_read_unlocked(account_id)+ await self._set_role(account_id, user_id, role)++ async def begin_deletion(+ self,+ account_id: str,+ user_id: str | None,+ *,+ task_id: str,+ owner_account_id: str,+ owner_user_id: str,+ ) -> tuple[DeletionRecord, bool]:+ async with self._mutation_lock:+ await self._refresh_accounts_for_management_read_unlocked()+ if user_id is not None:+ await self._refresh_users_for_management_read_unlocked(account_id)+ return await self._begin_deletion(+ account_id,+ user_id,+ task_id=task_id,+ owner_account_id=owner_account_id,+ owner_user_id=owner_user_id,+ )++ async def replace_deletion_task(+ self,+ account_id: str,+ user_id: str | None,+ *,+ expected_task_id: str,+ task_id: str,+ owner_account_id: str,+ owner_user_id: str,+ ) -> DeletionRecord:+ async with self._mutation_lock:+ return await self._replace_deletion_task(+ account_id,+ user_id,+ expected_task_id=expected_task_id,+ task_id=task_id,+ owner_account_id=owner_account_id,+ owner_user_id=owner_user_id,+ )++ async def finish_deletion(+ self, account_id: str, user_id: str | None, task_id: str+ ) -> bool:+ async with self._mutation_lock:+ return await self._finish_deletion(account_id, user_id, task_id)++ async def get_deletion(+ self, account_id: str, user_id: str | None = None+ ) -> DeletionRecord | None:+ return self._get_deletion(account_id) or (+ self._get_deletion(account_id, user_id) if user_id is not None else None+ )++ async def iter_deletions(+ self,+ ) -> list[tuple[str, str | None, DeletionRecord]]:+ return self._iter_deletions()++ async def create_group(+ self, account_id: str, group_id: str+ ) -> GroupSummary:+ await self._refresh_accounts_for_management_read()+ return await self._create_group(account_id, group_id)++ async def get_groups(self, account_id: str) -> list[GroupSummary]:+ await self._refresh_accounts_for_management_read()+ await self._ensure_account_groups_loaded(account_id)+ return self._get_groups(account_id)++ async def get_group_members(+ self, account_id: str, group_id: str+ ) -> list[str]:+ await self._refresh_accounts_for_management_read()+ await self._ensure_account_groups_loaded(account_id)+ return self._get_group_members(account_id, group_id)++ async def get_user_group_ids(self, account_id: str, user_id: str) -> tuple[str, ...]:+ account = self._accounts.get(account_id)+ if account is None or user_id not in account.users:+ return ()+ await self._ensure_account_groups_loaded(account_id)+ return self._get_user_group_ids(account_id, user_id)++ async def add_group_member(+ self, account_id: str, group_id: str, user_id: str+ ) -> bool:+ await self._refresh_users_for_management_read(account_id)+ return await self._add_group_member(account_id, group_id, user_id)++ async def remove_group_member(+ self, account_id: str, group_id: str, user_id: str+ ) -> bool:+ await self._refresh_accounts_for_management_read()+ return await self._remove_group_member(account_id, group_id, user_id)++ async def delete_group(self, account_id: str, group_id: str) -> None:+ await self._refresh_accounts_for_management_read()+ await self._delete_group(account_id, group_id)++ async def replace_active_user_api_key(+ self, account_id: str, user_id: str, api_key: str+ ) -> None:+ async with self._mutation_lock:+ await self._set_user_key(+ account_id,+ user_id,+ api_key,+ rotate=True,+ )++ async def verify_api_key(+ self,+ api_key: str,+ *,+ account_id_hint: str | None = None,+ user_id_hint: str | None = None,+ ) -> tuple[str, str] | None:+ for entry in self._prefix_index.get(self._get_key_prefix(api_key), []):+ if account_id_hint is not None and entry.account_id != account_id_hint:+ continue+ if user_id_hint is not None and entry.user_id != user_id_hint:+ continue+ account = self._accounts.get(entry.account_id)+ if account is None or account.deletion is not None:+ continue+ user = account.users.get(entry.user_id)+ if user is None or user.get("deletion"):+ continue+ if entry.is_hashed:+ try:+ matched = await asyncio.to_thread(+ PasswordHasher(+ time_cost=ARGON2_TIME_COST,+ memory_cost=ARGON2_MEMORY_COST,+ parallelism=ARGON2_PARALLELISM,+ hash_len=ARGON2_HASH_LENGTH,+ ).verify,+ entry.key_or_hash,+ api_key,+ )+ except VerificationError:+ matched = False+ else:+ matched = hmac.compare_digest(entry.key_or_hash, api_key)+ if matched:+ return entry.account_id, entry.user_id+ return None++ async def revoke_active_api_keys(+ self, account_id: str, user_id: str | None = None+ ) -> None:+ async with self._mutation_lock:+ await self._revoke_user_keys(account_id, user_id)++ async def get_user_key_fingerprint(+ self, account_id: str, user_id: str+ ) -> str | None:+ account = self._accounts.get(account_id)+ if account is None or account.deletion is not None:+ return None+ user = account.users.get(user_id)+ if user is None or user.get("deletion"):+ return None+ material = user.get("key", "")+ return hashlib.sha256(material.encode()).hexdigest() if material else Nonediff --git a/openviking/server/api_keys/new.py b/openviking/server/api_keys/new.pyindex 2e05161df..fc3fbdcc2 100644--- a/openviking/server/api_keys/new.py+++ b/openviking/server/api_keys/new.py@@ -1,227 +1,138 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""New format API Key implementation with directly decodable identity.--This implementation delegates legacy format support to LegacyAPIKeyManager-to avoid code duplication, while adding new format key generation.-"""+"""API key operations over a complete account store."""import base64import hmacimport secretsfrom typing import Optional, Tuple+from typing_extensions import deprecated++from openviking.server.account_stores.base import AccountStorefrom openviking.server.api_keys.legacy import (- LegacyAPIKeyManager,derive_seeded_api_key_secret,)-from openviking.server.api_keys.models import (- AccountInfo,- UserKeyEntry,- validate_account_user_role,-)from openviking.server.identity import ResolvedIdentity, Role-from openviking.storage.viking_fs import VikingFSfrom openviking_cli.exceptions import (FailedPreconditionError,- InvalidArgumentError,+ NotFoundError,UnauthenticatedError,)-from openviking_cli.session.user_id import validate_account_id, validate_user_id-from openviking_cli.utils import get_logger--logger = get_logger(__name__)def _encode_segment(data: str) -> str:- """Encode a string segment using URL-safe base64 without padding."""encoded = base64.urlsafe_b64encode(data.encode("utf-8"))return encoded.decode("utf-8").rstrip("=")def _decode_segment(encoded: str) -> str:- """Decode a URL-safe base64 segment, adding padding if needed."""padding_needed = 4 - (len(encoded) % 4)if padding_needed != 4:encoded += "=" * padding_needed- decoded = base64.urlsafe_b64decode(encoded.encode("utf-8"))- return decoded.decode("utf-8")+ return base64.urlsafe_b64decode(encoded.encode("utf-8")).decode("utf-8")def is_new_format_key(api_key: str) -> bool:- """Check if the API key is in the new format (three base64 segments separated by dots)."""- if not api_key:- return False- parts = api_key.split(".")- return len(parts) == 3+ return bool(api_key) and len(api_key.split(".")) == 3def parse_api_key(api_key: str) -> Tuple[str, str, str]:- """Parse a new format API key into (account_id, user_id, secret)."""if not is_new_format_key(api_key):raise ValueError("Not a new format API key")- parts = api_key.split(".")- account_id = _decode_segment(parts[0])- user_id = _decode_segment(parts[1])- secret = _decode_segment(parts[2])- return account_id, user_id, secret+ account_id, user_id, secret = api_key.split(".")+ return (+ _decode_segment(account_id),+ _decode_segment(user_id),+ _decode_segment(secret),+ )def generate_api_key(account_id: str, user_id: str, seed: Optional[str] = None) -> str:- """Generate a new format API key."""- account_segment = _encode_segment(account_id)- user_segment = _encode_segment(user_id)secret = (- derive_seeded_api_key_secret(user_id, seed)- if seed is not None- else secrets.token_hex(32)+ derive_seeded_api_key_secret(user_id, seed) if seed is not None else secrets.token_hex(32))- secret_segment = _encode_segment(secret)- return f"{account_segment}.{user_segment}.{secret_segment}"-+ return ".".join(map(_encode_segment, (account_id, user_id, secret)))-class NewAPIKeyManager:- """Manages API keys for multi-tenant authentication with new key format.- New key format: base64url(account_id).base64url(user_id).base64url(secret)- - Can directly decode account_id and user_id without prefix lookup- - Still uses Argon2id for secure secret verification- - Delegates legacy functionality to LegacyAPIKeyManager to avoid code duplication- """+class APIKeyManager:+ """Coordinate API key operations over an already-constructed account store."""def __init__(self,root_key: str,- viking_fs: VikingFS,- api_key_hashing_enabled: bool = False,+ store: AccountStore,*,issue_user_keys: bool = True,- ):- """Initialize NewAPIKeyManager.-- Args:- root_key: Global root API key for administrative access.- viking_fs: VikingFS client for persistent storage of user keys.- api_key_hashing_enabled: Whether API key Argon2id hashing is enabled.- Default: false - rely on file-level AES encryption for protection.- issue_user_keys: Whether this auth plugin issues personal credentials.- """+ ) -> None:+ self._store = store+ self._root_api_key = root_keyself._issue_user_keys = issue_user_keys- # Delegate to legacy manager for all core functionality- self._legacy = LegacyAPIKeyManager(- root_key, viking_fs, api_key_hashing_enabled=api_key_hashing_enabled- )async def load(self) -> None:- """Load accounts and user keys from VikingFS into memory."""- await self._legacy.load()- logger.info(- "NewAPIKeyManager loaded: %d accounts, %d user keys",- len(self._legacy.get_accounts()),- sum(len(info.users) for info in self._legacy._accounts.values()),- )-- async def reload(self) -> None:- """Read-only refresh of in-memory key state; delegates to the legacy manager."""- await self._legacy.reload()-- async def compute_store_signature(self) -> tuple:- """Return a cheap change signature for the on-disk key store."""- return await self._legacy.compute_store_signature()-- async def refresh_identity_registry_if_changed(- self, account_id: str | None = None- ) -> bool:- """Refresh account/user registry state for a management read when needed."""- return await self._legacy.refresh_identity_registry_if_changed(account_id)-- async def refresh_accounts_from_store(self) -> None:- """Refresh account metadata without loading user or group registries."""- await self._legacy.refresh_accounts_from_store()-- async def refresh_account_users_from_store(self, account_id: str) -> None:- """Refresh one account's users without loading unrelated registries."""- await self._legacy.refresh_account_users_from_store(account_id)+ try:+ await self._store.load()+ except BaseException:+ await self.close()+ raise- async def ensure_account_groups_loaded(self, account_id: str) -> None:- """Load one account's groups after an account-only refresh."""- await self._legacy.ensure_account_groups_loaded(account_id)+ async def close(self) -> None:+ await self._store.close()- def resolve(self, api_key: str) -> ResolvedIdentity:- """Resolve an API key to identity.+ async def _require_authenticatable_user(self, account_id: str, user_id: str):+ user = await self.get_user(account_id, user_id)+ if user is None:+ raise UnauthenticatedError("Unknown account or user")+ deletion = await self.get_deletion(account_id, user_id)+ if deletion is not None:+ raise UnauthenticatedError("Invalid API key")+ return user- First checks for root key.- Then checks if it's a new format key (fast decode path).- Then falls back to legacy prefix index lookup.- """- if not api_key:- raise UnauthenticatedError("Missing API Key")+ async def _require_manageable_user(self, account_id: str, user_id: str):+ account = await self.get_account(account_id)+ if account is None:+ raise NotFoundError(account_id, "account")+ if account["status"] != "active":+ raise FailedPreconditionError(+ "Account deletion is in progress",+ details={"task_id": account.get("task_id")},+ )+ user = await self.get_user_for_management(account_id, user_id)+ if user is None:+ raise NotFoundError(user_id, "user")+ deletion = await self.get_deletion(account_id, user_id)+ if deletion is not None:+ raise FailedPreconditionError(+ "User deletion is in progress",+ details={"task_id": deletion.get("task_id")},+ )+ return user- # Check root key first - use legacy's root key- if hmac.compare_digest(api_key, self._legacy._root_key):+ async def resolve_identity(self, api_key: str) -> ResolvedIdentity:+ if self._root_api_key and hmac.compare_digest(api_key, self._root_api_key):return ResolvedIdentity(role=Role.ROOT)+ account_id, user_id = await self._verify_key(api_key)+ user = await self._require_authenticatable_user(account_id, user_id)+ return ResolvedIdentity(+ role=Role(user["role"]),+ account_id=account_id,+ user_id=user_id,+ )- # Fast path for new format keys - decode identity directly from key- if is_new_format_key(api_key):+ async def _verify_key(self, key: str):+ account_id = None+ user_id = None+ if is_new_format_key(key):try:- account_id, user_id, _ = parse_api_key(api_key)-- # Verify the user exists in the account using legacy's data- account = self._legacy._accounts.get(account_id)- if account and account.deletion is None and user_id in account.users:- user_info = account.users[user_id]- stored_key_or_hash = user_info.get("key", "")-- # Verify the secret part matches using legacy's verify method- if stored_key_or_hash:- if user_info.get("key_prefix", "").startswith(- "$argon2"- ) or stored_key_or_hash.startswith("$argon2"):- # Hashed key- if self._legacy._verify_api_key(api_key, stored_key_or_hash):- return ResolvedIdentity(- role=Role(user_info.get("role", "user")),- account_id=account_id,- user_id=user_id,- )- else:- # Plaintext key- if hmac.compare_digest(api_key, stored_key_or_hash):- return ResolvedIdentity(- role=Role(user_info.get("role", "user")),- account_id=account_id,- user_id=user_id,- )- except Exception:- # If parsing fails or verification fails, fall through to try legacy path- pass-- # Fall back to legacy resolver for legacy keys- return self._legacy.resolve(api_key)-- def _issue_user_key(- self, account_id: str, user_id: str, user_info: dict, seed: Optional[str]- ) -> str:- """Generate, store and index one personal credential."""- key = generate_api_key(account_id, user_id, seed)- is_hashed = self._legacy._api_key_hashing_enabled- stored_key = self._legacy._hash_api_key(key) if is_hashed else key- prefix = self._legacy._get_key_prefix(key)- user_info["key"] = stored_key- if is_hashed:- user_info["key_prefix"] = prefix- else:- user_info.pop("key_prefix", None)- self._legacy._prefix_index.setdefault(prefix, []).append(- UserKeyEntry(- account_id=account_id,- user_id=user_id,- role=Role(user_info["role"]),- key_or_hash=stored_key,- is_hashed=is_hashed,- )+ account_id, user_id, _ = parse_api_key(key)+ except (ValueError, UnicodeError):+ raise UnauthenticatedError("Invalid API key") from None+ binding = await self._store.verify_api_key(+ key, account_id_hint=account_id, user_id_hint=user_id)- return key+ if binding is not None:+ return binding+ raise UnauthenticatedError("Invalid API key")async def create_account(self,@@ -229,80 +140,16 @@ class NewAPIKeyManager:admin_user_id: str,seed: Optional[str] = None,) -> str | None:- async with self._legacy.mutation_lock:- return await self._create_account_unlocked(account_id, admin_user_id, seed)-- async def _create_account_unlocked(- self,- account_id: str,- admin_user_id: str,- seed: Optional[str] = None,- ) -> str | None:- """Create a new account (workspace) with its first admin user.-- Returns the admin user's API key when personal credentials are enabled.- """- # Validate account_id and user_id format- verr = validate_account_id(account_id)- if verr:- raise InvalidArgumentError(verr)- verr = validate_user_id(admin_user_id)- if verr:- raise InvalidArgumentError(verr)-- # Check existence first- if account_id in self._legacy._accounts:- from openviking_cli.exceptions import AlreadyExistsError-- raise AlreadyExistsError(account_id, "account")-- # Copy the legacy implementation but use new key format- from datetime import datetime, timezone-- now = datetime.now(timezone.utc).isoformat()-- user_info = {"role": "admin"}- key = (- self._issue_user_key(account_id, admin_user_id, user_info, seed)- if self._issue_user_keys- else None- )-- # Add to legacy's data structures- self._legacy._accounts[account_id] = AccountInfo(- created_at=now,- users={admin_user_id: user_info},- groups={},- )+ if not self._issue_user_keys:+ await self._store.create_account(account_id, admin_user_id)+ return None- account_was_created = False- try:- created_account_ids = await self._legacy._save_accounts_json(- updated_account_ids={account_id},- reject_existing_account_ids={account_id},- )- account_was_created = account_id in created_account_ids- await self._legacy._save_users_json(- account_id,- {admin_user_id: user_info},- replace_existing=account_id in created_account_ids,- )- await self._legacy._write_groups_json(account_id, {})- except Exception:- await self._legacy._rollback_create_account(- account_id, account_was_created=account_was_created- )- raise+ key = generate_api_key(account_id, admin_user_id, seed)+ await self._store.create_account_with_api_key(account_id, admin_user_id, key)return keyasync def delete_account(self, account_id: str) -> None:- """Delete an account and remove all its user keys from the index."""- async with self._legacy.mutation_lock:- await self._legacy.delete_account(account_id)-- async def ensure_trusted_identities(self, identities: dict[str, set[str]]) -> dict[str, int]:- """Merge trusted identities without generating API keys."""- return await self._legacy.ensure_trusted_identities(identities)+ await self._store.delete_account(account_id)async def register_user(self,@@ -311,291 +158,126 @@ class NewAPIKeyManager:role: str = "user",seed: Optional[str] = None,) -> str | None:- async with self._legacy.mutation_lock:- return await self._register_user_unlocked(account_id, user_id, role, seed)-- async def _register_user_unlocked(- self,- account_id: str,- user_id: str,- role: str = "user",- seed: Optional[str] = None,- ) -> str | None:- """Register a user, issuing a personal credential only when enabled."""- resolved_role = validate_account_user_role(role)- # Validate user_id format- verr = validate_user_id(user_id)- if verr:- raise InvalidArgumentError(verr)-- # Check account exists first- self._legacy.ensure_account_active(account_id)- account = self._legacy._accounts.get(account_id)- if account is None:- from openviking_cli.exceptions import NotFoundError-- raise NotFoundError(account_id, "account")- if user_id in account.users:- from openviking_cli.exceptions import AlreadyExistsError-- raise AlreadyExistsError(user_id, "user")-- user_info = {"role": resolved_role}- key = (- self._issue_user_key(account_id, user_id, user_info, seed)- if self._issue_user_keys- else None- )- account.users[user_id] = user_info+ if not self._issue_user_keys:+ await self._store.create_user(account_id, user_id, role)+ return None- try:- await self._legacy._save_users_json(- account_id, {user_id: user_info}, reject_existing_user_ids={user_id}- )- except Exception:- account.users.pop(user_id, None)- self._legacy._remove_key_index_entry(account_id, user_id, user_info)- raise+ key = generate_api_key(account_id, user_id, seed)+ await self._store.create_user_with_api_key(account_id, user_id, role, key)return key- async def begin_deletion(- self,- account_id: str,- user_id: str | None,- *,- task_id: str,- owner_account_id: str,- owner_user_id: str,- ) -> tuple[dict, bool]:- async with self._legacy.mutation_lock:- return await self._legacy.begin_deletion(- account_id,- user_id,- task_id=task_id,- owner_account_id=owner_account_id,- owner_user_id=owner_user_id,- )-- async def replace_deletion_task(- self,- account_id: str,- user_id: str | None,- *,- expected_task_id: str,- task_id: str,- owner_account_id: str,- owner_user_id: str,- ) -> dict:- async with self._legacy.mutation_lock:- return await self._legacy.replace_deletion_task(- account_id,- user_id,- expected_task_id=expected_task_id,- task_id=task_id,- owner_account_id=owner_account_id,- owner_user_id=owner_user_id,- )-- async def finish_deletion(self, account_id: str, user_id: str | None, task_id: str) -> bool:- async with self._legacy.mutation_lock:- return await self._legacy.finish_deletion(account_id, user_id, task_id)-- def get_deletion(self, account_id: str, user_id: str | None = None) -> Optional[dict]:- return self._legacy.get_deletion(account_id, user_id)-- def iter_deletions(self) -> list[tuple[str, str | None, dict]]:- return self._legacy.iter_deletions()-- def is_deleting(self, account_id: str, user_id: str | None = None) -> bool:- return self._legacy.is_deleting(account_id, user_id)-- def ensure_account_active(self, account_id: str) -> None:- self._legacy.ensure_account_active(account_id)-- async def regenerate_key(- self,- account_id: str,- user_id: str,- seed: Optional[str] = None,- ) -> str:- async with self._legacy.mutation_lock:- return await self._regenerate_key_unlocked(account_id, user_id, seed)-- async def _regenerate_key_unlocked(- self,- account_id: str,- user_id: str,- seed: Optional[str] = None,- ) -> str:- """Regenerate a user's API key. Old key is immediately invalidated.-- Generates new format key regardless of original format.- """+ async def regenerate_key(self, account_id, user_id, seed=None):if not self._issue_user_keys:raise FailedPreconditionError("Personal API keys are disabled in trusted mode")+ await self._require_manageable_user(account_id, user_id)+ key = generate_api_key(account_id, user_id, seed)+ await self._store.replace_active_user_api_key(account_id, user_id, key)+ return key- # Check account and user exist- self._legacy.ensure_account_active(account_id)- account = self._legacy._accounts.get(account_id)- if account is None:- from openviking_cli.exceptions import NotFoundError-- raise NotFoundError(account_id, "account")- if user_id not in account.users:- from openviking_cli.exceptions import NotFoundError-- raise NotFoundError(user_id, "user")- if account.users[user_id].get("deletion"):- raise FailedPreconditionError("User deletion is in progress")-- old_user_info = account.users[user_id]- self._legacy._remove_key_index_entry(account_id, user_id, old_user_info)- new_key = self._issue_user_key(account_id, user_id, old_user_info, seed)-- await self._legacy._save_users_json(account_id, {user_id: account.users[user_id]})- return new_key-- async def set_role(self, account_id: str, user_id: str, role: str) -> None:- """Update a user's role."""- async with self._legacy.mutation_lock:- await self._legacy.set_role(account_id, user_id, role)-- def get_accounts(- self,- name_filter: str | None = None,- limit: int | None = None,- page: int = 1,- query_filter: str | None = None,- ) -> list:- """List all accounts."""- return self._legacy.get_accounts(- name_filter=name_filter,- limit=limit,- page=page,- query_filter=query_filter,- )-- def get_users(- self,- account_id: str,- limit: int | None = 100,- name_filter: str | None = None,- role_filter: str | None = None,- expose_key: bool = True,- page: int = 1,- ) -> list:- """List all users in an account."""- return self._legacy.get_users(- account_id,- limit=limit,- name_filter=name_filter,- role_filter=role_filter,- expose_key=expose_key and self._issue_user_keys,- page=page,- )-- def get_users_page(- self,- account_id: str,- limit: int | None = 100,- name_filter: str | None = None,- role_filter: str | None = None,- expose_key: bool = True,- page: int = 1,- query_filter: str | None = None,- ) -> dict:- return self._legacy.get_users_page(- account_id,- limit=limit,- name_filter=name_filter,- role_filter=role_filter,- expose_key=expose_key and self._issue_user_keys,- page=page,- query_filter=query_filter,+ async def get_registered_user_role(self, account_id: str, user_id: str) -> Role | None:+ user = await self.get_user(account_id, user_id)+ return Role(user["role"]) if user else None++ async def resolve_oauth_identity(+ self, account_id: str, user_id: str, role: Role+ ) -> ResolvedIdentity:+ user = await self._require_authenticatable_user(account_id, user_id)+ if role.rank > Role(user["role"]).rank:+ raise UnauthenticatedError(+ "OAuth token's embedded role exceeds the user's current role; "+ "please re-authorize the client."+ )+ return ResolvedIdentity(+ role=role,+ account_id=account_id,+ user_id=user_id,+ from_oauth=True,)- def has_user(self, account_id: str, user_id: str) -> bool:- """Return True when the account registry contains the given user."""- return self._legacy.has_user(account_id, user_id)-- def get_user_role(self, account_id: str, user_id: str) -> Role:- """Return the role of the given user in the given account.-- Returns Role.USER if the account or user doesn't exist.- """- return self._legacy.get_user_role(account_id, user_id)-- def get_user_group_ids(self, account_id: str, user_id: str) -> tuple[str, ...]:- return self._legacy.get_user_group_ids(account_id, user_id)+ async def ensure_trusted_identities(self, identities):+ return await self._store.ensure_trusted_identities(identities)- async def create_group(self, account_id: str, group_id: str) -> dict:- return await self._legacy.create_group(account_id, group_id)+ async def begin_deletion(self, account_id, user_id, **owner):+ return await self._store.begin_deletion(account_id, user_id, **owner)- def get_groups(self, account_id: str) -> list[dict]:- return self._legacy.get_groups(account_id)+ async def replace_deletion_task(self, account_id, user_id, **owner):+ return await self._store.replace_deletion_task(account_id, user_id, **owner)- def get_group_members(self, account_id: str, group_id: str) -> list[str]:- return self._legacy.get_group_members(account_id, group_id)+ async def finish_deletion(self, account_id, user_id, task_id):+ return await self._store.finish_deletion(account_id, user_id, task_id)- async def add_group_member(self, account_id: str, group_id: str, user_id: str) -> bool:- return await self._legacy.add_group_member(account_id, group_id, user_id)+ async def get_deletion(self, account_id, user_id=None):+ return await self._store.get_deletion(account_id, user_id)- async def remove_group_member(- self, account_id: str, group_id: str, user_id: str- ) -> bool:- return await self._legacy.remove_group_member(account_id, group_id, user_id)+ async def iter_deletions(self):+ return await self._store.iter_deletions()- async def delete_group(self, account_id: str, group_id: str) -> None:- await self._legacy.delete_group(account_id, group_id)+ async def get_account(self, account_id):+ return await self._store.get_account(account_id)- def get_user_key_fingerprint(self, account_id: str, user_id: str) -> Optional[str]:- """SHA-256 hex digest of the user's stored API key value, or None.+ async def get_user(self, account_id, user_id):+ return await self._store.get_user(account_id, user_id)- Delegates to legacy. See ``LegacyAPIKeyManager.get_user_key_fingerprint``- for the rotation/deletion semantics OAuth relies on.- """- return self._legacy.get_user_key_fingerprint(account_id, user_id)-- # ---- Property proxies for backward compatibility with tests ------ @property- def _accounts(self):- return self._legacy._accounts-- @property- def _prefix_index(self):- return self._legacy._prefix_index-- @property- def _root_key(self):- return self._legacy._root_key+ @deprecated(+ "get_user_for_management is a FileStore compatibility path and will be removed.",+ category=None,+ )+ async def get_user_for_management(self, account_id, user_id):+ return await self._store.get_user_for_management(account_id, user_id)++ async def list_accounts(self, **filters):+ return await self._store.list_accounts(**filters)++ async def list_users_page(self, account_id, **filters):+ expose_key = filters.pop("expose_key", True)+ store_filters = {+ name: filters[name]+ for name in (+ "limit",+ "name_filter",+ "role_filter",+ "page",+ "query_filter",+ "fresh",+ )+ if name in filters+ }+ page = await self._store.list_users_page(+ account_id, **store_filters+ )+ if not expose_key or not self._issue_user_keys:+ page["key_count"] = 0+ for user in page["users"]:+ user.pop("api_key", None)+ user.pop("key_prefix", None)+ return page- @property- def _api_key_hashing_enabled(self):- return self._legacy._api_key_hashing_enabled+ async def has_user(self, account_id, user_id):+ return await self.get_user(account_id, user_id) is not None- # ---- Helper method proxies for backward compatibility ----+ async def get_user_group_ids(self, account_id, user_id):+ return await self._store.get_user_group_ids(account_id, user_id)- def _get_key_prefix(self, api_key: str) -> str:- return self._legacy._get_key_prefix(api_key)+ async def set_role(self, account_id, user_id, role):+ await self._store.set_role(account_id, user_id, role)- def _hash_api_key(self, api_key: str) -> str:- return self._legacy._hash_api_key(api_key)+ async def create_group(self, account_id, group_id):+ return await self._store.create_group(account_id, group_id)- def _verify_api_key(self, api_key: str, hashed_key: str) -> bool:- return self._legacy._verify_api_key(api_key, hashed_key)+ async def get_groups(self, account_id):+ return await self._store.get_groups(account_id)- async def _read_json(self, path: str) -> Optional[dict]:- return await self._legacy._read_json(path)+ async def get_group_members(self, account_id, group_id):+ return await self._store.get_group_members(account_id, group_id)- async def _write_json(self, path: str, data: dict) -> None:- return await self._legacy._write_json(path, data)+ async def add_group_member(self, account_id, group_id, user_id):+ return await self._store.add_group_member(account_id, group_id, user_id)- async def _ensure_parent_dirs_async(self, path: str) -> None:- return await self._legacy._ensure_parent_dirs_async(path)+ async def remove_group_member(self, account_id, group_id, user_id):+ return await self._store.remove_group_member(account_id, group_id, user_id)- async def _save_accounts_json(self, **kwargs) -> set[str]:- return await self._legacy._save_accounts_json(**kwargs)+ async def delete_group(self, account_id, group_id):+ await self._store.delete_group(account_id, group_id)- async def _save_users_json(self, account_id: str) -> None:- return await self._legacy._save_users_json(account_id)+ async def get_user_key_fingerprint(self, account_id, user_id):+ return await self._store.get_user_key_fingerprint(account_id, user_id)diff --git a/openviking/server/app.py b/openviking/server/app.pyindex 3e0186dfd..22fdcade8 100644--- a/openviking/server/app.py+++ b/openviking/server/app.py@@ -669,14 +669,11 @@ def create_app(or "http://127.0.0.1:1933")- # Late-binding role resolver: app.state.api_key_manager is wired- # during lifespan, after the provider is constructed. Lambda- # closes over `app` and looks up at call time.- def _current_role(account_id: str, user_id: str) -> Role:- mgr = getattr(app.state, "api_key_manager", None)- if mgr is None or not hasattr(mgr, "get_user_role"):+ async def _current_role(account_id: str, user_id: str) -> Role:+ manager = getattr(app.state, "api_key_manager", None)+ if manager is None:return Role.USER- return mgr.get_user_role(account_id, user_id)+ return await manager.get_registered_user_role(account_id, user_id) or Role.USER_route_provider = OpenVikingOAuthProvider(store=_route_store,diff --git a/openviking/server/auth/__init__.py b/openviking/server/auth/__init__.pyindex 9f2509ca3..2230371a9 100644--- a/openviking/server/auth/__init__.py+++ b/openviking/server/auth/__init__.py@@ -92,16 +92,20 @@ def _get_plugin(request: Request):return plugin-def resolve_group_ids(request: Request, account_id: str, user_id: str) -> tuple[str, ...]:+def _uses_local_account_store(plugin) -> bool:+ """Whether request authorization is backed by server-managed identities."""+ return plugin.auth_mode in (AuthMode.API_KEY.value, AuthMode.TRUSTED.value)+++async def resolve_group_ids(request: Request, account_id: str, user_id: str) -> tuple[str, ...]:"""Resolve server-managed account groups for a request identity."""manager = getattr(request.app.state, "api_key_manager", None)- if manager is None:+ if manager is None or not hasattr(manager, "get_user_group_ids"):return ()- resolver = getattr(manager, "get_user_group_ids", None)- return tuple(resolver(account_id, user_id)) if resolver is not None else ()+ return tuple(await manager.get_user_group_ids(account_id, user_id))-def _build_request_context(+async def _build_request_context(request: Request,identity: ResolvedIdentity,*,@@ -115,23 +119,25 @@ def _build_request_context(ctx = RequestContext(user=UserIdentifier(account_id, user_id),role=identity.role,- group_ids=resolve_group_ids(request, account_id, user_id),+ group_ids=(+ await resolve_group_ids(request, account_id, user_id)+ if identity.role != Role.ROOT and _uses_local_account_store(plugin)+ else ()+ ),actor_peer_id=actor_peer_id,from_oauth=identity.from_oauth,api_key=api_key,)manager = getattr(request.app.state, "api_key_manager", None)- is_deleting = getattr(manager, "is_deleting", None)+ deletion = Noneif (- ctx.role != Role.ROOT- and callable(is_deleting)- and is_deleting(ctx.account_id, ctx.user.user_id)+ _uses_local_account_store(plugin)+ and ctx.role != Role.ROOT+ and manager is not None+ and hasattr(manager, "get_deletion")):- deletion = (- manager.get_deletion(ctx.account_id)- or manager.get_deletion(ctx.account_id, ctx.user.user_id)- or {}- )+ deletion = await manager.get_deletion(ctx.account_id, ctx.user.user_id)+ if deletion is not None:raise FailedPreconditionError("Identity deletion is in progress",details={"task_id": deletion.get("task_id")},@@ -152,6 +158,10 @@ async def resolve_identity(x_openviking_user: Optional[str] = Header(None, alias="X-OpenViking-User"),) -> ResolvedIdentity:"""Resolve API key to identity via the active auth plugin."""+ if x_api_key is None:+ x_api_key = request.headers.get("X-API-Key")+ if authorization is None:+ authorization = request.headers.get("Authorization")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)@@ -173,7 +183,7 @@ async def get_request_context(authorization_ctx: Optional[str] = Header(None, alias="Authorization"),) -> RequestContext:"""Convert ResolvedIdentity to RequestContext."""- return _build_request_context(+ return await _build_request_context(request,identity,actor_peer_id=normalize_actor_peer_header(x_openviking_actor_peer),@@ -188,7 +198,7 @@ async def get_session_request_context(authorization_ctx: Optional[str] = Header(None, alias="Authorization"),) -> RequestContext:"""Build a Session context without accepting an actor peer view."""- return _build_request_context(+ return await _build_request_context(request,identity,api_key=_extract_api_key(x_api_key_ctx, authorization_ctx),@@ -223,14 +233,16 @@ async def get_upload_request_context(request.state.signed_upload = consumedif _auth_mode(request) == AuthMode.API_KEY:manager = get_api_key_manager_or_raise(request)- if not manager.has_user(consumed.account_id, consumed.user_id):+ current_role = await manager.get_registered_user_role(+ consumed.account_id, consumed.user_id+ )+ if current_role is None:raise UnauthenticatedError("Upload token's user no longer exists")- current_role = Role(manager.get_user_role(consumed.account_id, consumed.user_id))if Role(consumed.role).rank > current_role.rank:raise UnauthenticatedError("Upload token's role exceeds the user's current role; request a new upload")- return _build_request_context(+ return await _build_request_context(request,ResolvedIdentity(role=consumed.role,@@ -244,7 +256,7 @@ async def get_upload_request_context(ctx = RequestContext(user=UserIdentifier(consumed.account_id, consumed.user_id),role=Role.USER,- group_ids=resolve_group_ids(request, consumed.account_id, consumed.user_id),+ group_ids=await resolve_group_ids(request, consumed.account_id, consumed.user_id),# Actor peer comes from the token (bound at mint time from the trusted MCP# context), never from this upload request's headers, so server-side# auto-ingest keeps the caller's peer scope for reason-memory routing.@@ -331,8 +343,7 @@ def require_auth_role(*allowed_roles: Role):"Admin API authentication failed: unable to resolve request context.")- manager = getattr(request.app.state, "api_key_manager", None)- if manager is None:+ if getattr(request.app.state, "api_key_manager", None) is None:raise PermissionDeniedError(_DEV_MODE_ADMIN_API_MESSAGE)if ctx.role not in allowed_roles:@@ -369,11 +380,7 @@ def require_auth_root_or_admin(func):def get_api_key_manager_or_raise(request: Request):- """Get APIKeyManager from app state or raise appropriate error.-- Raises:- PermissionDeniedError: When no APIKeyManager is available.- """+ """Return the compatibility management facade exposed by the auth mode."""manager = getattr(request.app.state, "api_key_manager", None)if manager is None:raise PermissionDeniedError(_DEV_MODE_ADMIN_API_MESSAGE)@@ -388,9 +395,3 @@ def should_expose_user_key(request: Request) -> bool:if not isinstance(config, ServerConfig):return Truereturn config.get_effective_auth_mode() != "trusted"---def registry_watcher_running(request: Request) -> bool:- plugin = getattr(request.app.state, "auth_plugin", None)- watch_task = getattr(plugin, "_watch_task", None)- return watch_task is not None and not watch_task.done()diff --git a/openviking/server/auth/plugin.py b/openviking/server/auth/plugin.pyindex 4585393d8..b58ee55c2 100644--- a/openviking/server/auth/plugin.py+++ b/openviking/server/auth/plugin.py@@ -105,14 +105,6 @@ class AuthPlugin(abc.ABC):"""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-async def shutdown(self) -> None:"""Release resources acquired during ``initialize`` (default no-op; override to cancel)."""passdiff --git a/openviking/server/auth/plugins/api_key.py b/openviking/server/auth/plugins/api_key.pyindex 126357aee..686444728 100644--- a/openviking/server/auth/plugins/api_key.py+++ b/openviking/server/auth/plugins/api_key.py@@ -4,19 +4,15 @@from __future__ import annotations-import asyncioimport sysfrom typing import Optionalfrom fastapi import Request-from openviking.server.api_keys import APIKeyManagerfrom openviking.server.auth.plugin import AuthPluginfrom openviking.server.identity import ResolvedIdentity, Role+from openviking.server.store_assembly import build_api_key_managerfrom openviking_cli.exceptions import PermissionDeniedError, UnauthenticatedError-from openviking_cli.utils import get_logger--_watch_logger = get_logger(__name__)_API_KEY_ROOT_ALLOWED_PATHS = {"/api/v1/system/status",@@ -54,7 +50,7 @@ def _remove_header(request: Request, name: bytes) -> None:class ApiKeyAuthPlugin(AuthPlugin):- """API key mode: resolve identity via APIKeyManager.+ """Compose credential verification and local identity resolution.Supports OAuth bearer tokens layered on top of API keys."""@@ -62,8 +58,7 @@ class ApiKeyAuthPlugin(AuthPlugin):auth_mode = "api_key"def __init__(self) -> None:- # Background key-store poll task; None when the watcher is disabled.- self._watch_task: Optional[asyncio.Task] = None+ self._api_key_manager = Noneasync def resolve_identity(self,@@ -73,9 +68,7 @@ class ApiKeyAuthPlugin(AuthPlugin):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")+ manager = request.app.state.api_key_managerif not api_key:raise UnauthenticatedError("Missing API Key when resolving identity.")@@ -90,7 +83,7 @@ class ApiKeyAuthPlugin(AuthPlugin):if oauth_identity is not None:return oauth_identity- identity = api_key_manager.resolve(api_key)+ identity = await manager.resolve_identity(api_key)identity.account_id = identity.account_id or "default"identity.user_id = identity.user_id or "default"@@ -133,35 +126,22 @@ class ApiKeyAuthPlugin(AuthPlugin):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)+ manager = request.app.state.api_key_manager+ current_fp = await 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."- )+ identity = await manager.resolve_oauth_identity(+ record.account_id,+ record.user_id,+ Role(record.role),+ )# Silently ignore identity assertion headers in api_key mode.if x_openviking_account:@@ -169,12 +149,7 @@ class ApiKeyAuthPlugin(AuthPlugin):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,- )+ return identitydef validate_config(self, config) -> None:if config.root_api_key and config.root_api_key != "":@@ -204,65 +179,27 @@ class ApiKeyAuthPlugin(AuthPlugin):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(+ manager = build_api_key_manager(root_key=config.root_api_key,viking_fs=service.viking_fs,api_key_hashing_enabled=config.api_key_hashing_enabled,+ account_store_provider=config.account_store.provider,+ account_store_params=config.account_store.params,+ account_store_watch_enabled=config.api_key_watch_enabled,+ account_store_watch_interval_seconds=config.api_key_watch_interval_seconds,+ issue_user_keys=True,)- await api_key_manager.load()- app.state.api_key_manager = api_key_manager-- # Read replicas never rewrite the store, so poll for writer-side changes.- if getattr(config, "api_key_watch_enabled", False):- interval = getattr(config, "api_key_watch_interval_seconds", 30.0)- self._watch_task = asyncio.create_task(self._watch_key_store(api_key_manager, interval))- _watch_logger.info("API key store watcher started (interval=%.1fs)", interval)+ await manager.load()+ self._api_key_manager = manager+ app.state.api_key_manager = managerasync def shutdown(self) -> None:- """Cancel the background key-store watcher, if running."""- if self._watch_task is None:- return- self._watch_task.cancel()+ manager = getattr(self, "_api_key_manager", None)try:- await self._watch_task- except asyncio.CancelledError:- pass- except Exception: # noqa: BLE001- _watch_logger.warning("API key store watcher exited with error", exc_info=True)+ if manager is not None:+ await manager.close()finally:- self._watch_task = None-- @staticmethod- async def _watch_key_store(api_key_manager: APIKeyManager, interval: float) -> None:- """Poll the key store and reload on signature change; errors are swallowed to survive."""- # Guard against a misconfigured non-positive interval spinning hot.- interval = interval if interval and interval > 0 else 30.0- try:- last_signature = await api_key_manager.compute_store_signature()- except Exception: # noqa: BLE001- _watch_logger.warning(- "Initial key-store signature failed; watcher will retry", exc_info=True- )- last_signature = None-- while True:- await asyncio.sleep(interval)- try:- signature = await api_key_manager.compute_store_signature()- except Exception: # noqa: BLE001- _watch_logger.debug("Key-store signature check failed", exc_info=True)- continue-- if signature == last_signature:- continue-- try:- await api_key_manager.reload()- last_signature = signature- _watch_logger.info("API key store change detected; in-memory index reloaded")- except Exception: # noqa: BLE001- # Keep last_signature unchanged so we retry the reload next tick.- _watch_logger.warning("API key store reload failed; will retry", exc_info=True)+ self._api_key_manager = Nonedef get_request_context_checks(self,diff --git a/openviking/server/auth/plugins/dev.py b/openviking/server/auth/plugins/dev.pyindex ca73d5f0c..17ce43a3a 100644--- a/openviking/server/auth/plugins/dev.py+++ b/openviking/server/auth/plugins/dev.py@@ -67,8 +67,5 @@ class DevAuthPlugin(AuthPlugin):"""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/ldap.py b/openviking/server/auth/plugins/ldap.pyindex 2a74982d3..61a5647a5 100644--- a/openviking/server/auth/plugins/ldap.py+++ b/openviking/server/auth/plugins/ldap.py@@ -490,11 +490,6 @@ class LDAPAuthPlugin(AuthPlugin):"LDAP auth plugin initialized with host=%s", self._config.host)- def requires_api_key_manager(self) -> bool:- """LDAP does not map external identities to admin roles, so no- APIKeyManager is needed. Admin API access is gated by role checks."""- return False-def can_skip_api_key_for_bot_proxy(self) -> bool:"""LDAP does not declare bot-proxy compatibility until VikingBotnatively understands the ``ldap`` auth mode (mode inference, Basicdiff --git a/openviking/server/auth/plugins/oidc.py b/openviking/server/auth/plugins/oidc.pyindex 3fb152356..83392200f 100644--- a/openviking/server/auth/plugins/oidc.py+++ b/openviking/server/auth/plugins/oidc.py@@ -352,11 +352,6 @@ class OIDCAuthPlugin(AuthPlugin):self._effective_audience,)- def requires_api_key_manager(self) -> bool:- """OIDC does not map external identities to admin roles, so no- APIKeyManager is needed. Admin API access is gated by role checks."""- return False-def can_skip_api_key_for_bot_proxy(self) -> bool:"""OIDC does not declare bot-proxy compatibility until VikingBotnatively understands the ``oidc`` auth mode and can propagate thediff --git a/openviking/server/auth/plugins/trusted.py b/openviking/server/auth/plugins/trusted.pyindex f31c352a3..45d61e7c0 100644--- a/openviking/server/auth/plugins/trusted.py+++ b/openviking/server/auth/plugins/trusted.py@@ -16,6 +16,7 @@ from openviking.core.identifiers import validate_account_id, validate_user_idfrom openviking.server.api_keys import APIKeyManagerfrom openviking.server.auth.plugin import AuthPluginfrom openviking.server.identity import ResolvedIdentity, Role+from openviking.server.store_assembly import build_api_key_managerfrom openviking_cli.exceptions import InvalidArgumentError, UnauthenticatedErrorfrom openviking_cli.utils import get_logger@@ -64,11 +65,16 @@ def _is_trusted_admin_path(path: str) -> bool:return path == "/api/v1/admin" or path.startswith("/api/v1/admin/")-def _asserted_role_from_header(request: Request) -> Optional[Role]:+def _asserted_role_from_header(request: Request, *, allow_assertion: bool) -> Optional[Role]:raw_role = request.headers.get(_TRUSTED_ROLE_HEADER)normalized_role = _normalize_request_value(raw_role)if normalized_role is None:return None+ if not allow_assertion:+ raise InvalidArgumentError(+ f"{_TRUSTED_ROLE_HEADER} requires trusted mode with Root API Key enabled."+ )+role = normalized_role.lower()if role not in _TRUSTED_ASSERTABLE_ROLES:raise InvalidArgumentError(f"{_TRUSTED_ROLE_HEADER} must be one of: user, admin.")@@ -79,7 +85,7 @@ class TrustedAuthPlugin(AuthPlugin):"""Trusted mode: trust X-OpenViking-Account/User headers.Requires a matching root_api_key on every authenticated request. Role is looked up from- APIKeyManager if the user exists, otherwise defaults to USER.+ AccountStore if the user exists, otherwise defaults to USER."""auth_mode = "trusted"@@ -93,6 +99,7 @@ class TrustedAuthPlugin(AuthPlugin):self._pending_count = 0self._in_flight_count = 0self._flush_task: Optional[asyncio.Task] = None+ self._flush_lock = asyncio.Lock()async def resolve_identity(self,@@ -102,19 +109,20 @@ class TrustedAuthPlugin(AuthPlugin):x_openviking_account: Optional[str] = None,x_openviking_user: Optional[str] = None,) -> ResolvedIdentity:+ if api_key is None:+ api_key = request.headers.get("X-API-Key")configured_root_api_key = request.app.state.config.root_api_keyif not api_key:raise UnauthenticatedError("Missing API Key in trusted mode. Send X-API-Key with the value of "- "server.root_api_key from the server's ov.conf. In Web Studio, enter "- "this value in Connection settings > Root or Admin API Key."+ "server.root_api_key from the server's ov.conf.")if not configured_root_api_key or not hmac.compare_digest(api_key, configured_root_api_key):raise UnauthenticatedError("Invalid API Key in trusted mode. The supplied key must match ""server.root_api_key in the server's ov.conf.")- asserted_role = _asserted_role_from_header(request)+ asserted_role = _asserted_role_from_header(request, allow_assertion=True)explicit_account_id, explicit_user_id = _explicit_identity_from_request(request)if (@@ -153,24 +161,31 @@ class TrustedAuthPlugin(AuthPlugin):raise InvalidArgumentError("Trusted mode requests must include " + " and ".join(missing_fields) + ".")+_validate_trusted_identity(effective_account_id, effective_user_id)- api_key_manager = self._api_key_manager- trusted_role = Role.USER+ local_role = Noneif asserted_role is not None:trusted_role = asserted_role- elif api_key_manager:- looked_up_role = api_key_manager.get_user_role(effective_account_id, effective_user_id)- if looked_up_role is not None:- trusted_role = looked_up_role+ else:+ if self._api_key_manager and effective_account_id and effective_user_id:+ local_role = await self._api_key_manager.get_registered_user_role(+ effective_account_id, effective_user_id+ )+ trusted_role = local_role or Role.USERidentity = ResolvedIdentity(role=trusted_role,account_id=effective_account_id,user_id=effective_user_id,)- if self.should_auto_register_trusted_identity(request):- self._queue_trusted_identity(effective_account_id, effective_user_id)+ if (+ self.should_auto_register_trusted_identity(request)+ and not is_admin_path+ and effective_account_id+ and effective_user_id+ ):+ await self._queue_trusted_identity(effective_account_id, effective_user_id)return identitydef validate_config(self, config) -> None:@@ -184,15 +199,19 @@ class TrustedAuthPlugin(AuthPlugin):sys.exit(1)async def initialize(self, app, service, config) -> None:- api_key_manager = APIKeyManager(+ manager = build_api_key_manager(root_key=config.root_api_key,viking_fs=service.viking_fs,api_key_hashing_enabled=config.api_key_hashing_enabled,+ account_store_provider=config.account_store.provider,+ account_store_params=config.account_store.params,+ account_store_watch_enabled=config.api_key_watch_enabled,+ account_store_watch_interval_seconds=config.api_key_watch_interval_seconds,issue_user_keys=False,)- await api_key_manager.load()- self._api_key_manager = api_key_manager- app.state.api_key_manager = api_key_manager+ await manager.load()+ self._api_key_manager = manager+ app.state.api_key_manager = managerself._flush_interval_seconds = config.trusted_identity_flush_interval_secondsself._pending_max_size = config.trusted_identity_pending_max_sizeif self._flush_interval_seconds > 0:@@ -205,12 +224,13 @@ class TrustedAuthPlugin(AuthPlugin):"""Return whether this trusted request's identity should be batch registered."""return self._flush_interval_seconds > 0- def _queue_trusted_identity(self, account_id: str, user_id: str) -> None:- if self._api_key_manager and (- self._api_key_manager.is_deleting(account_id, user_id)- or self._api_key_manager.has_user(account_id, user_id)- ):- return+ async def _queue_trusted_identity(self, account_id: str, user_id: str) -> None:+ manager = self._api_key_manager+ if manager is not None:+ if await manager.get_deletion(account_id, user_id) is not None:+ return+ if await manager.get_user(account_id, user_id) is not None:+ returnif user_id in self._in_flight.get(account_id, set()):returnif user_id in self._pending.get(account_id, set()):@@ -226,6 +246,10 @@ class TrustedAuthPlugin(AuthPlugin):self._pending_count += 1async def flush_trusted_identities(self) -> None:+ async with self._flush_lock:+ await self._flush_batch()++ async def _flush_batch(self) -> None:if self._api_key_manager is None or not self._pending:returnbatch = self._pending@@ -235,14 +259,14 @@ class TrustedAuthPlugin(AuthPlugin):self._in_flight = batchtry:await self._api_key_manager.ensure_trusted_identities(batch)- except Exception:+ except BaseException as exc:pending_after_failure = self._pendingfor account_id, user_ids in batch.items():pending_after_failure.setdefault(account_id, set()).update(user_ids)self._pending = pending_after_failureself._pending_count += self._in_flight_count- self._in_flight = {}- self._in_flight_count = 0+ if not isinstance(exc, Exception):+ raiselogger.warning("Trusted identity batch registration failed; will retry", exc_info=True)finally:self._in_flight = {}@@ -268,7 +292,18 @@ class TrustedAuthPlugin(AuthPlugin):passfinally:self._flush_task = None- await self.flush_trusted_identities()+ try:+ await self.flush_trusted_identities()+ finally:+ manager = self._api_key_manager+ try:+ if manager is not None:+ await manager.close()+ finally:+ self._api_key_manager = None++ def can_skip_api_key_for_bot_proxy(self) -> bool:+ return Truedef get_request_context_checks(self,diff --git a/openviking/server/config.py b/openviking/server/config.pyindex 04322a090..798642b4a 100644--- a/openviking/server/config.py+++ b/openviking/server/config.py@@ -301,6 +301,21 @@ class ToolOutputExternalizationConfig(BaseModel):failure_mode: Literal["reject", "preserve_raw", "preview_only"] = "preserve_raw"+class AccountStoreConfig(BaseModel):+ """Startup-only selection of the complete account store provider."""++ provider: str = "file"+ params: Dict[str, Any] = Field(default_factory=dict)++ @field_validator("provider")+ @classmethod+ def _validate_provider(cls, value: str) -> str:+ normalized = value.strip().lower()+ if not normalized:+ raise ValueError("account_store.provider must not be empty")+ return normalized++class ServerConfig(BaseModel):host: str = "127.0.0.1"port: int = 1933@@ -338,6 +353,7 @@ class ServerConfig(BaseModel):api_key_watch_enabled: bool = False# Poll interval; each check only stats registry files and reads fully on change.api_key_watch_interval_seconds: float = 30.0+ account_store: AccountStoreConfig = Field(default_factory=AccountStoreConfig)# Trusted-mode identity registration is batched in memory; 0 disables it.trusted_identity_flush_interval_seconds: float = Field(300.0, ge=0)trusted_identity_pending_max_size: int = Field(10_000, gt=0)diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.pyindex f6faba5c1..13f22ee69 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -62,7 +62,6 @@ from openviking.server.auth import (_extract_api_key,get_api_key_manager_or_raise,normalize_actor_peer_header,- registry_watcher_running,resolve_identity,should_expose_user_key,)@@ -200,7 +199,7 @@ class _IdentityASGIMiddleware:actor_peer_id = normalize_actor_peer_header(request.headers.get("x-openviking-actor-peer"))- ctx = _build_request_context(+ ctx = await _build_request_context(request,identity,actor_peer_id=actor_peer_id,@@ -373,9 +372,7 @@ async def list_users(if include_credentials and not should_expose_user_key(request):raise PermissionDeniedError("Credential disclosure is disabled in trusted auth mode")manager = get_api_key_manager_or_raise(request)- if not registry_watcher_running(request):- await manager.refresh_account_users_from_store(ctx.account_id)- result = manager.get_users_page(+ result = await manager.list_users_page(ctx.account_id,limit=limit,page=page,@@ -397,10 +394,8 @@ async def list_groups(context: Context) -> dict[str, Any]:"""ctx = _get_ctx()manager = get_api_key_manager_or_raise(context.request_context.request)- await manager.ensure_account_groups_loaded(ctx.account_id)- return {- "groups": [{"group_id": group["group_id"]} for group in manager.get_groups(ctx.account_id)]- }+ groups = await manager.get_groups(ctx.account_id)+ return {"groups": [{"group_id": group["group_id"]} for group in groups]}@_mcp_error_results()diff --git a/openviking/server/oauth/provider.py b/openviking/server/oauth/provider.pyindex e713655fc..5e6edd82e 100644--- a/openviking/server/oauth/provider.py+++ b/openviking/server/oauth/provider.py@@ -12,8 +12,9 @@ strings keyed by their SHA-256 hash, so this module contains no cryptography.from __future__ import annotations+import inspectimport secrets-from typing import Callable, Optional+from typing import Awaitable, Callable, Optionalfrom urllib.parse import urlencodefrom mcp.server.auth.provider import (@@ -97,7 +98,7 @@ class OpenVikingOAuthProvider(refresh_token_ttl_seconds: int = 30 * 24 * 3600,auth_code_ttl_seconds: int = 300,authorize_page_path: str = DEFAULT_AUTHORIZE_PAGE,- role_resolver: Optional[Callable[[str, str], "Role"]] = None,+ role_resolver: Optional[Callable[[str, str], Role | Awaitable[Role]]] = None,) -> None:self._store = storeself._issuer = issuer.rstrip("/")@@ -294,17 +295,14 @@ class OpenVikingOAuthProvider(if self._role_resolver is not None:try:token_role = Role(refresh_token.role)- current_role = Role(- self._role_resolver(refresh_token.account_id, refresh_token.user_id)- )- except (ValueError, Exception): # noqa: BLE001- token_role = None- current_role = None- if (- token_role is not None- and current_role is not None- and token_role.rank > current_role.rank- ):+ resolved = self._role_resolver(refresh_token.account_id, refresh_token.user_id)+ current_role = Role(await resolved if inspect.isawaitable(resolved) else resolved)+ except Exception as exc:+ raise TokenError(+ error="invalid_grant",+ error_description="Unable to validate current identity; re-authorize the client",+ ) from exc+ if token_role.rank > current_role.rank:raise TokenError(error="invalid_grant",error_description=(diff --git a/openviking/server/oauth/router.py b/openviking/server/oauth/router.pyindex 0dfb46204..81505e121 100644--- a/openviking/server/oauth/router.py+++ b/openviking/server/oauth/router.py@@ -473,10 +473,10 @@ async def oauth_verify(# If the verifier has no resolvable key (ROOT, trusted-mode requester# without a real key), refuse to mint OAuth: there's no key to bind to,# so we cannot honor the "OAuth lifetime ≤ key lifetime" invariant.- api_key_manager = getattr(request.app.state, "api_key_manager", None)+ manager = getattr(request.app.state, "api_key_manager", None)verifier_fp: Optional[str] = None- if api_key_manager is not None and hasattr(api_key_manager, "get_user_key_fingerprint"):- verifier_fp = api_key_manager.get_user_key_fingerprint(+ if manager is not None:+ verifier_fp = await manager.get_user_key_fingerprint(ctx.user.account_id, ctx.user.user_id)if not verifier_fp:diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.pyindex 27d591bc1..afe7d357c 100644--- a/openviking/server/routers/admin.py+++ b/openviking/server/routers/admin.py@@ -16,7 +16,6 @@ from openviking.server.api_keys.models import validate_account_user_rolefrom openviking.server.auth import (get_api_key_manager_or_raise,get_request_context,- registry_watcher_running,require_auth_root,require_auth_root_or_admin,should_expose_user_key,@@ -227,7 +226,7 @@ async def set_agent_evolution_status(def _get_api_key_manager(request: Request):- """Get APIKeyManager from app state."""+ """Return API key management operations for compatibility callers."""return get_api_key_manager_or_raise(request)@@ -246,21 +245,18 @@ def _check_account_access(ctx: RequestContext, account_id: str) -> None:raise PermissionDeniedError(f"ADMIN can only manage account: {ctx.account_id}")-async def _check_account_exists(- request: Request, account_id: str, *, refresh_scope: str | None = None-):+async def _check_account_exists(request: Request, account_id: str):manager = getattr(request.app.state, "api_key_manager", None)if manager is None:return None- watcher_running = registry_watcher_running(request)- if not watcher_running:- await manager.refresh_accounts_from_store()- accounts = manager.get_accounts()- if not any(item.get("account_id") == account_id for item in accounts):+ account = await manager.get_account(account_id)+ if account is None:raise NotFoundError(account_id, "account")- manager.ensure_account_active(account_id)- if refresh_scope is not None and not watcher_running:- await manager.refresh_account_users_from_store(refresh_scope)+ if account["status"] != "active":+ raise FailedPreconditionError(+ "Account is not active",+ details={"task_id": account.get("task_id")},+ )return manager@@ -343,9 +339,9 @@ async def _rollback_account_creation() -> None:"""Compensate resources created after the account registry entry.- ``APIKeyManager.create_account`` already rolls back its own registry writes.- This covers the later workspace, user-config and runtime-config steps when- one of them fails.+ Account creation and its initial API key are committed atomically by the+ AccountStore. This covers the later workspace, user-config and runtime-config+ steps when one of them fails."""if deletion_service is not None and actor is not None:try:@@ -398,7 +394,7 @@ async def _check_user_exists(request: Request, account_id: str, user_id: str, manager=None) -> None:manager = manager or _get_api_key_manager(request)- if not manager.has_user(account_id, user_id):+ if await manager.get_user_for_management(account_id, user_id) is None:raise NotFoundError(user_id, "user")@@ -519,10 +515,9 @@ async def list_accounts(ctx: RequestContext = Depends(get_request_context),):"""List accounts in creation order. `name` supports wildcard (* and ?) matching."""- manager = _get_api_key_manager(request)- if not registry_watcher_running(request):- await manager.refresh_accounts_from_store()- accounts = manager.get_accounts(name_filter=name, limit=limit, page=page, query_filter=query)+ accounts = await _get_api_key_manager(request).list_accounts(+ name_filter=name, limit=limit, page=page, query_filter=query+ )return Response(status="ok", result=accounts)@@ -994,15 +989,12 @@ async def list_users("""List users in an account, in creation order. `name` supports wildcard (* and ?) matching."""_check_account_access(ctx, account_id)manager = _get_api_key_manager(request)- if not registry_watcher_running(request):- await manager.refresh_account_users_from_store(account_id)- expose_key = should_expose_user_key(request)- users = manager.get_users_page(+ users = await manager.list_users_page(account_id,limit=limit,name_filter=name,role_filter=role,- expose_key=expose_key or not include_credentials,+ expose_key=should_expose_user_key(request) or not include_credentials,page=page,query_filter=query,)@@ -1011,6 +1003,8 @@ async def list_users({"user_id": user["user_id"],"role": user["role"],+ # A key prefix identifies a hash-only credential, which cannot+ # be supplied to server-side Gateway or Bot Studio bindings."api_key_available": bool(user.get("api_key")),}for user in users["users"]@@ -1028,7 +1022,7 @@ async def get_user_settings():"""Return the configured and effective memory policy for one User."""_check_account_access(ctx, account_id)- manager = await _check_account_exists(request, account_id, refresh_scope=account_id)+ manager = await _check_account_exists(request, account_id)await _check_user_exists(request, account_id, user_id, manager)service = get_service()if service.viking_fs is None:@@ -1060,7 +1054,7 @@ async def patch_user_settings():"""Update or clear the allowlisted User memory policy without restarting."""_check_account_access(ctx, account_id)- manager = await _check_account_exists(request, account_id, refresh_scope=account_id)+ manager = await _check_account_exists(request, account_id)await _check_user_exists(request, account_id, user_id, manager)service = get_service()if service.viking_fs is None:@@ -1112,8 +1106,7 @@ async def set_user_role(_check_account_access(ctx, account_id)if body.role != Role.ADMIN:raise InvalidArgumentError("set_user_role only supports promotion to admin.")- manager = _get_api_key_manager(request)- await manager.set_role(account_id, user_id, Role.ADMIN)+ await _get_api_key_manager(request).set_role(account_id, user_id, Role.ADMIN)return Response(status="ok",result={@@ -1156,7 +1149,9 @@ async def create_group(ctx: RequestContext = Depends(get_request_context),):_check_account_access(ctx, account_id)- result = await _get_api_key_manager(request).create_group(account_id, body.group_id)+ result = await _get_api_key_manager(request).create_group(+ account_id, body.group_id+ )return Response(status="ok", result=result)@@ -1168,9 +1163,7 @@ async def list_groups(ctx: RequestContext = Depends(get_request_context),):_check_account_access(ctx, account_id)- manager = _get_api_key_manager(request)- await manager.ensure_account_groups_loaded(account_id)- result = manager.get_groups(account_id)+ result = await _get_api_key_manager(request).get_groups(account_id)return Response(status="ok", result=result)@@ -1196,9 +1189,9 @@ async def list_group_members(ctx: RequestContext = Depends(get_request_context),):_check_account_access(ctx, account_id)- manager = _get_api_key_manager(request)- await manager.ensure_account_groups_loaded(account_id)- members = manager.get_group_members(account_id, group_id)+ members = await _get_api_key_manager(request).get_group_members(+ account_id, group_id+ )return Response(status="ok", result={"group_id": group_id, "members": members})@@ -1212,7 +1205,9 @@ async def add_group_member(ctx: RequestContext = Depends(get_request_context),):_check_account_access(ctx, account_id)- added = await _get_api_key_manager(request).add_group_member(account_id, group_id, user_id)+ added = await _get_api_key_manager(request).add_group_member(+ account_id, group_id, user_id+ )return Response(status="ok", result={"added": added})@@ -1226,5 +1221,7 @@ async def remove_group_member(ctx: RequestContext = Depends(get_request_context),):_check_account_access(ctx, account_id)- removed = await _get_api_key_manager(request).remove_group_member(account_id, group_id, user_id)+ removed = await _get_api_key_manager(request).remove_group_member(+ account_id, group_id, user_id+ )return Response(status="ok", result={"removed": removed})diff --git a/openviking/server/store_assembly.py b/openviking/server/store_assembly.pynew file mode 100644index 000000000..64741d189--- /dev/null+++ b/openviking/server/store_assembly.py@@ -0,0 +1,73 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Application-scoped dependency binding for complete account stores."""++from __future__ import annotations++from typing import TYPE_CHECKING, cast++from openviking.server.account_stores.base import AccountStore+from openviking.server.api_keys.legacy import FileStore+from openviking.storage.viking_fs import VikingFS+from openviking_cli.exceptions import InvalidArgumentError++if TYPE_CHECKING:+ from openviking.server.api_keys.new import APIKeyManager+++def build_api_key_manager(+ root_key: str,+ viking_fs: VikingFS | None,+ *,+ api_key_hashing_enabled: bool = False,+ account_store_provider: str = "file",+ account_store_params: dict[str, object] | None = None,+ account_store_watch_enabled: bool = False,+ account_store_watch_interval_seconds: float = 30.0,+ issue_user_keys: bool = True,+ account_store: AccountStore | None = None,+) -> APIKeyManager:+ """Assemble the API key facade over one complete account store."""+ from openviking.server.api_keys.new import APIKeyManager++ provider = account_store_provider.strip().lower()+ store = build_account_store(+ viking_fs=viking_fs,+ api_key_hashing_enabled=api_key_hashing_enabled,+ account_store_provider=provider,+ account_store_params=account_store_params,+ account_store_watch_enabled=account_store_watch_enabled,+ account_store_watch_interval_seconds=account_store_watch_interval_seconds,+ account_store=account_store,+ )+ return APIKeyManager(root_key, store, issue_user_keys=issue_user_keys)+++def build_account_store(+ *,+ viking_fs: VikingFS | None,+ api_key_hashing_enabled: bool,+ account_store_provider: str,+ account_store_params: dict[str, object] | None,+ account_store_watch_enabled: bool,+ account_store_watch_interval_seconds: float,+ account_store: AccountStore | None = None,+) -> AccountStore:+ """Create one complete account store from the configured provider."""+ if account_store is not None:+ return account_store++ provider = account_store_provider.strip().lower()+ if provider == "file":+ file_system = cast(VikingFS, viking_fs)+ return FileStore(+ viking_fs=file_system,+ params=dict(account_store_params or {}),+ api_key_hashing_enabled=api_key_hashing_enabled,+ watch_enabled=account_store_watch_enabled,+ watch_interval_seconds=account_store_watch_interval_seconds,+ )+ raise InvalidArgumentError(+ f"Unknown account store provider '{account_store_provider}'. "+ "Available providers: file"+ )diff --git a/openviking/service/deletion.py b/openviking/service/deletion.pyindex 9812c55bd..66dc96b8b 100644--- a/openviking/service/deletion.py+++ b/openviking/service/deletion.py@@ -80,7 +80,7 @@ class DeletionService:async def initialize(self) -> None:"""Bind the queue consumer and reconcile persisted deletion fences."""- self._service.viking_fs.set_deletion_guard(self._manager.is_deleting)+ self._service.viking_fs.set_deletion_guard(self._is_deleting)queue_manager = self._service._queue_managerqueue = queue_manager.get_queue(queue_manager.DATA_CLEANUP)queued_task_ids = {@@ -91,7 +91,7 @@ class DeletionService:queue.set_dequeue_handler(_DeletionProcessor(self, self._service_loop))tracker = get_task_tracker()- for account_id, user_id, deletion in self._manager.iter_deletions():+ for account_id, user_id, deletion in await self._manager.iter_deletions():task_id = deletion.get("task_id")owner_account_id = deletion.get("owner_account_id")owner_user_id = deletion.get("owner_user_id")@@ -124,6 +124,9 @@ class DeletionService:)queued_task_ids.add(task_id)+ async def _is_deleting(self, account_id: str, user_id: str | None = None) -> bool:+ return await self._manager.get_deletion(account_id, user_id) is not None+async def delete(self,account_id: str,@@ -273,7 +276,7 @@ class DeletionService:user_id = message["target"]["user_id"]scope = "account" if user_id is None else "user"tracker = get_task_tracker()- deletion = self._manager.get_deletion(account_id, user_id)+ deletion = await self._manager.get_deletion(account_id, user_id)if deletion is None or deletion["task_id"] != task_id:task = await tracker.get(task_id, **owner)# Account-owned records are removed with their account. A late@@ -290,9 +293,9 @@ class DeletionService:return Noneif deletion is None or deletion["task_id"] != task_id:exists = (- self._manager.has_user(account_id, user_id)+ await self._manager.has_user(account_id, user_id)if user_id is not None- else any(item["account_id"] == account_id for item in self._manager.get_accounts())+ else await self._manager.get_account(account_id) is not None)await tracker.complete(task_id, {"deleted": not exists, "stale": True}, **owner)return Nonediff --git a/openviking/service/legacy_migration.py b/openviking/service/legacy_migration.pyindex 6286f14c7..1146962ab 100644--- a/openviking/service/legacy_migration.py+++ b/openviking/service/legacy_migration.py@@ -120,7 +120,7 @@ class LegacyDataMigration:async def preflight(self) -> MigrationPlan:plan = MigrationPlan()- registry_accounts = self._registry_account_ids()+ registry_accounts = await self._registry_account_ids()physical_accounts = await self._physical_account_ids()for account_id in sorted(physical_accounts - registry_accounts):if await self._exists(f"/local/{account_id}/session"):@@ -135,11 +135,11 @@ class LegacyDataMigration:for account_id in sorted(registry_accounts):plan.account_users[account_id] = set()- for user_id in sorted(self._registry_user_ids(account_id)):- self._ensure_plan_user(account_id, user_id, plan)+ for user_id in sorted(await self._registry_user_ids(account_id)):+ await self._ensure_plan_user(account_id, user_id, plan)if await self._exists(f"/local/{account_id}/session"):for user_id in sorted(await self._physical_user_ids(account_id)):- self._ensure_plan_user(account_id, user_id, plan)+ await self._ensure_plan_user(account_id, user_id, plan)await self._plan_sessions(account_id, plan)return plan@@ -153,10 +153,10 @@ class LegacyDataMigration:result = MigrationResult()for account_id, user_id in sorted(plan.created_users):- if self._has_user(account_id, user_id):+ if await self._has_user(account_id, user_id):continue- await self._api_key_manager.register_user(account_id, user_id, "user")user_ctx = RequestContext(user=UserIdentifier(account_id, user_id), role=Role.USER)+ await self._api_key_manager.register_user(account_id, user_id, "user")await self._service.initialize_user_directories(user_ctx)result.created_users.append({"account_id": account_id, "user_id": user_id})@@ -195,26 +195,27 @@ class LegacyDataMigration:result.removed.append(target_to_dict(target))return result.to_dict()- def _registry_account_ids(self) -> set[str]:+ async def _registry_account_ids(self) -> set[str]:return {str(item.get("account_id", ""))- for item in self._api_key_manager.get_accounts()+ for item in await self._api_key_manager.list_accounts()if item.get("account_id")}- def _registry_user_ids(self, account_id: str) -> set[str]:- users = self._api_key_manager.get_users(+ async def _registry_user_ids(self, account_id: str) -> set[str]:+ page = await self._api_key_manager.list_users_page(account_id,limit=1_000_000,expose_key=False,)- return {str(item.get("user_id", "")) for item in users if item.get("user_id")}+ return {+ str(item.get("user_id", ""))+ for item in page["users"]+ if item.get("user_id")+ }- def _has_user(self, account_id: str, user_id: str) -> bool:- has_user = getattr(self._api_key_manager, "has_user", None)- if callable(has_user):- return bool(has_user(account_id, user_id))- return user_id in self._registry_user_ids(account_id)+ async def _has_user(self, account_id: str, user_id: str) -> bool:+ return await self._api_key_manager.has_user(account_id, user_id)async def _physical_account_ids(self) -> set[str]:entries = await self._ls("/local")@@ -289,7 +290,7 @@ class LegacyDataMigration:})return- self._ensure_plan_user(account_id, owner, plan)+ await self._ensure_plan_user(account_id, owner, plan)target_path = f"/local/{account_id}/user/{owner}/sessions/{session_id}"plan.operations.append(TreeCopy(@@ -320,7 +321,7 @@ class LegacyDataMigration:return Truereturn False- def _ensure_plan_user(self, account_id: str, user_id: str, plan: MigrationPlan) -> bool:+ async def _ensure_plan_user(self, account_id: str, user_id: str, plan: MigrationPlan) -> bool:if error := validate_user_id(user_id):detail = {"account_id": account_id,@@ -334,7 +335,7 @@ class LegacyDataMigration:if user_id in users:return Trueusers.add(user_id)- if not self._has_user(account_id, user_id):+ if not await self._has_user(account_id, user_id):plan.created_users.add((account_id, user_id))return Truediff --git a/openviking/storage/viking_fs/_access.py b/openviking/storage/viking_fs/_access.pyindex cd92c946f..d56a6e797 100644--- a/openviking/storage/viking_fs/_access.py+++ b/openviking/storage/viking_fs/_access.py@@ -3,6 +3,7 @@"""Access control, URI/path conversion, and visibility mixin for VikingFS."""import hashlib+import inspectimport jsonimport refrom contextlib import contextmanager@@ -237,7 +238,7 @@ class _AccessMixin:if action is AclAction.READ:return- self._ensure_identity_not_deleting(real_ctx)+ await self._ensure_identity_not_deleting(real_ctx)for uri in uris:self._safe_uri_parts(uri)if uri == "viking://" and real_ctx.role == Role.USER:@@ -403,10 +404,12 @@ class _AccessMixin:async def delete_acl(self, uri: str, ctx: Optional[RequestContext] = None) -> Dict[str, Any]:return await self.set_acl(uri, [], acl_mode=AclMode.INHERIT, ctx=ctx)- def _ensure_identity_not_deleting(self, ctx: RequestContext) -> None:+ async def _ensure_identity_not_deleting(self, ctx: RequestContext) -> None:guard = getattr(self, "_deletion_guard", None)- if ctx.role != Role.ROOT and guard is not None and guard(ctx.account_id, ctx.user.user_id):- raise FailedPreconditionError("Identity deletion is in progress")+ if ctx.role != Role.ROOT and guard is not None:+ result = guard(ctx.account_id, ctx.user.user_id)+ if await result if inspect.isawaitable(result) else result:+ raise FailedPreconditionError("Identity deletion is in progress")def _ensure_supported_delete_namespace(self, normalized_uri: str) -> None:parts = [p for p in normalized_uri[len("viking://") :].strip("/").split("/") if p]diff --git a/tests/api_test/tools/tests/test_api_key_manager.py b/tests/api_test/tools/tests/test_api_key_manager.pyindex 508a1bd24..71f1cd0e0 100644--- a/tests/api_test/tools/tests/test_api_key_manager.py+++ b/tests/api_test/tools/tests/test_api_key_manager.py@@ -34,8 +34,8 @@ async def test_api_key_manager():manager = _get_api_key_manager(mock_request)print(f"✅ _get_api_key_manager returned: {manager}")- print("\nTesting manager.get_accounts()...")- accounts = manager.get_accounts()+ print("\nTesting manager.list_accounts()...")+ accounts = await manager.list_accounts()print(f" accounts: {accounts}")except Exception as e:print(f"❌ _get_api_key_manager error: {e}")diff --git a/tests/api_test/tools/tests/test_simple_startup.py b/tests/api_test/tools/tests/test_simple_startup.pyindex 05cb1932a..e746b946b 100644--- a/tests/api_test/tools/tests/test_simple_startup.py+++ b/tests/api_test/tools/tests/test_simple_startup.py@@ -1,40 +1,46 @@+import asyncio+from openviking.server.app import create_appfrom openviking.server.config import load_server_config-print("Testing simple startup...")-print("=" * 80)-try:- config = load_server_config()- print("Config loaded:")- print(f" host: {config.host}")- print(f" port: {config.port}")- print(f" root_api_key configured: {bool(config.root_api_key)}")+async def main():+ print("Testing simple startup...")+ print("=" * 80)++ try:+ config = load_server_config()+ print("Config loaded:")+ print(f" host: {config.host}")+ print(f" port: {config.port}")+ print(f" root_api_key configured: {bool(config.root_api_key)}")++ print("\nCreating app...")+ app = create_app(config)++ print("\nApp created! Now checking lifespan...")- print("\nCreating app...")- app = create_app(config)+ # Let's check what lifespan looks like+ lifespan = app.router.lifespan_context+ print(f"Lifespan: {lifespan}")- print("\nApp created! Now checking lifespan...")+ print("\n" + "=" * 80)+ print("Let's try to manually create APIKeyManager!")- # Let's check what lifespan looks like- lifespan = app.router.lifespan_context- print(f"Lifespan: {lifespan}")+ from openviking.server.store_assembly import build_api_key_manager- print("\n" + "=" * 80)- print("Let's try to manually create APIKeyManager!")+ manager = build_api_key_manager(config.root_api_key, None)+ print("APIKeyManager created successfully!")- from openviking.server.auth import APIKeyManager+ print("\nTesting manager.list_accounts()...")+ accounts = await manager.list_accounts()+ print(f" accounts: {accounts}")- manager = APIKeyManager(config.root_api_key, None)- print("APIKeyManager created successfully!")- print(f" manager.root_api_key configured: {bool(manager.root_api_key)}")+ except Exception as e:+ print(f"\nError: {e}")+ import traceback- print("\nTesting manager.get_accounts()...")- accounts = manager.get_accounts()- print(f" accounts: {accounts}")+ traceback.print_exc()-except Exception as e:- print(f"\nError: {e}")- import traceback- traceback.print_exc()+asyncio.run(main())diff --git a/tests/integration/test_encryption_integration.py b/tests/integration/test_encryption_integration.pyindex adcfceba6..1091a7eee 100644--- a/tests/integration/test_encryption_integration.py+++ b/tests/integration/test_encryption_integration.py@@ -17,7 +17,8 @@ import pytest_asynciofrom openviking.crypto.config import bootstrap_encryptionfrom openviking.crypto.encryptor import FileEncryptorfrom openviking.crypto.providers import LocalFileProvider-from openviking.server.api_keys import APIKeyManager, is_new_format_key+from openviking.server.api_keys import is_new_format_key+from openviking.server.store_assembly import build_api_key_managerfrom openviking.service.core import OpenVikingServicefrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton@@ -191,7 +192,7 @@ class TestVikingFSEncryptionWithAccounts:await svc.initialize()# Create APIKeyManager using VikingFS to ensure system file encryption- api_key_manager = APIKeyManager(root_key=self.ROOT_KEY, viking_fs=svc.viking_fs)+ api_key_manager = build_api_key_manager(root_key=self.ROOT_KEY, viking_fs=svc.viking_fs)await api_key_manager.load()yield {"service": svc, "api_key_manager": api_key_manager, "test_data_dir": test_data_dir}@@ -325,7 +326,7 @@ class TestVikingFSEncryptionWithAccounts:)# Verify identity can be resolved correctly via API Key- identity = api_key_manager.resolve(user_key)+ identity = await api_key_manager.resolve_identity(user_key)assert identity.account_id == account_idassert identity.user_id == admin_user_id@@ -357,7 +358,7 @@ class TestVikingFSEncryptionWithAccounts:assert self._is_file_encrypted(account_users_path), "users.json not encrypted after update"# Verify identity can be resolved via new user's API Key- identity = api_key_manager.resolve(new_user_key)+ identity = await api_key_manager.resolve_identity(new_user_key)assert identity.account_id == account_idassert identity.user_id == new_user_id@@ -422,8 +423,8 @@ class TestVikingFSEncryptionWithAccounts:assert self._is_file_encrypted(account2_users_path)# Verify respective API Keys can resolve correctly- identity1 = api_key_manager.resolve(key1)- identity2 = api_key_manager.resolve(key2)+ identity1 = await api_key_manager.resolve_identity(key1)+ identity2 = await api_key_manager.resolve_identity(key2)assert identity1.account_id == account1_idassert identity2.account_id == account2_id@@ -549,9 +550,12 @@ This is a test skill for verifying encryption functionality.assert admin_user_key is not Noneassert is_new_format_key(admin_user_key)- # 2. Verify list-accounts operation (via accessing APIKeyManager internal data)+ # 2. Verify list-accounts operationprint("[2] Verify list-accounts operation")- assert test_account_id in api_key_manager._accounts, (+ account_ids = {+ account["account_id"] for account in await api_key_manager.list_accounts()+ }+ assert test_account_id in account_ids, (f"Account {test_account_id} not in account list")print(f" ✓ Account {test_account_id} exists in account list")@@ -565,9 +569,10 @@ This is a test skill for verifying encryption functionality.# 4. Verify list-users operationprint("[4] Verify list-users operation")- account_info = api_key_manager._accounts.get(test_account_id)- assert account_info is not None- assert test_user_id in account_info.users, f"User {test_user_id} not in user list"+ users = await api_key_manager.list_users_page(test_account_id)+ assert test_user_id in {+ user["user_id"] for user in users["users"]+ }, f"User {test_user_id} not in user list"print(f" ✓ User {test_user_id} exists in user list")# 5. Check all files in account directory are encrypted (recursive check)@@ -979,9 +984,7 @@ This is a test skill for verifying encryption functionality.# Delete test accountawait api_key_manager.delete_account(test_account_id)- assert test_account_id not in api_key_manager._accounts, (- f"Account {test_account_id} not deleted"- )+ assert await api_key_manager.get_account(test_account_id) is Noneprint(f" ✓ Test account deleted: {test_account_id}")print("\n" + "=" * 80)@@ -1139,7 +1142,7 @@ class TestAddResourceWithSemanticProcessing:await svc.initialize()# Create APIKeyManager using VikingFS to ensure system file encryption- api_key_manager = APIKeyManager(root_key=self.ROOT_KEY, viking_fs=svc.viking_fs)+ api_key_manager = build_api_key_manager(root_key=self.ROOT_KEY, viking_fs=svc.viking_fs)await api_key_manager.load()yield {@@ -1230,7 +1233,6 @@ This is a file in subdir2.entries = await svc.viking_fs.ls(uri, output="original", ctx=ctx)for entry in entries:entry_uri = entry["uri"]- entry_name = entry.get("name", "")if entry["isDir"]:await check_encrypted_files(entry_uri)@@ -1312,9 +1314,7 @@ This is a file in subdir2.print("=" * 80)await api_key_manager.delete_account(test_account_id)- assert test_account_id not in api_key_manager._accounts, (- f"Account {test_account_id} not deleted"- )+ assert await api_key_manager.get_account(test_account_id) is Noneprint(f" ✓ Test account deleted: {test_account_id}")print("\n" + "=" * 80)diff --git a/tests/integration/test_vault_encryption_integration.py b/tests/integration/test_vault_encryption_integration.pyindex 403967e14..900271d10 100644--- a/tests/integration/test_vault_encryption_integration.py+++ b/tests/integration/test_vault_encryption_integration.py@@ -19,7 +19,7 @@ from openviking.crypto.config import bootstrap_encryptionfrom openviking.crypto.encryptor import FileEncryptorfrom openviking.crypto.exceptions import AuthenticationFailedError, ConfigErrorfrom openviking.crypto.providers import VaultProvider, create_root_key_provider-from openviking.server.api_keys import APIKeyManager+from openviking.server.store_assembly import build_api_key_managerfrom openviking.service.core import OpenVikingServicefrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton@@ -319,7 +319,7 @@ class TestVikingFSEncryptionWithVault:await svc.initialize()# Create APIKeyManager using VikingFS to ensure system files are encrypted- api_key_manager = APIKeyManager(root_key=self.ROOT_KEY, viking_fs=svc.viking_fs)+ api_key_manager = build_api_key_manager(root_key=self.ROOT_KEY, viking_fs=svc.viking_fs)await api_key_manager.load()yield {"service": svc, "api_key_manager": api_key_manager, "test_data_dir": test_data_dir}diff --git a/tests/integration/test_volcengine_kms_encryption_integration.py b/tests/integration/test_volcengine_kms_encryption_integration.pyindex c4d93590e..02f471940 100644--- a/tests/integration/test_volcengine_kms_encryption_integration.py+++ b/tests/integration/test_volcengine_kms_encryption_integration.py@@ -19,7 +19,8 @@ import pytest_asynciofrom openviking.crypto.encryptor import FileEncryptorfrom openviking.crypto.providers import VolcengineKMSProvider-from openviking.server.api_keys import APIKeyManager, is_new_format_key+from openviking.server.api_keys import is_new_format_key+from openviking.server.store_assembly import build_api_key_managerfrom openviking.service.core import OpenVikingServicefrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton@@ -285,7 +286,7 @@ class TestVikingFSEncryptionWithVolcengineKMS:)await svc.initialize()- api_key_manager = APIKeyManager(root_key=self.ROOT_KEY, viking_fs=svc.viking_fs)+ api_key_manager = build_api_key_manager(root_key=self.ROOT_KEY, viking_fs=svc.viking_fs)await api_key_manager.load()yield {"service": svc, "api_key_manager": api_key_manager, "test_data_dir": test_data_dir}diff --git a/tests/server/account_store_fakes.py b/tests/server/account_store_fakes.pynew file mode 100644index 000000000..880dfe55f--- /dev/null+++ b/tests/server/account_store_fakes.py@@ -0,0 +1,72 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Test doubles for file-backed account-store tests."""++import threading+import time+import uuid++from openviking.pyagfs import AGFSNotFoundError+++class InMemoryAGFS:+ def __init__(self):+ self._files: dict[str, bytes] = {}+ self._modified_at: dict[str, float] = {}+ self._locks: dict[str, threading.Lock] = {}+ self._leases: dict[str, threading.Lock] = {}+ self._guard = threading.Lock()++ def read(self, path: str, ctx=None) -> bytes:+ del ctx+ with self._guard:+ try:+ return self._files[path]+ except KeyError as exc:+ raise AGFSNotFoundError(path) from exc++ def write(self, path: str, content: bytes, ctx=None) -> None:+ del ctx+ with self._guard:+ self._files[path] = bytes(content)+ self._modified_at[path] = time.monotonic()++ def stat(self, path: str, ctx=None, bypass_cache: bool = False) -> dict:+ del ctx, bypass_cache+ with self._guard:+ try:+ content = self._files[path]+ except KeyError as exc:+ raise AGFSNotFoundError(path) from exc+ return {+ "size": len(content),+ "modTime": self._modified_at[path],+ "isDir": False,+ }++ def ensure_parent_dirs(self, path: str, ctx=None) -> None:+ del path, ctx++ def pathlock_acquire_exact(+ self,+ ctx,+ path: str,+ timeout_secs: float = 0.0,+ owner_lease_ref=None,+ ) -> dict:+ del ctx, owner_lease_ref+ with self._guard:+ lock = self._locks.setdefault(path, threading.Lock())+ if not lock.acquire(timeout=timeout_secs):+ raise TimeoutError(f"timed out acquiring account store lock: {path}")+ lease_ref = uuid.uuid4().hex+ with self._guard:+ self._leases[lease_ref] = lock+ return {"lease_ref": lease_ref, "owned": True}++ def pathlock_release(self, ctx, owned_lease_ref: dict) -> None:+ del ctx+ lease_ref = owned_lease_ref["lease_ref"]+ with self._guard:+ lock = self._leases.pop(lease_ref)+ lock.release()diff --git a/tests/server/oauth/test_auth_integration.py b/tests/server/oauth/test_auth_integration.pyindex 0108adf97..0655c599f 100644--- a/tests/server/oauth/test_auth_integration.py+++ b/tests/server/oauth/test_auth_integration.py@@ -4,6 +4,7 @@from __future__ import annotations+from types import SimpleNamespacefrom typing import Optionalimport pytest@@ -13,13 +14,15 @@ from starlette.requests import Requestfrom openviking.server.auth import resolve_identityfrom openviking.server.config import ServerConfig-from openviking.server.identity import Role+from openviking.server.identity import ResolvedIdentity, Rolefrom openviking.server.oauth.provider import (ACCESS_TOKEN_PREFIX,OpenVikingOAuthProvider,)from openviking.server.oauth.storage import OAuthStore-from openviking_cli.exceptions import PermissionDeniedError, UnauthenticatedError+from openviking.server.store_assembly import build_api_key_manager+from openviking_cli.exceptions import UnauthenticatedError+from tests.server.account_store_fakes import InMemoryAGFSdef _make_request(@@ -78,14 +81,10 @@ class _StubKeyManager:raise_on_resolve: bool = True,fingerprints: Optional[dict[tuple[str, str], str]] = None,default_fingerprint: Optional[str] = _TEST_FP,- roles: Optional[dict[tuple[str, str], Role]] = None,- default_role: Role = Role.USER,):self._raise = raise_on_resolveself._fps = fingerprintsself._default_fp = default_fingerprint- self._roles = roles- self._default_role = default_roledef resolve(self, key: str): # noqa: D401if self._raise:@@ -94,15 +93,22 @@ class _StubKeyManager:return ResolvedIdentity(role=Role.USER, account_id="api-acct", user_id="api-user")- def get_user_key_fingerprint(self, account_id: str, user_id: str) -> Optional[str]:+ async def get_user_key_fingerprint(self, account_id: str, user_id: str) -> Optional[str]:if self._fps is None:return self._default_fpreturn self._fps.get((account_id, user_id))- def get_user_role(self, account_id: str, user_id: str) -> Role:- if self._roles is None:- return self._default_role- return self._roles.get((account_id, user_id), self._default_role)+ async def resolve_oauth_identity(self, account_id, user_id, role):+ return ResolvedIdentity(+ role=role,+ account_id=account_id,+ user_id=user_id,+ from_oauth=True,+ )++ async def resolve_identity(self, key):+ identity = self.resolve(key)+ return identity@pytest_asyncio.fixture@@ -208,7 +214,7 @@ async def test_oauth_path_skipped_when_disabled(store):@pytest.mark.asyncio-async def test_oauth_user_role_rejects_account_override(provider, store):+async def test_oauth_user_role_ignores_account_override(provider, store):"""A USER OAuth token cannot impersonate another tenant via header."""token = await _mint_token(provider, store, account_id="tenant-a", user_id="alice", role="user")request = _make_request(@@ -217,23 +223,23 @@ async def test_oauth_user_role_rejects_account_override(provider, store):oauth_provider=provider,extra_headers={"x-openviking-account": "tenant-b"},)- with pytest.raises(PermissionDeniedError):- await resolve_identity(- request,- x_api_key=None,- authorization=f"Bearer {token}",- x_openviking_account="tenant-b",- )+ identity = await resolve_identity(+ request,+ x_api_key=None,+ authorization=f"Bearer {token}",+ x_openviking_account="tenant-b",+ )+ assert (identity.account_id, identity.user_id) == ("tenant-a", "alice")+ assert "x-openviking-account" not in request.headers@pytest.mark.asyncioasync def test_oauth_root_can_be_used_without_explicit_tenant_headers(provider, store):"""ROOT OAuth tokens carry account/user in claims — no header requirement."""token = await _mint_token(provider, store, account_id="tenant-a", user_id="alice", role="root")- # Manager must report alice as ROOT so the role-downgrade gate passes.request = _make_request(bearer=token,- api_key_manager=_StubKeyManager(default_role=Role.ROOT),+ api_key_manager=_StubKeyManager(),oauth_provider=provider,)identity = await resolve_identity(request, x_api_key=None, authorization=f"Bearer {token}")@@ -293,57 +299,36 @@ async def test_oauth_token_rejected_when_authorizing_user_removed(provider, storawait resolve_identity(request, x_api_key=None, authorization=f"Bearer {token}")-async def test_oauth_token_rejected_after_role_downgrade(provider, store):- """set_role demotion must invalidate OAuth tokens whose embedded role- outranks the user's current role — fp alone won't catch this because- the key value is unchanged."""- token = await _mint_token(- provider,- store,- account_id="tenant-a",- user_id="alice",- role="admin", # token issued when alice was admin- authorizing_key_fp=_TEST_FP,- )- # Manager now reports alice as USER (post-set_role demotion).- demoted_manager = _StubKeyManager(- raise_on_resolve=True,- roles={("tenant-a", "alice"): Role.USER},- )- request = _make_request(- bearer=token,- api_key_manager=demoted_manager,- oauth_provider=provider,- )- with pytest.raises(UnauthenticatedError, match="exceeds the user's current role"):- await resolve_identity(request, x_api_key=None, authorization=f"Bearer {token}")---async def test_oauth_token_survives_role_promotion(provider, store):- """Promotion (current role > token role) is harmless — token's lower- privilege is still authorized. Only downgrades trigger rejection."""- token = await _mint_token(- provider,- store,- account_id="tenant-a",- user_id="alice",- role="user",- authorizing_key_fp=_TEST_FP,- )- promoted_manager = _StubKeyManager(- raise_on_resolve=True,- roles={("tenant-a", "alice"): Role.ADMIN},- )- request = _make_request(- bearer=token,- api_key_manager=promoted_manager,- oauth_provider=provider,- )- identity = await resolve_identity(request, x_api_key=None, authorization=f"Bearer {token}")- # Token's USER role is preserved — promotion doesn't auto-elevate.- assert identity.role == Role.USER[email protected]("initial,current", [(Role.ADMIN, Role.USER), (Role.USER, Role.ADMIN)])+async def test_oauth_token_respects_current_role(provider, store, initial, current):+ manager = build_api_key_manager("root", SimpleNamespace(agfs=InMemoryAGFS()))+ await manager.load()+ try:+ await manager.create_account("tenant-a", "owner")+ await manager.register_user("tenant-a", "alice", initial)+ token = await _mint_token(+ provider,+ store,+ account_id="tenant-a",+ user_id="alice",+ role=initial,+ authorizing_key_fp=await manager.get_user_key_fingerprint("tenant-a", "alice"),+ )+ request = _make_request(bearer=token, api_key_manager=manager, oauth_provider=provider)+ identity = await resolve_identity(request, x_api_key=None, authorization=f"Bearer {token}")+ assert identity.role == initial++ await manager.set_role("tenant-a", "alice", current)+ if current == Role.USER:+ with pytest.raises(UnauthenticatedError, match="exceeds the user's current role"):+ await resolve_identity(request, x_api_key=None, authorization=f"Bearer {token}")+ else:+ identity = await resolve_identity(+ request, x_api_key=None, authorization=f"Bearer {token}"+ )+ assert identity.role == Role.USER+ finally:+ await manager.close()@pytest.mark.asynciodiff --git a/tests/server/oauth/test_mcp_www_authenticate.py b/tests/server/oauth/test_mcp_www_authenticate.pyindex 0a07b0a84..d8c7356db 100644--- a/tests/server/oauth/test_mcp_www_authenticate.py+++ b/tests/server/oauth/test_mcp_www_authenticate.py@@ -51,7 +51,7 @@ def _build_test_app(*, oauth_enabled: bool, tmp_path=None) -> FastAPI: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+ app.state.api_key_manager = _UserOnlyKeyManager()# Set auth plugin (lifespan not triggered in ASGI tests)registry = get_registry()if registry.get("api_key") is None:@@ -69,24 +69,30 @@ def _build_test_app(*, oauth_enabled: bool, tmp_path=None) -> FastAPI:class _RootOnlyKeyManager:- def resolve(self, api_key):- if api_key != "root-test-1234567890abcd":- raise UnauthenticatedError("Invalid API Key")- return ResolvedIdentity(- role=Role.ROOT,- account_id="default",- user_id="default",- )+ def is_root_key(self, api_key):+ return api_key == "root-test-1234567890abcd"++ async def resolve_identity(self, api_key):+ if self.is_root_key(api_key):+ return ResolvedIdentity(role=Role.ROOT)+ raise UnauthenticatedError("Invalid API Key")class _UserOnlyKeyManager:- def resolve(self, api_key):+ def is_root_key(self, api_key):+ return False++ async def verify(self, api_key):if api_key != "user-test-1234567890abcd":raise UnauthenticatedError("Invalid API Key")+ return "default", "alice"++ async def resolve_identity(self, api_key):+ account_id, user_id = await self.verify(api_key)return ResolvedIdentity(role=Role.USER,- account_id="default",- user_id="alice",+ account_id=account_id,+ user_id=user_id,)diff --git a/tests/server/oauth/test_router.py b/tests/server/oauth/test_router.pyindex 6246e5473..9c5e251d0 100644--- a/tests/server/oauth/test_router.py+++ b/tests/server/oauth/test_router.py@@ -55,7 +55,7 @@ class _FpOnlyKeyManager:def __init__(self, fingerprints: dict[tuple[str, str], str]):self._fps = fingerprints- def get_user_key_fingerprint(self, account_id: str, user_id: str) -> Optional[str]:+ async def get_user_key_fingerprint(self, account_id: str, user_id: str) -> Optional[str]:return self._fps.get((account_id, user_id))diff --git a/tests/server/test_account_services.py b/tests/server/test_account_services.pynew file mode 100644index 000000000..aae4181b6--- /dev/null+++ b/tests/server/test_account_services.py@@ -0,0 +1,202 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++import asyncio+import json+import threading+from types import SimpleNamespace++import pytest++from openviking.server.api_keys import APIKeyManager+from openviking.server.api_keys.legacy import FileStore+from openviking.server.identity import Role+from openviking.server.store_assembly import build_api_key_manager+from openviking_cli.exceptions import (+ FailedPreconditionError,+ NotFoundError,+)+from tests.server.account_store_fakes import InMemoryAGFS+++def _file_store() -> FileStore:+ return FileStore(SimpleNamespace(agfs=InMemoryAGFS()))+++async def test_legacy_user_without_role_defaults_to_user_during_authentication():+ agfs = InMemoryAGFS()+ agfs.write(+ "/local/_system/accounts.json",+ json.dumps({"accounts": {"acme": {"created_at": "legacy"}}}).encode(),+ )+ agfs.write(+ "/local/acme/_system/users.json",+ json.dumps({"users": {"alice": {"key": "legacy-key"}}}).encode(),+ )+ manager = build_api_key_manager("root", SimpleNamespace(agfs=agfs))+ await manager.load()+ try:+ identity = await manager.resolve_identity("legacy-key")+ assert (identity.account_id, identity.user_id, identity.role) == (+ "acme",+ "alice",+ Role.USER,+ )+ finally:+ await manager.close()+++async def test_file_provider_keeps_existing_registry_paths():+ fs = SimpleNamespace(agfs=InMemoryAGFS())+ manager = build_api_key_manager("root", fs)+ await manager.load()+ try:+ key = await manager.create_account("acme", "alice")+ await manager.register_user("acme", "bob")+ assert await manager.resolve_identity(key)+ paths = set(fs.agfs._files)+ assert "/local/_system/accounts.json" in paths+ assert "/local/acme/_system/users.json" in paths+ assert "/local/acme/_system/groups.json" in paths+ assert not any("identities-v2" in path or "api-keys-v2" in path for path in paths)+ finally:+ await manager.close()+++async def test_file_account_creation_is_atomic_when_credential_write_fails():+ class FailingAGFS(InMemoryAGFS):+ def write(self, path, content, ctx=None):+ if path == "/local/acme/_system/users.json":+ raise OSError("credential store unavailable")+ return super().write(path, content, ctx)++ store = FileStore(SimpleNamespace(agfs=FailingAGFS()))+ manager = APIKeyManager("root", store)+ await manager.load()++ with pytest.raises(OSError, match="credential store unavailable"):+ await manager.create_account("acme", "alice")+ assert await manager.get_account("acme") is None+++async def test_file_user_creation_is_atomic_when_credential_write_fails():+ class FailingAGFS(InMemoryAGFS):+ fail_user_write = False++ def write(self, path, content, ctx=None):+ if self.fail_user_write and path == "/local/acme/_system/users.json":+ raise OSError("credential store unavailable")+ return super().write(path, content, ctx)++ agfs = FailingAGFS()+ store = FileStore(SimpleNamespace(agfs=agfs))+ manager = APIKeyManager("root", store)+ await manager.load()+ admin_key = await manager.create_account("acme", "alice")+ agfs.fail_user_write = True++ with pytest.raises(OSError, match="credential store unavailable"):+ await manager.register_user("acme", "bob")+ assert await manager.get_user("acme", "bob") is None+ assert (await manager.resolve_identity(admin_key)).user_id == "alice"+++async def test_regenerate_key_preserves_management_not_found_errors():+ manager = build_api_key_manager("root", SimpleNamespace(agfs=InMemoryAGFS()))+ await manager.load()+ await manager.create_account("acme", "alice")++ with pytest.raises(NotFoundError, match="Account not found"):+ await manager.regenerate_key("missing", "alice")+ with pytest.raises(NotFoundError, match="User not found"):+ await manager.regenerate_key("acme", "missing")+++async def test_file_store_allows_only_one_active_credential_per_user():+ store = _file_store()+ await store.load()+ await store.create_account_with_api_key("acme", "alice", "initial-key")++ await store.replace_active_user_api_key("acme", "alice", "first-key")+ await store.replace_active_user_api_key("acme", "alice", "second-key")+ assert await store.verify_api_key("first-key") is None+ active = await store.verify_api_key("second-key")+ assert active == ("acme", "alice")+++async def test_file_management_user_read_refreshes_only_explicitly():+ fs = SimpleNamespace(agfs=InMemoryAGFS())+ writer = build_api_key_manager("root", fs)+ reader = build_api_key_manager("root", fs)+ await writer.load()+ await reader.load()+ try:+ await writer.create_account("acme", "alice")++ assert not await reader.has_user("acme", "alice")+ assert await reader.get_user_for_management("acme", "alice") == {+ "user_id": "alice",+ "role": Role.ADMIN,+ }+ assert await reader.has_user("acme", "alice")+ finally:+ await reader.close()+ await writer.close()+++async def test_file_user_deletion_fence_survives_concurrent_role_update():+ class PausingAGFS(InMemoryAGFS):+ def __init__(self):+ super().__init__()+ self.pause_next_user_read = False+ self.user_read_started = threading.Event()+ self.allow_user_read = threading.Event()++ def read(self, path, ctx=None):+ if path == "/local/acme/_system/users.json" and self.pause_next_user_read:+ self.pause_next_user_read = False+ self.user_read_started.set()+ self.allow_user_read.wait()+ return super().read(path, ctx)++ agfs = PausingAGFS()+ store = FileStore(SimpleNamespace(agfs=agfs))+ await store.load()+ await store.create_account_with_api_key("acme", "alice", "alice-key")+ await store.create_user("acme", "bob", "user")++ agfs.pause_next_user_read = True+ set_role = asyncio.create_task(store.set_role("acme", "bob", "admin"))+ await asyncio.wait_for(asyncio.to_thread(agfs.user_read_started.wait), timeout=1)+ deleting = asyncio.create_task(+ store.begin_deletion(+ "acme",+ "bob",+ task_id="delete",+ owner_account_id="system",+ owner_user_id="system",+ )+ )+ await asyncio.sleep(0)+ agfs.allow_user_read.set()+ try:+ await set_role+ deletion, created = await deleting+ finally:+ agfs.allow_user_read.set()++ assert created+ assert deletion["task_id"] == "delete"+ assert (await store.get_deletion("acme", "bob"))["task_id"] == "delete"+++async def test_file_store_rejects_deleting_nonempty_group():+ store = _file_store()+ await store.load()+ await store.create_account_with_api_key("acme", "alice", "alice-key")+ await store.create_group("acme", "engineering")+ await store.add_group_member("acme", "engineering", "alice")++ with pytest.raises(FailedPreconditionError, match="Group must be empty"):+ await store.delete_group("acme", "engineering")+ assert await store.get_group_members("acme", "engineering") == ["alice"]diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.pyindex 648afdc59..739f97899 100644--- a/tests/server/test_admin_api.py+++ b/tests/server/test_admin_api.py@@ -22,12 +22,12 @@ from fastapi.responses import JSONResponsefrom openviking.config.binding import manager_over_sourcefrom openviking.config.source import MemoryConfigSourcefrom openviking.pyagfs.exceptions import AGFSNotFoundError-from openviking.server.api_keys import APIKeyManagerfrom openviking.server.app import create_appfrom openviking.server.config import ServerConfig, UserConfigfrom openviking.server.dependencies import set_servicefrom openviking.server.identity import RequestContext, Rolefrom openviking.server.models import ERROR_CODE_TO_HTTP_STATUS, ErrorInfo, Response+from openviking.server.store_assembly import build_api_key_managerfrom openviking.server.user_config import (read_user_add_targets,read_user_config,@@ -53,10 +53,6 @@ from openviking.session.memory.session_extract_context_provider import SessionExfrom openviking_cli.exceptions import OpenVikingErrorfrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils.config import get_openviking_config-from openviking_cli.utils.config.open_viking_config import (- OpenVikingConfig,- OpenVikingConfigSingleton,-)def _uid() -> str:@@ -179,7 +175,7 @@ def _build_lightweight_admin_test_app() -> FastAPI:).model_dump(),)- manager = APIKeyManager(root_key=ROOT_KEY, viking_fs=fake_service.viking_fs)+ manager = build_api_key_manager(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)@@ -187,6 +183,7 @@ def _build_lightweight_admin_test_app() -> FastAPI:if registry.get("api_key") is None:registry.register(ApiKeyAuthPlugin)app.state.auth_plugin = registry.get("api_key")()+ app.state.auth_plugin._api_key_manager = managerapp.include_router(admin_router.router)return app@@ -194,7 +191,6 @@ def _build_lightweight_admin_test_app() -> FastAPI:@pytest_asyncio.fixture(scope="function")async def lightweight_admin_app(monkeypatch):- monkeypatch.setattr(OpenVikingConfigSingleton, "_instance", OpenVikingConfig())app = _build_lightweight_admin_test_app()await app.state.fake_service.runtime_config_manager.initialize()await app.state.api_key_manager.load()@@ -223,7 +219,7 @@ async def admin_app(admin_service):app = create_app(config=config, service=admin_service)set_service(admin_service)- manager = APIKeyManager(root_key=ROOT_KEY, viking_fs=admin_service.viking_fs)+ manager = build_api_key_manager(root_key=ROOT_KEY, viking_fs=admin_service.viking_fs)await manager.load()app.state.api_key_manager = managerapp.state.deletion_service = await setup_deletion(@@ -236,6 +232,7 @@ async def admin_app(admin_service):if registry.get("api_key") is None:registry.register(ApiKeyAuthPlugin)app.state.auth_plugin = registry.get("api_key")()+ app.state.auth_plugin._api_key_manager = managerreturn app@@ -386,7 +383,7 @@ async def test_studio_full_configuration_preview_and_save_are_root_only(path = tmp_path / "startup.conf"server = {"port": 1933}if cli_host:- server.update(host="0.0.0.0", auth_mode="trusted")+ server.update(host="0.0.0.0", auth_mode="trusted", root_api_key=ROOT_KEY)lightweight_admin_app.state.server_config_overrides = {"host": cli_host}path.write_text(json.dumps({"server": server, "storage": {"workspace": "/tmp/old"}}))monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file", path)@@ -1798,10 +1795,23 @@ async def test_create_account(adapter = Mock(mode="vikingdb", USE_CONTENT_FIELD=True)adapter.get.return_value = []adapter.get_collection.return_value.get_meta_data.return_value = {- "Fields": [{"FieldName": name} for name in (- "id", "uri", "account_id", "context_type", "abstract", "level",- "user", "agent", "vector", "sparse_vector", "created_at", "updated_at",- )]+ "Fields": [+ {"FieldName": name}+ for name in (+ "id",+ "uri",+ "account_id",+ "context_type",+ "abstract",+ "level",+ "user",+ "agent",+ "vector",+ "sparse_vector",+ "created_at",+ "updated_at",+ )+ ]}adapter.upsert.side_effect = lambda rows: [row["id"] for row in rows]factory = Mock(return_value=adapter)@@ -1865,7 +1875,9 @@ async def test_create_account_rolls_back_when_runtime_config_write_fails()assert response.status_code == 500- assert not any(item["account_id"] == acct for item in admin_app.state.api_key_manager.get_accounts())+ assert not any(+ item["account_id"] == acct for item in await admin_app.state.api_key_manager.list_accounts()+ )assert not await _agfs_exists(admin_service, f"/local/{acct}")@@ -1943,6 +1955,7 @@ async def test_user_memory_policy_can_be_initialized_and_hot_updated(assert get_settings.json()["result"]["memory_policy"] == {"self": {"enabled": True},"peer": {"enabled": True},+ "working_memory": {"enabled": False},"memory_types": ["profile"],}@@ -1994,6 +2007,7 @@ async def test_user_memory_policy_can_be_initialized_and_hot_updated(assert reset_settings.json()["result"]["memory_policy"] == {"self": {"enabled": True},"peer": {"enabled": True},+ "working_memory": {"enabled": False},"memory_types": ["events"],}@@ -2030,6 +2044,7 @@ async def test_user_memory_policy_uses_server_default_without_user_override(assert get_settings.json()["result"]["memory_policy"] == {"self": {"enabled": True},"peer": {"enabled": True},+ "working_memory": {"enabled": False},"memory_types": ["profile"],}@@ -2104,60 +2119,6 @@ async def test_list_accounts(admin_client: httpx.AsyncClient):assert "default" not in queried_ids-async def test_list_accounts_without_watcher_reads_only_accounts_registry(- lightweight_admin_client: httpx.AsyncClient,- lightweight_admin_app: FastAPI,- monkeypatch: pytest.MonkeyPatch,-):- """Without a watcher, account listing must not load user registries."""- manager = lightweight_admin_app.state.api_key_manager- original_read_json = manager._legacy._read_json- read_paths: list[str] = []-- async def _record_read(path: str):- read_paths.append(path)- return await original_read_json(path)-- monkeypatch.setattr(manager._legacy, "_read_json", _record_read)-- resp = await lightweight_admin_client.get(- "/api/v1/admin/accounts?limit=5&page=1", headers=root_headers()- )-- assert resp.status_code == 200, resp.text- assert read_paths == ["/local/_system/accounts.json"]---async def test_list_users_without_watcher_reads_only_target_user_registry(- lightweight_admin_client: httpx.AsyncClient,- lightweight_admin_app: FastAPI,- monkeypatch: pytest.MonkeyPatch,-):- """Without a watcher, user listing must not load unrelated registries."""- acct = _uid()- await lightweight_admin_client.post(- "/api/v1/admin/accounts",- json={"account_id": acct, "admin_user_id": "alice"},- headers=root_headers(),- )- manager = lightweight_admin_app.state.api_key_manager- original_read_json = manager._legacy._read_json- read_paths: list[str] = []-- async def _record_read(path: str):- read_paths.append(path)- return await original_read_json(path)-- monkeypatch.setattr(manager._legacy, "_read_json", _record_read)-- resp = await lightweight_admin_client.get(- f"/api/v1/admin/accounts/{acct}/users", headers=root_headers()- )-- assert resp.status_code == 200, resp.text- assert read_paths == [f"/local/{acct}/_system/users.json"]--async def test_list_users_for_default_account_without_users_file_returns_empty_list(lightweight_admin_client: httpx.AsyncClient,):@@ -2170,43 +2131,13 @@ async def test_list_users_for_default_account_without_users_file_returns_empty_lassert resp.json()["result"] == []-async def test_list_accounts_with_watcher_uses_memory(- lightweight_admin_client: httpx.AsyncClient,- lightweight_admin_app: FastAPI,- monkeypatch: pytest.MonkeyPatch,-):- """A running watcher keeps list requests on the in-memory fast path."""- loop = asyncio.get_running_loop()- watch_task = loop.create_future()- lightweight_admin_app.state.auth_plugin._watch_task = watch_task-- async def _unexpected_read(_path: str):- raise AssertionError("list accounts should not read AGFS while watcher is running")-- manager = lightweight_admin_app.state.api_key_manager- monkeypatch.setattr(manager._legacy, "_read_json", _unexpected_read)- try:- resp = await lightweight_admin_client.get(- "/api/v1/admin/accounts", headers=root_headers()- )- users_resp = await lightweight_admin_client.get(- "/api/v1/admin/accounts/default/users", headers=root_headers()- )- finally:- watch_task.cancel()-- assert resp.status_code == 200, resp.text- assert users_resp.status_code == 200, users_resp.text--async def test_identity_settings_refreshes_a_stale_registry_on_demand(admin_client: httpx.AsyncClient,admin_app: FastAPI,admin_service: OpenVikingService,):"""Detail settings reads must not depend on a preceding list request."""- replica = admin_app.state.api_key_manager- writer = APIKeyManager(+ writer = build_api_key_manager(root_key=ROOT_KEY,viking_fs=admin_service.viking_fs,)@@ -2214,65 +2145,21 @@ async def test_identity_settings_refreshes_a_stale_registry_on_demand(acct = _uid()await writer.ensure_trusted_identities({acct: {"trusted-user"}})- assert replica.has_user(acct, "trusted-user") is Falseaccount_settings = await admin_client.get(f"/api/v1/admin/accounts/{acct}/settings",headers=root_headers(),)assert account_settings.status_code == 200, account_settings.text- assert replica.has_user(acct, "trusted-user") is Falseawait writer.ensure_trusted_identities({acct: {"trusted-user-2"}})- assert replica.has_user(acct, "trusted-user-2") is Falseuser_settings = await admin_client.get(f"/api/v1/admin/accounts/{acct}/users/trusted-user-2/settings",headers=root_headers(),)assert user_settings.status_code == 200, user_settings.text- assert replica.has_user(acct, "trusted-user") is True- assert replica.has_user(acct, "trusted-user-2") is True---async def test_identity_settings_without_watcher_use_scoped_registry_reads(- lightweight_admin_client: httpx.AsyncClient,- lightweight_admin_app: FastAPI,- monkeypatch: pytest.MonkeyPatch,-):- """Settings checks must not fall back to a full identity-registry reload."""- acct = _uid()- await lightweight_admin_client.post(- "/api/v1/admin/accounts",- json={"account_id": acct, "admin_user_id": "alice"},- headers=root_headers(),- )- manager = lightweight_admin_app.state.api_key_manager- original_read_json = manager._legacy._read_json- read_paths: list[str] = []-- async def _record_read(path: str):- read_paths.append(path)- return await original_read_json(path)-- monkeypatch.setattr(manager._legacy, "_read_json", _record_read)-- account_resp = await lightweight_admin_client.get(- f"/api/v1/admin/accounts/{acct}/settings", headers=root_headers()- )- assert account_resp.status_code == 200, account_resp.text- assert read_paths == ["/local/_system/accounts.json"]-- read_paths.clear()- user_resp = await lightweight_admin_client.get(- f"/api/v1/admin/accounts/{acct}/users/alice/settings",- headers=root_headers(),- )- assert user_resp.status_code == 200, user_resp.text- assert read_paths == [- "/local/_system/accounts.json",- f"/local/{acct}/_system/users.json",- ]+ await writer.close()@pytest.mark.parametrize("index_updates_immediately", [True, False])@@ -2371,8 +2258,7 @@ async def test_delete_account(assert failed["status"] == "failed"assert "injected vector failure" in failed["error"]assert await _agfs_exists(admin_service, path)- await manager.reload()- assert manager.get_deletion(acct)["task_id"] == task_id+ assert (await manager.get_deletion(acct))["task_id"] == task_idretried = await admin_client.delete(f"/api/v1/admin/accounts/{acct}", headers=root_headers())retry_task_id = retried.json()["result"]["task_id"]@@ -2399,10 +2285,12 @@ async def test_delete_account(assert adapter.get(deleted_ids[:100])assert not await _agfs_exists(admin_service, f"/local/{acct}")assert await _agfs_exists(admin_service, "/local/other/resources/keep.md")- assert manager.get_deletion(acct) is None- assert not manager.has_user(acct, "alice")+ assert await manager.get_deletion(acct) is None+ assert not await manager.has_user(acct, "alice")assert await get_task_tracker().get(old_task.task_id, account_id=acct, user_id="alice") is None- assert await get_task_tracker().get(user_cleanup.task_id, account_id=acct, user_id="alice") is None+ assert (+ await get_task_tracker().get(user_cleanup.task_id, account_id=acct, user_id="alice") is None+ )assert (await _wait_for_task(admin_client, task_id))["status"] == "failed"# Late cleanup deliveries are harmless after deletion, including when the@@ -2439,12 +2327,13 @@ async def test_delete_account(skipped = await _wait_for_task(admin_client, late_task_id)assert skipped["status"] == "completed"assert skipped["result"] == {"deleted": not recreated, "stale": True}- assert await get_task_tracker().get(- user_cleanup.task_id, account_id=acct, user_id="alice"- ) is None+ assert (+ await get_task_tracker().get(user_cleanup.task_id, account_id=acct, user_id="alice")+ is None+ )assert await _agfs_exists(admin_service, path) is recreatedif recreated:- assert manager.resolve(replacement_key).user_id == "bob"+ assert (await manager.resolve_identity(replacement_key)).user_id == "bob"async def test_delete_account_retries_when_runtime_config_cleanup_fails(@@ -2478,7 +2367,7 @@ async def test_delete_account_retries_when_runtime_config_cleanup_fails(headers={"X-API-Key": user_key},)assert denied.status_code == 401- assert admin_app.state.api_key_manager.get_deletion(acct) is not None+ assert await admin_app.state.api_key_manager.get_deletion(acct) is not Noneconflict = await admin_client.post("/api/v1/admin/accounts",@@ -2494,7 +2383,7 @@ async def test_delete_account_retries_when_runtime_config_cleanup_fails()completed = await _wait_for_task(admin_client, retry.json()["result"]["task_id"])assert completed["status"] == "completed"- assert admin_app.state.api_key_manager.get_deletion(acct) is None+ assert await admin_app.state.api_key_manager.get_deletion(acct) is Noneassert delete_config.await_count == 2@@ -2783,7 +2672,7 @@ async def test_remove_user(assert not await admin_service.viking_fs.exists(private_uri, ctx=bob_ctx)assert not await admin_service.viking_fs.exists(bob_upload_uri, ctx=upload_ctx)assert await admin_service.viking_fs.exists(alice_upload_uri, ctx=upload_ctx)- assert not admin_app.state.api_key_manager.has_user(acct, "bob")+ assert not await admin_app.state.api_key_manager.has_user(acct, "bob")assert (await get_task_tracker().get(bob_task.task_id,@@ -3059,7 +2948,7 @@ async def test_legacy_migration_only_moves_sessions(result = task["result"]assert result["migrated"]["operations"] == {"sessions": 2}assert result["created_users"] == [{"account_id": acct, "user_id": "charlie"}]- assert admin_app.state.api_key_manager.has_user(acct, "charlie")+ assert await admin_app.state.api_key_manager.has_user(acct, "charlie")assert await _agfs_read_text(admin_service, shared_path) == "shared workflow"for session_id, owner in (("s1", "alice"), ("s2", "charlie")):assert (@@ -3136,17 +3025,29 @@ async def test_session_storage_uses_canonical_uri(@pytest_asyncio.fixture(scope="function")-async def trusted_admin_app(lightweight_admin_app):+async def trusted_admin_app(admin_service):from openviking.server.auth.plugins import TrustedAuthPlugin+ from openviking.server.auth.registry import get_registry- app = lightweight_admin_appconfig = ServerConfig(- auth_mode="trusted", root_api_key=ROOT_KEY, trusted_identity_flush_interval_seconds=0+ auth_mode="trusted",+ root_api_key=ROOT_KEY,+ trusted_identity_flush_interval_seconds=0,)- app.state.config = config- app.state.auth_plugin = TrustedAuthPlugin()- await app.state.auth_plugin.initialize(app, app.state.fake_service, config)- await app.state.api_key_manager.create_account("platform", "gateway-admin")+ app = create_app(config=config, service=admin_service)+ set_service(admin_service)++ # Initialize the plugin directly because the ASGI transport does not run lifespan.+ registry = get_registry()+ if registry.get("trusted") is None:+ registry.register(TrustedAuthPlugin)+ app.state.auth_plugin = registry.get("trusted")()+ await app.state.auth_plugin.initialize(app, admin_service, config)++ manager = app.state.api_key_manager+ if await manager.get_account("platform") is None:+ await manager.create_account("platform", "gateway-admin")+return app@@ -3180,22 +3081,22 @@ async def test_trusted_mode_root_can_create_account(assert body["result"]["account_id"] == acctassert body["result"]["admin_user_id"] == "alice"assert "user_key" not in body["result"]+ listed = await trusted_admin_client.get(+ "/api/v1/admin/accounts",+ headers=trusted_headers(account="platform", user="gateway-admin", include_api_key=True),+ )+ assert listed.status_code == 200+ account = next(item for item in listed.json()["result"] if item["account_id"] == acct)+ assert set(account) == {"account_id", "created_at", "user_count", "status"}+ assert account["status"] == "active"+ assert account["user_count"] == 1[email protected]("hashing_enabled", [False, True])async def test_trusted_mode_admin_can_register_user_in_own_account(trusted_admin_client: httpx.AsyncClient,trusted_admin_app,- monkeypatch,- hashing_enabled,):"""Trusted ADMIN requests should be able to manage users in their own account."""- manager = trusted_admin_app.state.api_key_manager- manager._legacy._api_key_hashing_enabled = hashing_enabled- monkeypatch.setattr(- "openviking.server.api_keys.new.generate_api_key",- Mock(side_effect=AssertionError("trusted must not generate personal credentials")),- )acct = _uid()create_resp = await trusted_admin_client.post("/api/v1/admin/accounts",@@ -3222,17 +3123,23 @@ async def test_trusted_mode_admin_can_register_user_in_own_account(assert resp.json()["result"]["user_id"] == "bob"assert "user_key" not in resp.json()["result"]- before = deepcopy(manager._accounts[acct].users)- assert before == {"alice": {"role": "admin"}, "bob": {"role": "user"}}- response = await trusted_admin_client.post(- f"/api/v1/admin/accounts/{acct}/users/bob/key", headers=root_headers()+ users = await trusted_admin_client.get(+ f"/api/v1/admin/accounts/{acct}/users",+ params={"include_credentials": "false"},+ headers=trusted_headers(account=acct, user="alice", include_api_key=True),)- assert response.status_code == 412- assert response.json()["error"]["code"] == "FAILED_PRECONDITION"- assert response.json()["error"]["message"] == "Personal API keys are disabled in trusted mode"- await manager.reload()- assert manager._accounts[acct].users == before- assert manager._legacy._prefix_index == {}+ assert users.status_code == 200+ assert all(+ user["api_key_available"] is False+ for user in users.json()["result"]+ )++ rotated = await trusted_admin_client.post(+ f"/api/v1/admin/accounts/{acct}/users/bob/key",+ headers=root_headers(),+ )+ assert rotated.status_code == 412+ assert rotated.json()["error"]["code"] == "FAILED_PRECONDITION"async def test_trusted_mode_admin_can_list_users_with_account_only_in_url(@@ -3374,32 +3281,6 @@ async def test_trusted_mode_requires_matching_api_key_for_admin_api(assert resp.status_code == 401-async def test_trusted_mode_create_account_lists_current_account_metadata(- trusted_admin_client: httpx.AsyncClient,- trusted_admin_app,-):- """Trusted account creation should list the current account metadata shape."""- acct = _uid()- resp = await trusted_admin_client.post(- "/api/v1/admin/accounts",- json={- "account_id": acct,- "admin_user_id": "alice",- },- headers=trusted_headers(- account="platform",- user="gateway-admin",- include_api_key=True,- ),- )- assert resp.status_code == 200-- manager = trusted_admin_app.state.api_key_manager- account = next(item for item in manager.get_accounts() if item["account_id"] == acct)- assert set(account) == {"account_id", "created_at", "user_count", "status"}- assert account["status"] == "active"--async def test_user_page_summary_and_search_preserve_legacy_response(lightweight_admin_client: httpx.AsyncClient,lightweight_admin_app: FastAPI,@@ -3412,36 +3293,35 @@ async def test_user_page_summary_and_search_preserve_legacy_response()assert created.status_code == 200manager = lightweight_admin_app.state.api_key_manager- seed = {- f"user-{index}": {- "role": "admin" if index == 2832 else "user",- "key": f"test-key-{index}",- }- for index in range(1, 2833)- }- seed["deleting-user"] = {"role": "admin", "key": "deleted", "deletion": {"status": "pending"}}- await manager._legacy._save_users_json(acct, seed)+ for index in range(1, 113):+ last_key = await manager.register_user(+ acct, f"user-{index}", Role.ADMIN if index == 112 else Role.USER+ )+ await manager.register_user(acct, "deleting-user", Role.ADMIN)+ await manager.begin_deletion(+ acct, "deleting-user", task_id="delete", owner_account_id=acct, owner_user_id="owner"+ )url = f"/api/v1/admin/accounts/{acct}/users"response = await lightweight_admin_client.get(- url, params={"include_summary": True, "limit": 20, "page": 142}, headers=root_headers()+ url, params={"include_summary": True, "limit": 20, "page": 6}, headers=root_headers())assert response.status_code == 200, response.textresult = response.json()["result"]assert len(result["users"]) == 13- assert result["users"][-1]["user_id"] == "user-2832"- assert result["total"] == result["account_total"] == result["key_count"] == 2833+ assert result["users"][-1]["user_id"] == "user-112"+ assert result["total"] == result["account_total"] == result["key_count"] == 113assert result["manager_count"] == 2response = await lightweight_admin_client.get(url,- params={"include_summary": True, "limit": 20, "query": " UsEr-2832 "},+ params={"include_summary": True, "limit": 20, "query": " UsEr-112 "},headers=root_headers(),)result = response.json()["result"]assert result["total"] == 1- assert result["users"][0]["user_id"] == "user-2832"- assert result["account_total"] == 2833+ assert result["users"][0]["user_id"] == "user-112"+ assert result["account_total"] == 113assert result["manager_count"] == 2response = await lightweight_admin_client.get(@@ -3451,11 +3331,11 @@ async def test_user_page_summary_and_search_preserve_legacy_response()assert response.json()["result"]["total"] == 0assert response.json()["result"]["users"] == []- assert response.json()["result"]["account_total"] == 2833+ assert response.json()["result"]["account_total"] == 113response = await lightweight_admin_client.get(url, headers=root_headers())assert isinstance(response.json()["result"], list)- assert len(response.json()["result"]) == 2833+ assert len(response.json()["result"]) == 113response = await lightweight_admin_client.get(url,params={"limit": 1, "page": 2, "name": "user-*", "role": "user"},@@ -3463,7 +3343,7 @@ async def test_user_page_summary_and_search_preserve_legacy_response()assert response.json()["result"][0]["user_id"] == "user-2"- hidden = manager.get_users_page(acct, expose_key=False, limit=1)+ hidden = await manager.list_users_page(acct, expose_key=False, limit=1)assert hidden["key_count"] == 0assert "api_key" not in hidden["users"][0]assert "key_prefix" not in hidden["users"][0]@@ -3482,8 +3362,8 @@ async def test_user_page_summary_and_search_preserve_legacy_response(identity = RequestContext(UserIdentifier(acct, "user-1"), role)token = mcp_endpoint._mcp_ctx.set(identity)try:- directory = await mcp_endpoint.list_users(context, query="user-2832")- assert directory == {"users": [{"user_id": "user-2832"}], "total": 1}+ directory = await mcp_endpoint.list_users(context, query="user-112")+ assert directory == {"users": [{"user_id": "user-112"}], "total": 1}assert await mcp_endpoint.list_groups(context) == {"groups": [{"group_id": "engineering"}]}@@ -3495,9 +3375,9 @@ async def test_user_page_summary_and_search_preserve_legacy_response()else:credentials = await mcp_endpoint.list_users(- context, query="user-2832", include_credentials=True+ context, query="user-112", include_credentials=True)- assert credentials["users"][0]["api_key"] == "test-key-2832"+ assert credentials["users"][0]["api_key"] == last_keyoriginal_config = lightweight_admin_app.state.configlightweight_admin_app.state.config = ServerConfig(auth_mode="trusted", root_api_key=ROOT_KEY@@ -3505,7 +3385,7 @@ async def test_user_page_summary_and_search_preserve_legacy_response(try:with pytest.raises(PermissionDeniedError, match="trusted"):await mcp_endpoint.list_users(context, include_credentials=True)- assert await mcp_endpoint.list_users(context, query="user-2832") == directory+ assert await mcp_endpoint.list_users(context, query="user-112") == directoryfinally:lightweight_admin_app.state.config = original_configfinally:diff --git a/tests/server/test_agent_evolution_global_setting.py b/tests/server/test_agent_evolution_global_setting.pyindex 9abb81644..b7c036fc3 100644--- a/tests/server/test_agent_evolution_global_setting.py+++ b/tests/server/test_agent_evolution_global_setting.py@@ -83,22 +83,17 @@ class _FakeRuntimeConfig:class _FakeApiKeyManager:- """Minimal admin-gate stand-in: account existence + user refresh no-ops."""+ """Minimal admin-gate stand-in."""def __init__(self, account_ids):self._account_ids = list(account_ids)- async def refresh_accounts_from_store(self):- return None-- async def refresh_account_users_from_store(self, account_id):- return None-- def ensure_account_active(self, account_id):+ async def get_account(self, account_id):if account_id not in self._account_ids:- raise AssertionError(f"unexpected account: {account_id}")+ return None+ return {"account_id": account_id, "status": "active"}- def get_accounts(self):+ async def list_accounts(self):return [{"account_id": aid} for aid in self._account_ids]diff --git a/tests/server/test_api_key_manager.py b/tests/server/test_api_key_manager.pyindex 40497bdd7..184eb2891 100644--- a/tests/server/test_api_key_manager.py+++ b/tests/server/test_api_key_manager.py@@ -1,19 +1,20 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""Tests for APIKeyManager (openviking/server/api_keys.py)."""+"""Public account and credential contracts through APIKeyManager."""import asyncioimport hashlibimport uuid+from types import SimpleNamespaceimport pytestimport pytest_asyncio-from openviking.pyagfs.exceptions import AGFSNotFoundError+from openviking.pyagfs import AGFSNotFoundErrorfrom openviking.server.api_keys import APIKeyManager-from openviking.server.api_keys.legacy import ACCOUNTS_PATH, USERS_PATH_TEMPLATEfrom openviking.server.identity import Role+from openviking.server.store_assembly import build_api_key_managerfrom openviking_cli.exceptions import (AlreadyExistsError,FailedPreconditionError,@@ -22,6 +23,7 @@ from openviking_cli.exceptions import (PermissionDeniedError,UnauthenticatedError,)+from tests.server.account_store_fakes import InMemoryAGFSdef _uid() -> str:@@ -36,18 +38,23 @@ def _seed_secret(user_id: str, seed: str) -> str:ROOT_KEY = "test-root-key-abcdef1234567890abcdef1234567890"-@pytest_asyncio.fixture(scope="function")-async def manager_service(service):- """Use the shared service fixture with local fake models."""- yield service+def manager_service():+ return SimpleNamespace(viking_fs=SimpleNamespace(agfs=InMemoryAGFS()))@pytest_asyncio.fixture(scope="function")async def manager(manager_service):"""Fresh APIKeyManager instance, loaded."""- mgr = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+ mgr = build_api_key_manager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)await mgr.load()- return mgr+ yield mgr+ await mgr.close()+++async def _list_users(manager, account_id, **filters):+ page = await manager.list_users_page(account_id, **filters)+ return page["users"]# ---- Root key tests ----@@ -55,22 +62,17 @@ async def manager(manager_service):async def test_resolve_root_key(manager: APIKeyManager):"""Root key should resolve to ROOT role."""- identity = manager.resolve(ROOT_KEY)+ identity = await manager.resolve_identity(ROOT_KEY)assert identity.role == Role.ROOTassert identity.account_id is Noneassert identity.user_id is None-async def test_resolve_wrong_key_raises(manager: APIKeyManager):[email protected]("key", ["wrong-key", ""])+async def test_resolve_invalid_key_raises(manager: APIKeyManager, key):"""Invalid key should raise UnauthenticatedError."""with pytest.raises(UnauthenticatedError):- manager.resolve("wrong-key")---async def test_resolve_empty_key_raises(manager: APIKeyManager):- """Empty key should raise UnauthenticatedError."""- with pytest.raises(UnauthenticatedError):- manager.resolve("")+ await manager.resolve_identity(key)# ---- Account lifecycle tests ----@@ -78,17 +80,19 @@ async def test_resolve_empty_key_raises(manager: APIKeyManager):async def test_create_account(manager: APIKeyManager):"""create_account should create workspace + first admin user."""+ from openviking.server.api_keys import parse_api_key+acct = _uid()key = await manager.create_account(acct, "alice")- assert isinstance(key, str)- # New format: base64url(account_id).base64url(user_id).base64url(secret)- # Length varies based on account_id and user_id, but should have two dots- assert key.count(".") == 2+ account_id, user_id, secret = parse_api_key(key)+ assert (account_id, user_id) == (acct, "alice")+ assert secret- identity = manager.resolve(key)+ identity = await manager.resolve_identity(key)assert identity.role == Role.ADMINassert identity.account_id == acctassert identity.user_id == "alice"+ assert await manager.get_registered_user_role(acct, "alice") == Role.ADMINasync def test_create_duplicate_account_raises(manager: APIKeyManager):@@ -99,345 +103,25 @@ async def test_create_duplicate_account_raises(manager: APIKeyManager):await manager.create_account(acct, "bob")-async def test_ensure_trusted_identities_creates_keyless_users_once(- manager: APIKeyManager, monkeypatch: pytest.MonkeyPatch+async def test_ensure_trusted_identities_creates_missing_users_once(+ manager: APIKeyManager,):"""Trusted identity batches add only missing users and never mint keys."""acme = _uid()globex = _uid()- logged: list[tuple] = []-- def _record_info(*args) -> None:- logged.append(args)-- monkeypatch.setattr(manager._legacy.__module__ + ".logger.info", _record_info)result = await manager.ensure_trusted_identities({acme: {"alice", "bob"}, globex: {"eve"}})assert result == {"created_accounts": 2, "created_users": 3}- assert logged == [- ("Persisted trusted identities for account %s: %s", acme, ["alice", "bob"]),- ("Persisted trusted identities for account %s: %s", globex, ["eve"]),- ]- assert manager.get_user_role(acme, "alice") == Role.USER- assert "key" not in manager._legacy._accounts[acme].users["alice"]- assert manager.get_users(acme, expose_key=True) == [+ assert await manager.get_registered_user_role(acme, "alice") == Role.USER+ assert await _list_users(manager, acme, expose_key=True) == [{"user_id": "alice", "role": "user"},{"user_id": "bob", "role": "user"},]- writes: list[str] = []- original_write = manager._legacy._write_json-- async def _record_write(path: str, data: dict, lease_ref=None):- writes.append(path)- await original_write(path, data, lease_ref)-- monkeypatch.setattr(manager._legacy, "_write_json", _record_write)- repeat = await manager.ensure_trusted_identities(- {acme: {"alice", "bob"}, globex: {"eve"}}- )+ repeat = await manager.ensure_trusted_identities({acme: {"alice", "bob"}, globex: {"eve"}})assert repeat == {"created_accounts": 0, "created_users": 0}- assert writes == []---async def test_trusted_identity_merge_serializes_with_user_registration(- manager: APIKeyManager, monkeypatch: pytest.MonkeyPatch-):- """A background merge cannot overlap a manager mutation in one process."""- acct = _uid()- await manager.create_account(acct, "alice")-- entered_merge = asyncio.Event()- release_merge = asyncio.Event()- original_merge = manager._legacy._ensure_trusted_identities_unlocked-- async def _blocked_merge(identities):- entered_merge.set()- await release_merge.wait()- return await original_merge(identities)-- monkeypatch.setattr(manager._legacy, "_ensure_trusted_identities_unlocked", _blocked_merge)- merge_task = asyncio.create_task(- manager.ensure_trusted_identities({acct: {"trusted-user"}})- )- await entered_merge.wait()-- register_task = asyncio.create_task(manager.register_user(acct, "bob"))- await asyncio.sleep(0)- assert not register_task.done()-- release_merge.set()- await asyncio.gather(merge_task, register_task)- assert {item["user_id"] for item in manager.get_users(acct)} == {- "alice",- "bob",- "trusted-user",- }---async def test_reload_serializes_with_account_deletion(- manager: APIKeyManager, monkeypatch: pytest.MonkeyPatch-):- """Reload must not restore an account deleted while an old snapshot is building."""- acct = _uid()- await manager.create_account(acct, "alice")-- entered_build = asyncio.Event()- release_build = asyncio.Event()- original_build = manager._legacy._build_state-- async def _blocked_build(accounts_data, *, allow_migration):- entered_build.set()- await release_build.wait()- return await original_build(accounts_data, allow_migration=allow_migration)-- monkeypatch.setattr(manager._legacy, "_build_state", _blocked_build)- reload_task = asyncio.create_task(manager.reload())- await entered_build.wait()-- delete_task = asyncio.create_task(manager.delete_account(acct))- await asyncio.sleep(0)- assert not delete_task.done()-- release_build.set()- await asyncio.gather(reload_task, delete_task)- assert all(item["account_id"] != acct for item in manager.get_accounts())---async def test_identity_registry_refresh_reads_another_instances_trusted_user(- manager: APIKeyManager, manager_service-):- """A management reader refreshes a changed account/user registry on demand."""- replica = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)- await replica.load()- acct = _uid()-- await manager.ensure_trusted_identities({acct: {"alice"}})- assert replica.has_user(acct, "alice") is False-- assert await replica.refresh_identity_registry_if_changed(acct) is True- assert replica.has_user(acct, "alice") is True---async def test_account_registry_refresh_check_stats_only_accounts_file(- manager: APIKeyManager, monkeypatch: pytest.MonkeyPatch-):- """The account-list fast path must not stat every account's users file."""- stat_paths: list[str] = []-- async def _record_stat(path: str) -> tuple:- stat_paths.append(path)- return (path,)-- monkeypatch.setattr(manager._legacy, "_stat_signature", _record_stat)-- await manager._legacy._identity_registry_signature()-- assert stat_paths == [ACCOUNTS_PATH]---async def test_refresh_accounts_from_store_does_not_read_user_registries(- manager: APIKeyManager, monkeypatch: pytest.MonkeyPatch-):- """An account-list refresh reads only accounts.json and keeps cached users."""- acct = _uid()- await manager.create_account(acct, "alice")- cached_users = manager._legacy._accounts[acct].users- original_read_json = manager._legacy._read_json- read_paths: list[str] = []-- async def _record_read(path: str):- read_paths.append(path)- return await original_read_json(path)-- monkeypatch.setattr(manager._legacy, "_read_json", _record_read)-- await manager.refresh_accounts_from_store()-- assert read_paths == [ACCOUNTS_PATH]- assert manager._legacy._accounts[acct].users is cached_users- account = next(item for item in manager.get_accounts() if item["account_id"] == acct)- assert account["user_count"] == 1---async def test_refresh_account_users_from_store_reads_only_target_registry(- manager: APIKeyManager, monkeypatch: pytest.MonkeyPatch-):- """A user-list refresh reads and replaces only the requested account's users."""- target = _uid()- unrelated = _uid()- await manager.create_account(target, "alice")- await manager.create_account(unrelated, "bob")- unrelated_users = manager._legacy._accounts[unrelated].users- original_read_json = manager._legacy._read_json- read_paths: list[str] = []-- async def _record_read(path: str):- read_paths.append(path)- return await original_read_json(path)-- monkeypatch.setattr(manager._legacy, "_read_json", _record_read)-- await manager.refresh_account_users_from_store(target)-- assert read_paths == [USERS_PATH_TEMPLATE.format(account_id=target)]- assert manager._legacy._accounts[unrelated].users is unrelated_users---async def test_refresh_account_users_from_store_is_atomic_on_invalid_data(- manager: APIKeyManager, monkeypatch: pytest.MonkeyPatch-):- """An invalid persisted user must not partially replace authentication state."""- acct = _uid()- user_key = await manager.create_account(acct, "alice")- cached_users = manager._legacy._accounts[acct].users- users_path = USERS_PATH_TEMPLATE.format(account_id=acct)- original_read_json = manager._legacy._read_json-- async def _read_invalid_role(path: str):- if path == users_path:- return {"users": {"mallory": {"role": "invalid", "key": "bad-key"}}}- return await original_read_json(path)-- monkeypatch.setattr(manager._legacy, "_read_json", _read_invalid_role)-- with pytest.raises(ValueError):- await manager.refresh_account_users_from_store(acct)-- assert manager._legacy._accounts[acct].users is cached_users- identity = manager.resolve(user_key)- assert identity.account_id == acct- assert identity.user_id == "alice"---async def test_scoped_store_refresh_observes_another_manager(- manager: APIKeyManager, manager_service-):- """Scoped refreshes expose another manager's account and user changes."""- replica = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)- await replica.load()- acct = _uid()-- key = await manager.create_account(acct, "alice")- await replica.refresh_accounts_from_store()- account = next(item for item in replica.get_accounts() if item["account_id"] == acct)- assert account["user_count"] == 0-- await replica.refresh_account_users_from_store(acct)- assert replica.get_users(acct, expose_key=False) == [- {"user_id": "alice", "role": "admin"}- ]- account = next(item for item in replica.get_accounts() if item["account_id"] == acct)- assert account["user_count"] == 1-- deletion, _ = await manager.begin_deletion(- acct, None, task_id="delete-account", owner_account_id="_system", owner_user_id="root"- )- await replica.refresh_accounts_from_store()- assert replica.get_deletion(acct) == deletion- with pytest.raises(UnauthenticatedError):- replica.resolve(key)---async def test_account_only_refresh_loads_groups_before_group_write(manager_service):- """A partially discovered account must not overwrite persisted groups."""- writer = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)- reader = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)- await writer.load()- await reader.load()- acct = _uid()-- await writer.create_account(acct, "alice")- await writer.create_group(acct, "engineering")- await writer.add_group_member(acct, "engineering", "alice")-- await reader.refresh_accounts_from_store()- discovered = reader._legacy._accounts[acct]- assert discovered.groups_loaded is False- assert discovered.groups == {}-- await reader.create_group(acct, "finance")-- verifier = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)- await verifier.load()- assert verifier.get_groups(acct) == [- {"group_id": "engineering", "member_count": 1},- {"group_id": "finance", "member_count": 0},- ]- assert verifier.get_group_members(acct, "engineering") == ["alice"]---async def test_account_only_refresh_discards_recreated_account_state(- manager: APIKeyManager, monkeypatch: pytest.MonkeyPatch-):- """A recreated account must not retain users or keys from its old incarnation."""- acct = _uid()- old_key = await manager.create_account(acct, "alice")- original_read_json = manager._legacy._read_json-- async def _read_recreated_account(path: str):- if path == ACCOUNTS_PATH:- return {"accounts": {acct: {"created_at": "recreated"}}}- return await original_read_json(path)-- monkeypatch.setattr(manager._legacy, "_read_json", _read_recreated_account)-- await manager.refresh_accounts_from_store()-- account = next(item for item in manager.get_accounts() if item["account_id"] == acct)- assert account == {- "account_id": acct,- "created_at": "recreated",- "user_count": 0,- "status": "active",- }- with pytest.raises(UnauthenticatedError):- manager.resolve(old_key)---async def test_refresh_known_account_without_users_file_returns_empty_users(- manager: APIKeyManager, monkeypatch: pytest.MonkeyPatch-):- """A missing users.json is an empty registry for an account already in memory."""- original_read_json = manager._legacy._read_json-- async def _missing_default_users(path: str):- if path == USERS_PATH_TEMPLATE.format(account_id="default"):- return None- return await original_read_json(path)-- monkeypatch.setattr(manager._legacy, "_read_json", _missing_default_users)-- await manager.refresh_account_users_from_store("default")-- assert manager.get_users("default", expose_key=False) == []---async def test_trusted_identity_merge_refreshes_only_affected_user_signatures(- manager: APIKeyManager, monkeypatch: pytest.MonkeyPatch-):- """A trusted batch must not stat unrelated accounts' user registries."""- target = _uid()- unrelated = _uid()- await manager.create_account(target, "admin")- await manager.create_account(unrelated, "admin")-- stat_paths: list[str] = []- original_stat = manager._legacy._stat_signature-- async def _record_stat(path: str) -> tuple:- stat_paths.append(path)- return await original_stat(path)-- monkeypatch.setattr(manager._legacy, "_stat_signature", _record_stat)-- await manager.ensure_trusted_identities({target: {"trusted-user"}})-- assert stat_paths.count(ACCOUNTS_PATH) == 1- assert stat_paths.count(USERS_PATH_TEMPLATE.format(account_id=target)) == 1- assert USERS_PATH_TEMPLATE.format(account_id=unrelated) not in stat_pathsasync def test_management_writer_preserves_a_trusted_identity_from_another_instance(@@ -447,17 +131,17 @@ async def test_management_writer_preserves_a_trusted_identity_from_another_instaacct = _uid()await manager.create_account(acct, "admin")- replica = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+ replica = build_api_key_manager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)await replica.load()await manager.ensure_trusted_identities({acct: {"trusted-user"}})- assert replica.has_user(acct, "trusted-user") is False+ assert await replica.has_user(acct, "trusted-user") is Falseawait replica.register_user(acct, "managed-user")- verifier = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+ verifier = build_api_key_manager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)await verifier.load()- assert {item["user_id"] for item in verifier.get_users(acct)} == {+ assert {item["user_id"] for item in await _list_users(verifier, acct)} == {"admin","trusted-user","managed-user",@@ -470,18 +154,17 @@ async def test_concurrent_management_registration_of_same_user_rejects_second_wr"""The second stale instance must not replace the first user's key."""acct = _uid()await manager.create_account(acct, "admin")- replica = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+ replica = build_api_key_manager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)await replica.load()first_key = await manager.register_user(acct, "alice")with pytest.raises(AlreadyExistsError):await replica.register_user(acct, "alice")- assert replica.has_user(acct, "alice") is False- verifier = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+ verifier = build_api_key_manager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)await verifier.load()- assert verifier.resolve(first_key).user_id == "alice"+ assert (await verifier.resolve_identity(first_key)).user_id == "alice"async def test_management_registration_does_not_replace_a_trusted_user(@@ -490,7 +173,7 @@ async def test_management_registration_does_not_replace_a_trusted_user("""A stale management writer must reject an identity created by trusted flush."""acct = _uid()await manager.create_account(acct, "admin")- replica = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+ replica = build_api_key_manager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)await replica.load()await manager.ensure_trusted_identities({acct: {"alice"}})@@ -498,14 +181,10 @@ async def test_management_registration_does_not_replace_a_trusted_user(with pytest.raises(AlreadyExistsError):await replica.register_user(acct, "alice")- verifier = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+ verifier = build_api_key_manager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)await verifier.load()- assert verifier.get_users(acct, expose_key=True) == [- {- "user_id": "admin",- "role": "admin",- "api_key": manager._accounts[acct].users["admin"]["key"],- },+ assert await _list_users(verifier, acct, expose_key=False) == [+ {"user_id": "admin", "role": "admin"},{"user_id": "alice", "role": "user"},]@@ -514,7 +193,7 @@ async def test_management_account_writer_preserves_a_trusted_account_from_anothemanager: APIKeyManager, manager_service):"""A stale account write must retain accounts registered by another instance."""- replica = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+ replica = build_api_key_manager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)await replica.load()trusted_account = _uid()managed_account = _uid()@@ -522,9 +201,9 @@ async def test_management_account_writer_preserves_a_trusted_account_from_anotheawait manager.ensure_trusted_identities({trusted_account: {"trusted-user"}})await replica.create_account(managed_account, "managed-admin")- verifier = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+ verifier = build_api_key_manager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)await verifier.load()- assert {item["account_id"] for item in verifier.get_accounts()} >= {+ assert {item["account_id"] for item in await verifier.list_accounts()} >= {trusted_account,managed_account,}@@ -534,7 +213,7 @@ async def test_concurrent_management_creation_of_same_account_rejects_second_wrimanager: APIKeyManager, manager_service):"""A stale instance cannot create a second admin for an existing account."""- replica = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+ replica = build_api_key_manager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)await replica.load()account_id = _uid()@@ -542,54 +221,29 @@ async def test_concurrent_management_creation_of_same_account_rejects_second_wriwith pytest.raises(AlreadyExistsError):await replica.create_account(account_id, "bob")- assert account_id not in replica._legacy._accounts- verifier = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+ verifier = build_api_key_manager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)await verifier.load()- assert verifier.resolve(first_key).user_id == "alice"- assert verifier.get_users(account_id, expose_key=False) == [+ assert (await verifier.resolve_identity(first_key)).user_id == "alice"+ assert await _list_users(verifier, account_id, expose_key=False) == [{"user_id": "alice", "role": "admin"}]-async def test_create_account_rolls_back_when_user_persistence_fails(- manager: APIKeyManager, monkeypatch: pytest.MonkeyPatch-):- """create_account should not leave partial in-memory state after a write failure."""- acct = _uid()- original_save_users_json = manager._legacy._save_users_json-- async def _fail_save_users_json(account_id: str, *args, **kwargs) -> None:- if account_id == acct:- raise AGFSNotFoundError(account_id)- await original_save_users_json(account_id, *args, **kwargs)-- monkeypatch.setattr(manager._legacy, "_save_users_json", _fail_save_users_json)-- with pytest.raises(AGFSNotFoundError):- await manager.create_account(acct, "alice")-- assert acct not in manager._legacy._accounts-- monkeypatch.setattr(manager._legacy, "_save_users_json", original_save_users_json)- retry_key = await manager.create_account(acct, "alice")- assert manager.resolve(retry_key).account_id == acct--async def test_delete_account(manager: APIKeyManager):- """The durable account fence revokes keys and survives reload until its owner finishes."""+ """The durable account fence revokes keys until its owner finishes."""from openviking_cli.exceptions import FailedPreconditionErroracct = _uid()key = await manager.create_account(acct, "alice")- assert manager.resolve(key).account_id == acct+ assert (await manager.resolve_identity(key)).account_id == acctdeletion, created = await manager.begin_deletion(acct, None, task_id="delete-account-1", owner_account_id="_system", owner_user_id="root")assert created- with pytest.raises(UnauthenticatedError):- manager.resolve(key)- assert manager.get_user_key_fingerprint(acct, "alice") is None+ with pytest.raises(UnauthenticatedError, match="Invalid API key"):+ await manager.resolve_identity(key)+ assert await manager.get_user_key_fingerprint(acct, "alice") is Nonewith pytest.raises(AlreadyExistsError):await manager.create_account(acct, "bob")with pytest.raises(FailedPreconditionError):@@ -597,12 +251,11 @@ async def test_delete_account(manager: APIKeyManager):with pytest.raises(FailedPreconditionError):await manager.regenerate_key(acct, "alice")await manager.ensure_trusted_identities({acct: {"trusted-user"}})- assert not manager.has_user(acct, "trusted-user")+ assert not await manager.has_user(acct, "trusted-user")- await manager.reload()- assert manager.get_deletion(acct) == deletion- with pytest.raises(UnauthenticatedError):- manager.resolve(key)+ assert await manager.get_deletion(acct) == deletion+ with pytest.raises(UnauthenticatedError, match="Invalid API key"):+ await manager.resolve_identity(key)assert await manager.finish_deletion(acct, None, "stale-task") is Falsereplacement = await manager.replace_deletion_task(acct,@@ -615,8 +268,8 @@ async def test_delete_account(manager: APIKeyManager):assert replacement["task_id"] == "delete-account-2"assert await manager.finish_deletion(acct, None, "delete-account-1") is Falseassert await manager.finish_deletion(acct, None, "delete-account-2") is True- assert not manager.has_user(acct, "alice")- assert manager.get_deletion(acct) is None+ assert not await manager.has_user(acct, "alice")+ assert await manager.get_deletion(acct) is Noneasync def test_recreated_account_does_not_restore_deleted_users(manager: APIKeyManager):@@ -628,9 +281,9 @@ async def test_recreated_account_does_not_restore_deleted_users(manager: APIKeyMnew_key = await manager.create_account(acct, "new-admin")with pytest.raises(UnauthenticatedError):- manager.resolve(old_key)- assert manager.resolve(new_key).user_id == "new-admin"- assert manager.get_users(acct, expose_key=False) == [+ await manager.resolve_identity(old_key)+ assert (await manager.resolve_identity(new_key)).user_id == "new-admin"+ assert await _list_users(manager, acct, expose_key=False) == [{"user_id": "new-admin", "role": "admin"}]@@ -643,31 +296,26 @@ async def test_delete_nonexistent_account_raises(manager: APIKeyManager):async def test_default_account_exists(manager: APIKeyManager):"""Default account should be created on load."""- accounts = manager.get_accounts()+ accounts = await manager.list_accounts()assert any(a["account_id"] == "default" for a in accounts)@pytest.mark.parametrize("operation", ["create", "delete", "trusted"])async def test_account_mutation_preserves_registry_when_baseline_is_missing(- manager: APIKeyManager, monkeypatch: pytest.MonkeyPatch, operation: str+ manager: APIKeyManager, manager_service, monkeypatch: pytest.MonkeyPatch, operation: str):survivor = _uid()key = await manager.create_account(survivor, "alice")target = _uid()if operation == "delete":await manager.create_account(target, "bob")- read = manager._legacy._async_agfs.read- before = await read(ACCOUNTS_PATH)- missing_reads = 0-- async def missing_once(path, *args, **kwargs):- nonlocal missing_reads- if path == ACCOUNTS_PATH and missing_reads == 0:- missing_reads += 1- raise AGFSNotFoundError("injected missing registry read")- return await read(path, *args, **kwargs)+ agfs = manager_service.viking_fs.agfs+ read = agfs.read- monkeypatch.setattr(manager._legacy._async_agfs, "read", missing_once)+ def missing_registry(path, *args, **kwargs):+ if path == "/local/_system/accounts.json":+ raise AGFSNotFoundError("injected missing registry read")+ return read(path, *args, **kwargs)async def mutate():if operation == "create":@@ -676,17 +324,25 @@ async def test_account_mutation_preserves_registry_when_baseline_is_missing(return await manager.delete_account(target)return await manager.ensure_trusted_identities({target: {"bob"}})- with pytest.raises(FailedPreconditionError, match="Account registry"):- await mutate()- assert missing_reads == 1- assert await read(ACCOUNTS_PATH) == before- assert manager.resolve(key).account_id == survivor- await manager.reload()- assert manager.resolve(key).account_id == survivor- # The failed mutation must also release its lease and leave retries usable.- await mutate()- await manager.reload()- assert manager.resolve(key).account_id == survivor+ with monkeypatch.context() as patch:+ patch.setattr(agfs, "read", missing_registry)+ with pytest.raises(FailedPreconditionError, match="Account registry"):+ await mutate()+ assert (await manager.resolve_identity(key)).account_id == survivor++ # Check durable state both after failure and after a successful retry.+ for retried in (False, True):+ if retried:+ await mutate()+ verifier = build_api_key_manager(ROOT_KEY, manager_service.viking_fs)+ await verifier.load()+ try:+ assert (await verifier.resolve_identity(key)).account_id == survivor+ target_exists = (operation == "delete") != retried+ assert await verifier.has_user(target, "bob") == target_exists+ assert (await verifier.get_account(target) is not None) == target_exists+ finally:+ await verifier.close()# ---- User lifecycle tests ----@@ -694,66 +350,18 @@ async def test_account_mutation_preserves_registry_when_baseline_is_missing(async def test_register_user(manager: APIKeyManager):"""register_user should create a user with given role."""+ from openviking.server.api_keys import parse_api_key+acct = _uid()await manager.create_account(acct, "alice")key = await manager.register_user(acct, "bob", "user")+ assert parse_api_key(key)[:2] == (acct, "bob")- identity = manager.resolve(key)+ identity = await manager.resolve_identity(key)assert identity.role == Role.USERassert identity.account_id == acctassert identity.user_id == "bob"---async def test_concurrent_registry_writes_wait_for_locks(manager: APIKeyManager):- first_account = _uid()- second_account = _uid()- accounts_block = asyncio.Event()- original_acquire = manager._legacy._async_agfs.pathlock_acquire_exact-- async def blocked_acquire(path, timeout_secs=10.0, owner_lease_ref=None, *, fs_ctx=None):- del owner_lease_ref, fs_ctx- if path == ACCOUNTS_PATH:- await accounts_block.wait()- return await original_acquire(path, timeout_secs=timeout_secs)-- manager._legacy._async_agfs.pathlock_acquire_exact = blocked_acquire-- account_tasks = [- asyncio.create_task(manager.create_account(first_account, "alice")),- asyncio.create_task(manager.create_account(second_account, "bob")),- ]- await asyncio.sleep(0.05)- assert all(not task.done() for task in account_tasks)-- accounts_block.set()- await asyncio.gather(*account_tasks)- accounts = await manager._read_json(ACCOUNTS_PATH)- assert {first_account, second_account} <= set(accounts["accounts"])-- users_path = f"/local/{first_account}/_system/users.json"- users_block = asyncio.Event()-- async def blocked_users_acquire(path, timeout_secs=10.0, owner_lease_ref=None, *, fs_ctx=None):- del owner_lease_ref, fs_ctx- if path == users_path:- await users_block.wait()- return await original_acquire(path, timeout_secs=timeout_secs)-- manager._legacy._async_agfs.pathlock_acquire_exact = blocked_users_acquire-- user_tasks = [- asyncio.create_task(manager.register_user(first_account, "bob")),- asyncio.create_task(manager.register_user(first_account, "carol")),- ]- await asyncio.sleep(0.05)- assert all(not task.done() for task in user_tasks)-- users_block.set()- await asyncio.gather(*user_tasks)- users = await manager._read_json(users_path)- assert set(users["users"]) == {"alice", "bob", "carol"}-- manager._legacy._async_agfs.pathlock_acquire_exact = original_acquire+ assert await manager.get_registered_user_role(acct, "bob") == Role.USERasync def test_register_duplicate_user_raises(manager: APIKeyManager):@@ -787,19 +395,46 @@ async def test_user_deletion_fence_revokes_key_and_rejects_stale_finish(assert created is Trueassert deletion["task_id"] == "delete-1"- assert manager.is_deleting(acct, "bob")- with pytest.raises(UnauthenticatedError):- manager.resolve(bob_key)+ assert await manager.get_deletion(acct, "bob") == deletion+ with pytest.raises(UnauthenticatedError, match="Invalid API key"):+ await manager.resolve_identity(bob_key)with pytest.raises(AlreadyExistsError):await manager.register_user(acct, "bob", "user")assert await manager.finish_deletion(acct, "bob", "stale") is False- assert manager.has_user(acct, "bob")+ assert await manager.has_user(acct, "bob")assert await manager.finish_deletion(acct, "bob", "delete-1") is True- assert not manager.has_user(acct, "bob")+ assert not await manager.has_user(acct, "bob")new_key = await manager.register_user(acct, "bob", "user")assert await manager.finish_deletion(acct, "bob", "delete-1") is False- assert manager.resolve(new_key).user_id == "bob"+ assert (await manager.resolve_identity(new_key)).user_id == "bob"+++async def test_account_deletion_fence_overrides_user_deletion_fence(manager: APIKeyManager):+ acct = _uid()+ await manager.create_account(acct, "alice")+ await manager.register_user(acct, "bob")+ user_deletion, user_created = await manager.begin_deletion(+ acct,+ "bob",+ task_id="delete-user",+ owner_account_id=acct,+ owner_user_id="alice",+ )+ account_deletion, account_created = await manager.begin_deletion(+ acct,+ None,+ task_id="delete-account",+ owner_account_id=acct,+ owner_user_id="alice",+ )++ assert user_created+ assert account_created+ assert user_deletion["task_id"] == "delete-user"+ assert await manager.get_deletion(acct, "bob") == account_deletion++async def test_regenerate_key(manager: APIKeyManager):"""Regenerating key should invalidate old key and return new valid key."""acct = _uid()@@ -811,10 +446,10 @@ async def test_regenerate_key(manager: APIKeyManager):# Old key invalidwith pytest.raises(UnauthenticatedError):- manager.resolve(old_key)+ await manager.resolve_identity(old_key)# New key valid- identity = manager.resolve(new_key)+ identity = await manager.resolve_identity(new_key)assert identity.user_id == "bob"assert identity.account_id == acct@@ -825,16 +460,16 @@ async def test_get_user_key_fingerprint_changes_on_rotation(manager: APIKeyManagawait manager.create_account(acct, "alice")await manager.register_user(acct, "bob", "user")- fp1 = manager.get_user_key_fingerprint(acct, "bob")+ fp1 = await manager.get_user_key_fingerprint(acct, "bob")assert fp1 is not Noneassert len(fp1) == 64 # sha256 hex# Same call should be deterministic.- assert manager.get_user_key_fingerprint(acct, "bob") == fp1+ assert await manager.get_user_key_fingerprint(acct, "bob") == fp1# Rotation flips the stored value → fp must change.await manager.regenerate_key(acct, "bob")- fp2 = manager.get_user_key_fingerprint(acct, "bob")+ fp2 = await manager.get_user_key_fingerprint(acct, "bob")assert fp2 is not Noneassert fp2 != fp1@@ -846,11 +481,11 @@ async def test_get_user_key_fingerprint_changes_on_rotation(manager: APIKeyManagowner_account_id=acct,owner_user_id="alice",)- assert manager.get_user_key_fingerprint(acct, "bob") is None+ assert await manager.get_user_key_fingerprint(acct, "bob") is Noneasync def test_get_user_key_fingerprint_unknown_returns_none(manager: APIKeyManager):- assert manager.get_user_key_fingerprint("nope", "nobody") is None+ assert await manager.get_user_key_fingerprint("nope", "nobody") is Noneasync def test_set_role(manager: APIKeyManager):@@ -859,23 +494,23 @@ async def test_set_role(manager: APIKeyManager):await manager.create_account(acct, "alice")bob_key = await manager.register_user(acct, "bob", "user")- assert manager.resolve(bob_key).role == Role.USER+ assert (await manager.resolve_identity(bob_key)).role == Role.USERawait manager.set_role(acct, "bob", "admin")- assert manager.resolve(bob_key).role == Role.ADMIN+ assert (await manager.resolve_identity(bob_key)).role == Role.ADMINwith pytest.raises(PermissionDeniedError, match="server.root_api_key"):await manager.set_role(acct, "bob", Role.ROOT)- assert manager.resolve(bob_key).role == Role.ADMIN+ assert (await manager.resolve_identity(bob_key)).role == Role.ADMINasync def test_get_users(manager: APIKeyManager):- """get_users should list all users in an account."""+ """list_users should list all users in an account."""acct = _uid()await manager.create_account(acct, "alice")await manager.register_user(acct, "bob", "user")- users = manager.get_users(acct)+ users = await _list_users(manager, acct)user_ids = {u["user_id"] for u in users}assert user_ids == {"alice", "bob"}@@ -890,33 +525,35 @@ async def test_get_users(manager: APIKeyManager):owner_account_id=acct,owner_user_id="alice",)- users = manager.get_users(acct)+ users = await _list_users(manager, acct)assert {u["user_id"] for u in users} == {"alice"}async def test_get_users_name_filter(manager: APIKeyManager):- """get_users name_filter uses fnmatch wildcard matching against user IDs."""+ """list_users name_filter uses fnmatch wildcard matching against user IDs."""acct = _uid()await manager.create_account(acct, "alice")await manager.register_user(acct, "alan", "user")await manager.register_user(acct, "bob", "user")# Wildcard substring match- matched = {u["user_id"] for u in manager.get_users(acct, name_filter="al*")}+ matched = {u["user_id"] for u in await _list_users(manager, acct, name_filter="al*")}assert matched == {"alice", "alan"}# Exact match (no wildcard) only hits the literal ID- assert {u["user_id"] for u in manager.get_users(acct, name_filter="alice")} == {"alice"}+ assert {u["user_id"] for u in await _list_users(manager, acct, name_filter="alice")} == {+ "alice"+ }# No match- assert manager.get_users(acct, name_filter="zzz*") == []+ assert await _list_users(manager, acct, name_filter="zzz*") == []# No filter returns all- assert {u["user_id"] for u in manager.get_users(acct)} == {"alice", "alan", "bob"}+ assert {u["user_id"] for u in await _list_users(manager, acct)} == {"alice", "alan", "bob"}async def test_get_accounts_filter(manager: APIKeyManager):- """get_accounts supports fnmatch name_filter, mirroring get_users."""+ """list_accounts supports fnmatch name_filter, mirroring list_users."""prefix = f"acme_{uuid.uuid4().hex[:8]}"first = f"{prefix}_alpha"second = f"{prefix}_beta"@@ -926,19 +563,19 @@ async def test_get_accounts_filter(manager: APIKeyManager):await manager.create_account(other, "u3")# Wildcard match returns only the two prefixed accounts- matched = {a["account_id"] for a in manager.get_accounts(name_filter=f"{prefix}*")}+ matched = {a["account_id"] for a in await manager.list_accounts(name_filter=f"{prefix}*")}assert matched == {first, second}# Exact match (no wildcard) hits a single account- assert {a["account_id"] for a in manager.get_accounts(name_filter=first)} == {first}+ assert {a["account_id"] for a in await manager.list_accounts(name_filter=first)} == {first}# No filter returns all accounts (including the default one)- all_ids = {a["account_id"] for a in manager.get_accounts()}+ all_ids = {a["account_id"] for a in await manager.list_accounts()}assert {first, second, other} <= all_idsasync def test_get_users_pagination_and_ordering(manager: APIKeyManager):- """get_users returns users in creation order and honors limit/page."""+ """list_users returns users in creation order and honors limit/page."""acct = _uid()await manager.create_account(acct, "alice")# Register out of alphabetical order; creation order is alice, dave, bob, carol.@@ -947,23 +584,23 @@ async def test_get_users_pagination_and_ordering(manager: APIKeyManager):await manager.register_user(acct, "carol", "user")# No limit -> all users, in creation order.- ids = [u["user_id"] for u in manager.get_users(acct)]+ ids = [u["user_id"] for u in await _list_users(manager, acct)]assert ids == ["alice", "dave", "bob", "carol"]# First page of 2 (creation order).- page1 = [u["user_id"] for u in manager.get_users(acct, limit=2, page=1)]+ page1 = [u["user_id"] for u in await _list_users(manager, acct, limit=2, page=1)]assert page1 == ["alice", "dave"]# Second page of 2 (creation order).- page2 = [u["user_id"] for u in manager.get_users(acct, limit=2, page=2)]+ page2 = [u["user_id"] for u in await _list_users(manager, acct, limit=2, page=2)]assert page2 == ["bob", "carol"]# Page past the end is empty.- assert manager.get_users(acct, limit=2, page=3) == []+ assert await _list_users(manager, acct, limit=2, page=3) == []async def test_get_accounts_pagination_and_ordering(manager: APIKeyManager):- """get_accounts returns accounts in creation order and honors limit/page."""+ """list_accounts returns accounts in creation order and honors limit/page."""prefix = f"page_{uuid.uuid4().hex[:8]}"# Creation order matches this list.ids = [f"{prefix}_{suffix}" for suffix in ("delta", "alpha", "charlie", "bravo")]@@ -971,24 +608,30 @@ async def test_get_accounts_pagination_and_ordering(manager: APIKeyManager):await manager.create_account(account_id, "u")# No limit -> all matches, in creation order.- got = [a["account_id"] for a in manager.get_accounts(name_filter=f"{prefix}*")]+ got = [a["account_id"] for a in await manager.list_accounts(name_filter=f"{prefix}*")]assert got == ids# First page of 2 (creation order).- page1 = [a["account_id"] for a in manager.get_accounts(name_filter=f"{prefix}*", limit=2, page=1)]+ page1 = [+ a["account_id"]+ for a in await manager.list_accounts(name_filter=f"{prefix}*", limit=2, page=1)+ ]assert page1 == ids[:2]# Second page of 2 (creation order).- page2 = [a["account_id"] for a in manager.get_accounts(name_filter=f"{prefix}*", limit=2, page=2)]+ page2 = [+ a["account_id"]+ for a in await manager.list_accounts(name_filter=f"{prefix}*", limit=2, page=2)+ ]assert page2 == ids[2:]# Page past the end is empty.- assert manager.get_accounts(name_filter=f"{prefix}*", limit=2, page=3) == []+ assert await manager.list_accounts(name_filter=f"{prefix}*", limit=2, page=3) == []async def test_user_and_group_persistence_across_reload(manager_service):"""Reload preserves keys/groups, while user deletion removes membership."""- mgr1 = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+ mgr1 = build_api_key_manager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)await mgr1.load()acct = _uid()@@ -999,16 +642,16 @@ async def test_user_and_group_persistence_across_reload(manager_service):group_id = created_group["group_id"]assert await mgr1.add_group_member(acct, group_id, "bob") is Trueassert await mgr1.add_group_member(acct, group_id, "bob") is True- assert mgr1._accounts[acct].groups == {"engineering": {"members": ["bob"]}}+ assert await mgr1.get_group_members(acct, group_id) == ["bob"]- mgr2 = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+ mgr2 = build_api_key_manager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)await mgr2.load()- identity = mgr2.resolve(key)+ identity = await mgr2.resolve_identity(key)assert identity.account_id == acctassert identity.user_id == "alice"assert identity.role == Role.ADMIN- assert mgr2.get_user_group_ids(acct, "bob") == (group_id,)+ assert await mgr2.get_user_group_ids(acct, "bob") == (group_id,)await mgr2.begin_deletion(acct,@@ -1019,286 +662,15 @@ async def test_user_and_group_persistence_across_reload(manager_service):)await mgr2.finish_deletion(acct, "bob", "delete-bob")- mgr3 = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+ mgr3 = build_api_key_manager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)await mgr3.load()- assert mgr3.get_user_group_ids(acct, "bob") == ()- assert mgr3.get_group_members(acct, group_id) == []---async def test_legacy_account_without_settings_loads_without_namespace_settings(manager_service):- """Legacy accounts no longer create account settings during load."""- acct = _uid()- created_at = "2026-04-16T00:00:00+00:00"-- seed_mgr = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)- await seed_mgr._write_json(- "/local/_system/accounts.json", {"accounts": {acct: {"created_at": created_at}}}- )- await seed_mgr._write_json(- f"/local/{acct}/_system/users.json",- {"users": {"alice": {"role": "admin", "key": "legacy-key-alice"}}},- )-- mgr = APIKeyManager(- root_key=ROOT_KEY,- viking_fs=manager_service.viking_fs,- )- await mgr.load()-- identity = mgr.resolve("legacy-key-alice")- assert identity.account_id == acct- assert identity.user_id == "alice"-- settings = await mgr._read_json(f"/local/{acct}/_system/setting.json")- assert settings is None---# ---- Argon2id hashing tests -------async def test_create_account_with_argon2id_hashing_enabled(manager_service):- """create_account with api_key_hashing_enabled=True should create hashed keys."""- acct = _uid()- mgr = APIKeyManager(- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=True- )- await mgr.load()-- key = await mgr.create_account(acct, "alice")- stored_hash = _get_stored_hash(mgr, acct, "alice")-- _print_api_key_info("创建账号", acct, "alice", key, stored_hash)-- assert isinstance(key, str)- assert key.count(".") == 2 # New format has two dots- _assert_argon2_hash(stored_hash)-- identity = mgr.resolve(key)- assert identity.role == Role.ADMIN- assert identity.account_id == acct- assert identity.user_id == "alice"---async def test_register_user_with_argon2id_hashing_enabled(manager_service):- """register_user with api_key_hashing_enabled=True should create hashed keys."""- acct = _uid()- mgr = APIKeyManager(- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=True- )- await mgr.load()-- await mgr.create_account(acct, "alice")- key = await mgr.register_user(acct, "bob", "user")- stored_hash = _get_stored_hash(mgr, acct, "bob")-- _print_api_key_info("注册用户", acct, "bob", key, stored_hash, role="user")- _assert_argon2_hash(stored_hash)-- identity = mgr.resolve(key)- assert identity.role == Role.USER- assert identity.account_id == acct- assert identity.user_id == "bob"---async def test_regenerate_key_with_argon2id_hashing_enabled(manager_service):- """regenerate_key with api_key_hashing_enabled=True should create new hashed key."""- acct = _uid()- mgr = APIKeyManager(- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=True- )- await mgr.load()-- await mgr.create_account(acct, "alice")- old_key = await mgr.register_user(acct, "bob", "user")- old_stored_hash = _get_stored_hash(mgr, acct, "bob")-- new_key = await mgr.regenerate_key(acct, "bob")- new_stored_hash = _get_stored_hash(mgr, acct, "bob")-- _print_key_regeneration_info(- "重新生成密钥", acct, "bob", old_key, old_stored_hash, new_key, new_stored_hash- )-- assert new_key != old_key- assert new_stored_hash != old_stored_hash- _assert_argon2_hash(new_stored_hash)-- # Old key invalid- with pytest.raises(UnauthenticatedError):- mgr.resolve(old_key)-- # New key valid- identity = mgr.resolve(new_key)- assert identity.user_id == "bob"- assert identity.account_id == acct---async def test_migrate_plaintext_keys_to_argon2id_hashing(manager_service):- """Keys created with api_key_hashing disabled should be migrated when api_key_hashing is enabled."""- acct = _uid()-- # First, create a key with api_key_hashing disabled- mgr1 = APIKeyManager(- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=False- )- await mgr1.load()- key = await mgr1.create_account(acct, "alice")-- # Now, reload with api_key_hashing enabled - should migrate the key- mgr2 = APIKeyManager(- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=True- )- await mgr2.load()-- # Key should still work- identity = mgr2.resolve(key)- assert identity.account_id == acct- assert identity.user_id == "alice"---async def test_persistence_with_argon2id_hashing_enabled(manager_service):- """Hashed keys should survive manager reload from AGFS."""- mgr1 = APIKeyManager(- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=True- )- await mgr1.load()-- acct = _uid()- key = await mgr1.create_account(acct, "alice")- stored_hash1 = _get_stored_hash(mgr1, acct, "alice")-- _print_api_key_info("持久化验证", acct, "alice", key, stored_hash1)- print("正在重新加载管理器...\n")-- # Create new manager instance and reload- mgr2 = APIKeyManager(- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=True- )- await mgr2.load()-- stored_hash2 = _get_stored_hash(mgr2, acct, "alice")-- print(f"\n{'=' * 80}")- print("[持久化验证 - 重新加载后]")- print(f"重新加载后存储的 Argon2id 哈希值: {stored_hash2}")- print(f"哈希值一致: {stored_hash1 == stored_hash2}")- print(f"{'=' * 80}\n")-- assert stored_hash1 == stored_hash2- _assert_argon2_hash(stored_hash2)-- identity = mgr2.resolve(key)- assert identity.account_id == acct- assert identity.user_id == "alice"- assert identity.role == Role.ADMIN---def _print_api_key_info(- test_name: str,- account_id: str,- user_id: str,- original_key: str,- stored_hash: str,- role: str = None,-) -> None:- """打印 API Key 相关信息的辅助函数。"""- print(f"\n{'=' * 80}")- print(f"[加密测试 - {test_name}]")- print(f"账号ID: {account_id}")- print(f"用户名: {user_id}")- if role:- print(f"角色: {role}")- print(f"原始 API Key (返回给用户): {original_key}")- print(f"存储的 Argon2id 哈希值: {stored_hash}")- print(f"原始 Key 长度: {len(original_key)}")- print(f"哈希值长度: {len(stored_hash)}")- print(f"{'=' * 80}\n")---def _print_key_regeneration_info(- test_name: str,- account_id: str,- user_id: str,- old_key: str,- old_hash: str,- new_key: str,- new_hash: str,-) -> None:- """打印密钥重新生成信息的辅助函数。"""- print(f"\n{'=' * 80}")- print(f"[加密测试 - {test_name}]")- print(f"账号ID: {account_id}")- print(f"用户名: {user_id}")- print(f"旧原始 API Key: {old_key}")- print(f"旧存储的 Argon2id 哈希值: {old_hash}")- print(f"新原始 API Key: {new_key}")- print(f"新存储的 Argon2id 哈希值: {new_hash}")- print(f"密钥已更换: {new_key != old_key}")- print(f"哈希已更换: {new_hash != old_hash}")- print(f"{'=' * 80}\n")---def _assert_argon2_hash(stored_hash: str) -> None:- """验证存储的哈希值是有效的 Argon2id 格式。"""- assert stored_hash.startswith("$argon2"), "哈希值必须是 Argon2id 格式"---def _get_stored_hash(mgr: APIKeyManager, account_id: str, user_id: str) -> str:- """从管理器中获取用户存储的哈希值。"""- account_info = mgr._accounts.get(account_id)- assert account_info is not None, f"账号 {account_id} 不存在"- assert user_id in account_info.users, f"用户 {user_id} 不存在"- return account_info.users[user_id]["key"]+ assert await mgr3.get_user_group_ids(acct, "bob") == ()+ assert await mgr3.get_group_members(acct, group_id) == []# ---- New format API Key tests -----async def test_new_format_key_generation(manager: APIKeyManager):- """Test that new keys are generated in the new format with three segments."""- from openviking.server.api_keys import is_new_format_key, parse_api_key-- acct = _uid()- key = await manager.create_account(acct, "alice")-- # Verify new format- assert is_new_format_key(key)- assert key.count(".") == 2-- # Verify we can parse identity directly from the key- account_id, user_id, secret = parse_api_key(key)- assert account_id == acct- assert user_id == "alice"- assert len(secret) > 0---async def test_new_format_key_resolve_fast_path(manager: APIKeyManager):- """Test that new format keys use the fast decode path without prefix lookup."""- acct = _uid()- key = await manager.create_account(acct, "alice")-- # Resolve should work and return correct identity- identity = manager.resolve(key)- assert identity.role == Role.ADMIN- assert identity.account_id == acct- assert identity.user_id == "alice"---async def test_register_user_generates_new_format(manager: APIKeyManager):- """Test that register_user generates keys in new format."""- from openviking.server.api_keys import is_new_format_key-- acct = _uid()- await manager.create_account(acct, "alice")- key = await manager.register_user(acct, "bob", "user")-- assert is_new_format_key(key)- identity = manager.resolve(key)- assert identity.role == Role.USER- assert identity.account_id == acct- assert identity.user_id == "bob"--async def test_seeded_new_format_keys_are_predictable(manager: APIKeyManager):from openviking.server.api_keys import parse_api_key@@ -1334,8 +706,8 @@ async def test_seeded_register_and_regenerate_key(manager: APIKeyManager):assert new_key != old_keywith pytest.raises(UnauthenticatedError):- manager.resolve(old_key)- assert manager.resolve(new_key).user_id == "bob"+ await manager.resolve_identity(old_key)+ assert (await manager.resolve_identity(new_key)).user_id == "bob"async def test_seed_must_not_be_empty(manager: APIKeyManager):@@ -1344,153 +716,6 @@ async def test_seed_must_not_be_empty(manager: APIKeyManager):await manager.create_account(acct, "alice", seed="")-async def test_seeded_key_with_hashing_enabled(manager_service):- from openviking.server.api_keys import parse_api_key-- acct = _uid()- mgr = APIKeyManager(- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=True- )- await mgr.load()-- key = await mgr.create_account(acct, "alice", seed="seeded-secret")- _, _, secret = parse_api_key(key)- assert secret == _seed_secret("alice", "seeded-secret")-- stored_hash = _get_stored_hash(mgr, acct, "alice")- _assert_argon2_hash(stored_hash)- assert stored_hash != key- assert mgr.resolve(key).user_id == "alice"---async def test_regenerate_key_upgrades_to_new_format(manager_service):- """Test that regenerate_key upgrades legacy keys to new format."""- from openviking.server.api_keys import LegacyAPIKeyManager, is_new_format_key-- acct = _uid()-- # First create a legacy key using LegacyAPIKeyManager- legacy_mgr = LegacyAPIKeyManager(- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=False- )- await legacy_mgr.load()- legacy_key = await legacy_mgr.create_account(acct, "alice")- assert not is_new_format_key(legacy_key)- assert len(legacy_key) == 64-- # Now load with NewAPIKeyManager and regenerate- new_mgr = APIKeyManager(- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=False- )- await new_mgr.load()-- # Legacy key should still work- identity = new_mgr.resolve(legacy_key)- assert identity.user_id == "alice"-- # Regenerate should give a new format key- new_key = await new_mgr.regenerate_key(acct, "alice")- assert is_new_format_key(new_key)- assert new_key != legacy_key-- # Old key should no longer work- from openviking_cli.exceptions import UnauthenticatedError-- with pytest.raises(UnauthenticatedError):- new_mgr.resolve(legacy_key)-- # New key should work- identity2 = new_mgr.resolve(new_key)- assert identity2.user_id == "alice"- assert identity2.account_id == acct---async def test_mixed_key_formats(manager_service):- """Test that both legacy and new format keys can coexist."""- from openviking.server.api_keys import APIKeyManager, LegacyAPIKeyManager, is_new_format_key-- acct = _uid()-- # Create account with legacy manager- legacy_mgr = LegacyAPIKeyManager(- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=False- )- await legacy_mgr.load()- legacy_key = await legacy_mgr.create_account(acct, "alice")- assert not is_new_format_key(legacy_key)-- # Add another user with new format using NewAPIKeyManager- new_mgr = APIKeyManager(- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=False- )- await new_mgr.load()- new_key = await new_mgr.register_user(acct, "bob", "user")- assert is_new_format_key(new_key)-- # Both keys should work- identity1 = new_mgr.resolve(legacy_key)- assert identity1.user_id == "alice"-- identity2 = new_mgr.resolve(new_key)- assert identity2.user_id == "bob"---async def test_new_format_with_encryption(manager_service):- """Test new format key generation and verification with encryption enabled."""- from openviking.server.api_keys import is_new_format_key-- acct = _uid()- mgr = APIKeyManager(- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=True- )- await mgr.load()-- key = await mgr.create_account(acct, "alice")- assert is_new_format_key(key)-- stored_hash = _get_stored_hash(mgr, acct, "alice")- _assert_argon2_hash(stored_hash)-- # Key should still resolve correctly- identity = mgr.resolve(key)- assert identity.user_id == "alice"- assert identity.account_id == acct---async def test_parse_api_key_edge_cases():- """Test parse_api_key with various edge cases."""- # Test with simple ASCII values- # First generate some test keys using the utility functions- from openviking.server.api_keys import generate_api_key, is_new_format_key, parse_api_key-- key = generate_api_key("test-account", "test-user")- assert is_new_format_key(key)-- account_id, user_id, secret = parse_api_key(key)- assert account_id == "test-account"- assert user_id == "test-user"- assert len(secret) == 64 # 32 bytes as hex---async def test_encode_decode_roundtrip():- """Test that encode and decode operations are inverses."""- from openviking.server.api_keys.new import _decode_segment, _encode_segment-- test_cases = [- "simple",- "with-hyphens",- "with_underscores",- "with@special!chars",- "acme_12345678", # Typical account format from _uid()- "[email protected]",- ]-- for test_str in test_cases:- encoded = _encode_segment(test_str)- decoded = _decode_segment(encoded)- assert decoded == test_str, f"Failed for: {test_str}"--async def test_is_new_format_key_validation():"""Test is_new_format_key correctly identifies key format."""from openviking.server.api_keys import generate_api_key, is_new_format_key@@ -1511,113 +736,89 @@ async def test_is_new_format_key_validation():assert not is_new_format_key("too.many.parts.here")-# ---- get_user_role / legacy public API parity ----+# ---- Registered user role -----async def test_get_user_role_returns_admin_for_account_admin(manager: APIKeyManager):- """get_user_role must return ADMIN for the account's first admin user.-- Trusted mode (openviking/server/auth.py) calls this method to resolve the- effective role when X-OpenViking-Account / X-OpenViking-User headers are- present. Must not raise AttributeError on the default APIKeyManager.- """+async def test_get_registered_user_role_returns_none_when_user_missing(manager: APIKeyManager):acct = _uid()await manager.create_account(acct, "admin_user")- assert manager.get_user_role(acct, "admin_user") == Role.ADMIN-+ assert await manager.get_registered_user_role(acct, "nobody") is None+ assert await manager.get_registered_user_role("no_such_account", "no_such_user") is None-async def test_get_user_role_returns_user_for_registered_user(manager: APIKeyManager):- acct = _uid()- await manager.create_account(acct, "admin_user")- await manager.register_user(acct, "regular_user", "user")- assert manager.get_user_role(acct, "regular_user") == Role.USER--async def test_get_user_role_defaults_to_user_when_user_missing(manager: APIKeyManager):- """Missing user should default to Role.USER, matching legacy behavior."""- acct = _uid()- await manager.create_account(acct, "admin_user")- assert manager.get_user_role(acct, "nobody") == Role.USER+# ---- Read-replica refresh contract -----async def test_get_user_role_defaults_to_user_when_account_missing(manager: APIKeyManager):- """Missing account should default to Role.USER, matching legacy behavior."""- assert manager.get_user_role("no_such_account", "no_such_user") == Role.USER---def test_new_api_key_manager_public_api_parity_with_legacy():- """NewAPIKeyManager must expose every public method LegacyAPIKeyManager does.-- PR #1686 wrapped LegacyAPIKeyManager in a NewAPIKeyManager that forwards- methods by hand rather than inheriting. A missing proxy (e.g. get_user_role)- becomes a latent AttributeError at runtime. This test enforces parity on the- public surface so future wrappers can't silently regress the contract.- """- from openviking.server.api_keys.legacy import LegacyAPIKeyManager- from openviking.server.api_keys.new import NewAPIKeyManager-- def _public_methods(cls) -> set:- return {- name for name in dir(cls) if not name.startswith("_") and callable(getattr(cls, name))- }-- legacy_public = _public_methods(LegacyAPIKeyManager)- new_public = _public_methods(NewAPIKeyManager)- missing = legacy_public - new_public- assert not missing, (- f"NewAPIKeyManager is missing public methods present on "- f"LegacyAPIKeyManager: {sorted(missing)}"+async def test_explicit_fresh_list_bypasses_watcher_interval(manager_service):+ writer = build_api_key_manager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+ reader = build_api_key_manager(+ root_key=ROOT_KEY,+ viking_fs=manager_service.viking_fs,+ account_store_watch_enabled=True,+ account_store_watch_interval_seconds=300,)+ await writer.load()+ await reader.load()+ acct = _uid()+ try:+ await writer.create_account(acct, "alice")+ await writer.register_user(acct, "bob")+ page = await reader.list_users_page(acct, limit=None, fresh=True)-# ---- Read-only reload / change-signature tests -----#-# Read replicas load the key store once at startup and never rewrite it. A user-# registered / rotated / removed on the writer is therefore invisible to a-# reader until it refreshes its in-memory index. reload() + compute_store_-# signature() give the optional background watcher a read-only way to converge.-+ assert {user["user_id"] for user in page["users"]} == {"alice", "bob"}+ finally:+ await reader.close()+ await writer.close()-async def test_reload_picks_up_user_registered_by_writer(manager_service):- """A reader's reload() should see a user the writer registered afterwards.- This reproduces the read-replica auth failure: two managers over the same- store, a user created via the "writer", initially rejected by the "reader",- then accepted after reload().- """- writer = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+async def test_watched_reader_accepts_user_registered_by_writer(manager_service):+ writer = build_api_key_manager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)await writer.load()- reader = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)- await reader.load()-acct = _uid()await writer.create_account(acct, "alice")+ reader = build_api_key_manager(+ root_key=ROOT_KEY,+ viking_fs=manager_service.viking_fs,+ account_store_watch_enabled=True,+ account_store_watch_interval_seconds=0.01,+ )+ await reader.load()+ await asyncio.sleep(0.03)user_key = await writer.register_user(acct, "bob")- # Reader has not refreshed yet: the new user's key is unknown.- with pytest.raises(UnauthenticatedError):- reader.resolve(user_key)-- await reader.reload()-- identity = reader.resolve(user_key)- assert identity.account_id == acct- assert identity.user_id == "bob"---async def test_reload_reflects_removed_user(manager_service):- """reload() should drop a user the writer removed after the reader loaded."""- writer = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+ try:+ for _ in range(100):+ try:+ identity = await reader.resolve_identity(user_key)+ break+ except UnauthenticatedError:+ await asyncio.sleep(0.01)+ else:+ pytest.fail("watched reader did not observe the registered user")+ assert (identity.account_id, identity.user_id) == (acct, "bob")+ finally:+ await reader.close()+ await writer.close()+++async def test_watched_reader_rejects_user_removed_by_writer(manager_service):+ writer = build_api_key_manager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)await writer.load()acct = _uid()await writer.create_account(acct, "alice")user_key = await writer.register_user(acct, "bob")- reader = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+ reader = build_api_key_manager(+ root_key=ROOT_KEY,+ viking_fs=manager_service.viking_fs,+ account_store_watch_enabled=True,+ account_store_watch_interval_seconds=0.01,+ )await reader.load()- # Reader accepts bob at first.- assert reader.resolve(user_key).user_id == "bob"+ assert (await reader.resolve_identity(user_key)).user_id == "bob"+ await asyncio.sleep(0.03)await writer.begin_deletion(acct,@@ -1627,129 +828,15 @@ async def test_reload_reflects_removed_user(manager_service):owner_user_id="alice",)await writer.finish_deletion(acct, "bob", "delete-1")- await reader.reload()-- with pytest.raises(UnauthenticatedError):- reader.resolve(user_key)---async def test_reload_does_not_write_to_store(manager_service, monkeypatch):- """reload() must never persist: read replicas mount a read-only volume."""- writer = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)- await writer.load()- acct = _uid()- await writer.create_account(acct, "alice")-- reader = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)- await reader.load()-- async def _fail_write_json(*args, **kwargs):- raise AssertionError("reload() must not write to the key store")-- monkeypatch.setattr(reader._legacy, "_write_json", _fail_write_json)- monkeypatch.setattr(reader._legacy, "_save_accounts_json", _fail_write_json)- monkeypatch.setattr(reader._legacy, "_save_users_json", _fail_write_json)-- # Must not raise: no write path should be exercised.- await reader.reload()---async def test_reload_with_hashing_enabled_does_not_migrate(manager_service, monkeypatch):- """reload() with hashing on must index plaintext keys without migrating them.-- load() migrates plaintext -> Argon2id (a write); reload() is read-only and- must skip that migration while still resolving the plaintext key.- """- acct = _uid()- seed_mgr = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)- await seed_mgr._write_json(- ACCOUNTS_PATH, {"accounts": {acct: {"created_at": "2026-04-16T00:00:00+00:00"}}}- )- await seed_mgr._write_json(- f"/local/{acct}/_system/users.json",- {"users": {"alice": {"role": "admin", "key": "legacy-plaintext-key-alice"}}},- )-- reader = APIKeyManager(- root_key=ROOT_KEY,- viking_fs=manager_service.viking_fs,- api_key_hashing_enabled=True,- )-- async def _fail_write_json(*args, **kwargs):- raise AssertionError("reload() must not migrate plaintext keys")-- monkeypatch.setattr(reader._legacy, "_write_json", _fail_write_json)- monkeypatch.setattr(reader._legacy, "_save_users_json", _fail_write_json)-- await reader.reload()-- identity = reader.resolve("legacy-plaintext-key-alice")- assert identity.account_id == acct- assert identity.user_id == "alice"---async def test_reload_tolerates_uninitialized_store(manager_service):- """reload() before the store exists must keep current state, not wipe it."""- reader = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)- # Deliberately skip load(): accounts.json does not exist yet (reader started- # before the writer bootstrapped the store).- await reader.reload()- # Root key still resolves; no crash from a missing store.- assert reader.resolve(ROOT_KEY).role == Role.ROOT---async def test_store_signature_changes_on_user_registration(manager_service):- """The change signature must move when users.json changes (not just accounts)."""- writer = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)- await writer.load()- acct = _uid()- await writer.create_account(acct, "alice")-- before = await writer.compute_store_signature()- await writer.register_user(acct, "bob")- after = await writer.compute_store_signature()-- assert before != after---async def test_store_signature_stable_without_changes(manager_service):- """Two consecutive signatures with no store change must be equal.-- This is what lets the watcher skip a full reload on an unchanged store.- """- writer = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)- await writer.load()- acct = _uid()- await writer.create_account(acct, "alice")-- first = await writer.compute_store_signature()- second = await writer.compute_store_signature()- assert first == second---async def test_store_signature_stats_bypass_cache(manager_service, monkeypatch):- """Signature stats must bypass plugin-local caches so S3 metadata stays fresh.-- Without bypass_cache the S3FS sliding-TTL stat cache pins stale (size, modTime)- and the watcher never observes writer-side changes.- """- writer = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)- await writer.load()- acct = _uid()- await writer.create_account(acct, "alice")-- real_stat = writer._legacy._async_agfs.stat- seen_bypass: list = []-- async def _spy_stat(path, *, fs_ctx=None, bypass_cache=False):- seen_bypass.append(bypass_cache)- return await real_stat(path, fs_ctx=fs_ctx, bypass_cache=bypass_cache)-- monkeypatch.setattr(writer._legacy._async_agfs, "stat", _spy_stat)-- await writer.compute_store_signature()-- # accounts.json + one users.json were stat'd, all with bypass_cache=True.- assert seen_bypass- assert all(seen_bypass)+ try:+ for _ in range(100):+ try:+ await reader.resolve_identity(user_key)+ except UnauthenticatedError:+ break+ await asyncio.sleep(0.01)+ else:+ pytest.fail("watched reader did not observe the removed user")+ finally:+ await reader.close()+ await writer.close()diff --git a/tests/server/test_auth.py b/tests/server/test_auth.pyindex f0376244f..06c941a65 100644--- a/tests/server/test_auth.py+++ b/tests/server/test_auth.py@@ -3,7 +3,6 @@"""Tests for multi-tenant authentication (openviking/server/auth.py)."""-import asyncioimport uuidimport httpx@@ -14,6 +13,7 @@ from fastapi import Request as FastAPIRequestfrom fastapi.responses import JSONResponsefrom starlette.requests import Request+from openviking.server.api_keys import APIKeyManagerfrom openviking.server.app import create_appfrom openviking.server.auth import get_request_context, resolve_identityfrom openviking.server.auth.registry import get_registry@@ -21,6 +21,7 @@ from openviking.server.config import ServerConfig, _is_localhost, validate_servefrom openviking.server.dependencies import set_servicefrom openviking.server.identity import ResolvedIdentity, Rolefrom openviking.server.models import ERROR_CODE_TO_HTTP_STATUS, ErrorInfo, Response+from openviking.server.store_assembly import build_api_key_managerfrom openviking.service.core import OpenVikingServicefrom openviking.service.task_store import PersistentTaskStorefrom openviking.service.task_tracker import (@@ -92,22 +93,28 @@ def _make_request(# Ensure built-in plugins are registeredimport openviking.server.auth.plugins # noqa: F401+ if auth_mode == "trusted" and root_api_key is None:+ root_api_key = ROOT_KEY+ request_headers = dict(headers or {})+ if auth_mode == "trusted":+ request_headers.setdefault("X-API-Key", ROOT_KEY)+raw_headers = []- for key, value in (headers or {}).items():+ for key, value in request_headers.items():raw_headers.append((key.lower().encode("latin-1"), value.encode("latin-1")))app = FastAPI()# When auth is disabled and mode is the default api_key, fall back to dev modeeffective_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()+ app.state.api_key_manager = (+ api_key_manager if auth_enabled and api_key_manager is not None else None+ )# Set auth plugin based on moderegistry = get_registry()plugin_cls = registry.get(effective_auth_mode)if plugin_cls is not None:app.state.auth_plugin = plugin_cls()- if effective_auth_mode == "trusted" and api_key_manager is not None:+ if effective_auth_mode == "trusted":app.state.auth_plugin._api_key_manager = api_key_managerscope = {"type": "http",@@ -133,13 +140,14 @@ def _build_auth_http_test_app(# Ensure built-in plugins are registeredimport openviking.server.auth.plugins # noqa: F401+ if auth_mode == "trusted" and root_api_key is None:+ root_api_key = ROOT_KEY+app = FastAPI()# When auth is disabled and mode is the default api_key, fall back to dev modeeffective_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()+ app.state.api_key_manager = object() if auth_enabled else None# Set auth plugin based on moderegistry = get_registry()plugin_cls = registry.get(effective_auth_mode)@@ -235,8 +243,7 @@ async def auth_service(temp_dir):@pytest_asyncio.fixture(scope="function")async def auth_app(auth_service):- """App with root_api_key configured and APIKeyManager loaded."""- from openviking.server.api_keys import APIKeyManager+ """App with root_api_key configured and identity services initialized."""from openviking.server.auth.plugins import ApiKeyAuthPluginfrom openviking.server.auth.registry import get_registry@@ -244,8 +251,7 @@ async def auth_app(auth_service):app = create_app(config=config, service=auth_service)set_service(auth_service)- # Manually initialize APIKeyManager (lifespan not triggered in ASGI tests)- manager = APIKeyManager(root_key=ROOT_KEY, viking_fs=auth_service.viking_fs)+ manager = build_api_key_manager(ROOT_KEY, auth_service.viking_fs)await manager.load()app.state.api_key_manager = manager@@ -257,7 +263,20 @@ async def auth_app(auth_service):plugin = plugin_cls()app.state.auth_plugin = plugin- return app+ yield app+ await manager.close()+++async def _stored_users(service, account_id):+ manager = build_api_key_manager(ROOT_KEY, service.viking_fs)+ await manager.load()+ try:+ if await manager.get_account(account_id) is None:+ return []+ page = await manager.list_users_page(account_id, expose_key=True)+ return page["users"]+ finally:+ await manager.close()@pytest_asyncio.fixture(scope="function")@@ -501,98 +520,33 @@ async def test_user_key_cannot_access_admin_api(auth_client: httpx.AsyncClient,assert resp.status_code == 403-async def test_admin_key_cannot_switch_effective_user_within_account(auth_app):- """ADMIN API keys cannot assert a different data-plane user in api_key mode."""[email protected]("role", [Role.ADMIN, Role.USER])+async def test_api_key_identity_cannot_be_overridden(auth_app, role):manager = auth_app.state.api_key_manageraccount_id = _uid()admin_key = await manager.create_account(account_id, "admin_user")- await manager.register_user(account_id, "alice")-- request = _make_request(- "/api/v1/resources",- headers={- "X-API-Key": admin_key,- "X-OpenViking-Account": account_id,- "X-OpenViking-User": "alice",- },- auth_enabled=True,- api_key_manager=manager,- )-- with pytest.raises(PermissionDeniedError, match="X-OpenViking-Account"):- await resolve_identity(- request,- x_api_key=admin_key,- x_openviking_account=account_id,- x_openviking_user="alice",+ user_key = await manager.register_user(account_id, "alice")+ key, owner = (admin_key, "admin_user") if role == Role.ADMIN else (user_key, "alice")+ for overrides in (+ {},+ {"X-OpenViking-Account": "other-account"},+ {"X-OpenViking-Account": account_id, "X-OpenViking-User": "bob"},+ ):+ request = _make_request(+ "/api/v1/resources",+ headers={"X-API-Key": key, **overrides},+ auth_enabled=True,+ api_key_manager=manager,)---async def test_admin_key_cannot_switch_account_via_header(auth_app):- """ADMIN keys must stay inside their own account."""- manager = auth_app.state.api_key_manager- account_id = _uid()- admin_key = await manager.create_account(account_id, "admin_user")-- request = _make_request(- "/api/v1/resources",- headers={- "X-API-Key": admin_key,- "X-OpenViking-Account": "other-account",- },- auth_enabled=True,- api_key_manager=manager,- )-- with pytest.raises(PermissionDeniedError, match="X-OpenViking-Account"):- await resolve_identity(+ identity = await resolve_identity(request,- x_api_key=admin_key,- x_openviking_account="other-account",- )---async def test_user_key_resolves_to_key_user_and_cannot_switch_user(auth_app):- """USER keys resolve to their owner and may not impersonate another user."""- manager = auth_app.state.api_key_manager- account_id = _uid()- await manager.create_account(account_id, "admin_user")- user_key = await manager.register_user(account_id, "alice")-- request = _make_request(- "/api/v1/resources",- headers={- "X-API-Key": user_key,- },- auth_enabled=True,- api_key_manager=manager,- )-- identity = await resolve_identity(- request,- x_api_key=user_key,- )-- assert identity.role == Role.USER- assert identity.account_id == account_id- assert identity.user_id == "alice"-- forbidden_request = _make_request(- "/api/v1/resources",- headers={- "X-API-Key": user_key,- "X-OpenViking-User": "bob",- },- auth_enabled=True,- api_key_manager=manager,- )-- with pytest.raises(PermissionDeniedError, match="X-OpenViking-User"):- await resolve_identity(- forbidden_request,- x_api_key=user_key,- x_openviking_user="bob",+ x_api_key=key,+ x_openviking_account=overrides.get("X-OpenViking-Account"),+ x_openviking_user=overrides.get("X-OpenViking-User"),)+ assert (identity.account_id, identity.user_id, identity.role) == (account_id, owner, role)+ assert "x-openviking-account" not in request.headers+ assert "x-openviking-user" not in request.headersasync def test_cross_tenant_session_get_returns_not_found(auth_client: httpx.AsyncClient, auth_app):@@ -915,6 +869,29 @@ async def test_dev_mode_root_tenant_scoped_requests_keep_200_via_http():assert response.json()["status"] == "ok"+async def test_trusted_mode_allows_header_identity_without_api_key():+ """Trusted mode should accept explicit tenant headers without API key."""+ request = _make_request(+ "/api/v1/resources",+ headers={+ "X-OpenViking-Account": "acme",+ "X-OpenViking-User": "alice",+ },+ auth_enabled=False,+ auth_mode="trusted",+ )++ identity = await resolve_identity(+ request,+ x_openviking_account="acme",+ x_openviking_user="alice",+ )++ assert identity.role == Role.USER+ assert identity.account_id == "acme"+ assert identity.user_id == "alice"++async def test_trusted_mode_defaults_role_to_user():"""Trusted mode should default requests to USER when no explicit role header is sent."""request = _make_request(@@ -925,12 +902,10 @@ async def test_trusted_mode_defaults_role_to_user():},auth_enabled=False,auth_mode="trusted",- root_api_key=ROOT_KEY,)identity = await resolve_identity(request,- x_api_key=ROOT_KEY,x_openviking_account="acme",x_openviking_user="alice",)@@ -953,13 +928,11 @@ async def test_trusted_mode_looks_up_role_from_api_key_manager(auth_app):},auth_enabled=True,auth_mode="trusted",- root_api_key=ROOT_KEY,api_key_manager=manager,)identity = await resolve_identity(request,- x_api_key=ROOT_KEY,x_openviking_account=account_id,x_openviking_user="admin_user",)@@ -977,13 +950,11 @@ async def test_trusted_mode_looks_up_role_from_api_key_manager(auth_app):},auth_enabled=True,auth_mode="trusted",- root_api_key=ROOT_KEY,api_key_manager=manager,)identity = await resolve_identity(request,- x_api_key=ROOT_KEY,x_openviking_account=account_id,x_openviking_user="regular_user",)@@ -1007,13 +978,11 @@ async def test_trusted_mode_defaults_to_user_when_user_not_found(auth_app):},auth_enabled=True,auth_mode="trusted",- root_api_key=ROOT_KEY,api_key_manager=manager,)identity = await resolve_identity(request,- x_api_key=ROOT_KEY,x_openviking_account=account_id,x_openviking_user="nonexistent_user",)@@ -1036,13 +1005,11 @@ async def test_trusted_mode_defaults_to_user_when_account_not_found(auth_app):},auth_enabled=False,auth_mode="trusted",- root_api_key=ROOT_KEY,api_key_manager=manager,)identity = await resolve_identity(request,- x_api_key=ROOT_KEY,x_openviking_account=account_id,x_openviking_user="some_user",)@@ -1053,7 +1020,7 @@ async def test_trusted_mode_defaults_to_user_when_account_not_found(auth_app):async def test_trusted_identity_registration_batches_data_plane_identity(auth_service):- """Enabled trusted registration queues every data-plane identity until flush."""+ """Registration is delayed until flush and remains idempotent after restart."""from openviking.server.auth.plugins import TrustedAuthPluginconfig = ServerConfig(@@ -1061,41 +1028,31 @@ async def test_trusted_identity_registration_batches_data_plane_identity(auth_seroot_api_key=ROOT_KEY,trusted_identity_flush_interval_seconds=300,)- app = FastAPI()- app.state.config = config- plugin = TrustedAuthPlugin()- await plugin.initialize(app, auth_service, config)- try:- request = _make_request(- "/api/v1/resources",- headers={- "X-OpenViking-Account": "acme",- "X-OpenViking-User": "alice",- },- auth_enabled=False,- auth_mode="trusted",- root_api_key=ROOT_KEY,- )- request.app.state.config = config- request.app.state.api_key_manager = app.state.api_key_manager-- identity = await plugin.resolve_identity(- request,- api_key=ROOT_KEY,- x_openviking_account="acme",- x_openviking_user="alice",- )- assert identity.account_id == "acme"- assert identity.user_id == "alice"- assert plugin._api_key_manager.has_user("acme", "alice") is False-- await plugin.flush_trusted_identities()-- assert plugin._api_key_manager.get_users("acme", expose_key=True) == [- {"user_id": "alice", "role": "user"}- ]- finally:- await plugin.shutdown()+ for restarted in (False, True):+ app = FastAPI()+ app.state.config = config+ plugin = TrustedAuthPlugin()+ await plugin.initialize(app, auth_service, config)+ try:+ request = _make_request("/api/v1/resources", auth_enabled=False, auth_mode="trusted")+ request.app.state.config = config+ request.app.state.api_key_manager = app.state.api_key_manager+ identity = await plugin.resolve_identity(+ request, x_openviking_account="acme", x_openviking_user="alice"+ )+ assert (identity.account_id, identity.user_id, identity.role) == (+ "acme",+ "alice",+ Role.USER,+ )+ if not restarted:+ assert await _stored_users(auth_service, "acme") == []+ await plugin.flush_trusted_identities()+ assert await _stored_users(auth_service, "acme") == [+ {"user_id": "alice", "role": "user"}+ ]+ finally:+ await plugin.shutdown()async def test_invalid_trusted_identity_does_not_block_later_registration(@@ -1122,20 +1079,16 @@ async def test_invalid_trusted_identity_does_not_block_later_registration(},auth_enabled=False,auth_mode="trusted",- root_api_key=ROOT_KEY,)request.app.state.config = configwith pytest.raises(InvalidArgumentError, match="user_id"):await plugin.resolve_identity(request,- api_key=ROOT_KEY,x_openviking_account="acme",x_openviking_user="invalid/user",)- assert plugin._pending == {}-valid_request = _make_request("/api/v1/resources",headers={@@ -1144,133 +1097,60 @@ async def test_invalid_trusted_identity_does_not_block_later_registration(},auth_enabled=False,auth_mode="trusted",- root_api_key=ROOT_KEY,)valid_request.app.state.config = configawait plugin.resolve_identity(valid_request,- api_key=ROOT_KEY,x_openviking_account="good-account",x_openviking_user="alice",)await plugin.flush_trusted_identities()- assert plugin._api_key_manager.has_user("good-account", "alice")+ assert await _stored_users(auth_service, "good-account") == [+ {"user_id": "alice", "role": "user"}+ ]finally:await plugin.shutdown()-async def test_trusted_identity_registration_skips_identity_loaded_from_registry(auth_service):- """A restarted plugin must not queue an identity already loaded from storage."""- from openviking.server.auth.plugins import TrustedAuthPlugin-- config = ServerConfig(auth_mode="trusted", root_api_key=ROOT_KEY)- app = FastAPI()- app.state.config = config- first_plugin = TrustedAuthPlugin()- await first_plugin.initialize(app, auth_service, config)- try:- await first_plugin._api_key_manager.ensure_trusted_identities({"acme": {"alice"}})- finally:- await first_plugin.shutdown()-- restarted_app = FastAPI()- restarted_app.state.config = config- restarted_plugin = TrustedAuthPlugin()- await restarted_plugin.initialize(restarted_app, auth_service, config)- try:- request = _make_request(- "/api/v1/resources",- headers={- "X-OpenViking-Account": "acme",- "X-OpenViking-User": "alice",- },- auth_enabled=False,- auth_mode="trusted",- root_api_key=ROOT_KEY,- )- request.app.state.config = config-- await restarted_plugin.resolve_identity(- request, api_key=ROOT_KEY, x_openviking_account="acme", x_openviking_user="alice"- )-- assert restarted_plugin._pending == {}- finally:- await restarted_plugin.shutdown()---async def test_disabled_trusted_identity_registration_and_admin_paths_do_not_enqueue(auth_service):+ "interval,path",+ [(0, "/api/v1/resources"), (0, "/api/v1/admin/accounts"), (300, "/api/v1/admin/accounts")],+)+async def test_trusted_registration_respects_configuration_and_route(auth_service, interval, path):"""A zero interval disables registration, and Admin paths never register."""from openviking.server.auth.plugins import TrustedAuthPluginconfig = ServerConfig(- auth_mode="trusted", root_api_key=ROOT_KEY, trusted_identity_flush_interval_seconds=0+ auth_mode="trusted",+ root_api_key=ROOT_KEY,+ trusted_identity_flush_interval_seconds=interval,)app = FastAPI()app.state.config = configplugin = TrustedAuthPlugin()await plugin.initialize(app, auth_service, config)- try:- assert plugin._flush_task is None- for path in ("/api/v1/resources", "/api/v1/admin/accounts"):- headers = {- "X-OpenViking-Account": "acme",- "X-OpenViking-User": "alice",- }- request = _make_request(- path,- headers=headers,- auth_enabled=False,- auth_mode="trusted",- root_api_key=ROOT_KEY,- )- request.app.state.config = config- request.app.state.api_key_manager = app.state.api_key_manager- await plugin.resolve_identity(- request,- api_key=ROOT_KEY,- x_openviking_account="acme",- x_openviking_user="alice",- )-- await plugin.flush_trusted_identities()- assert plugin._api_key_manager.has_user("acme", "alice") is False- finally:- await plugin.shutdown()---async def test_trusted_identity_registration_excludes_admin_paths(auth_service):- """Enabled registration must still exclude Admin requests."""- from openviking.server.auth.plugins import TrustedAuthPlugin-- config = ServerConfig(auth_mode="trusted", root_api_key=ROOT_KEY)- app = FastAPI()- app.state.config = config- plugin = TrustedAuthPlugin()- await plugin.initialize(app, auth_service, config)try:request = _make_request(- "/api/v1/admin/accounts",+ path,headers={"X-OpenViking-Account": "acme","X-OpenViking-User": "alice",},auth_enabled=False,auth_mode="trusted",- root_api_key=ROOT_KEY,)request.app.state.config = configrequest.app.state.api_key_manager = app.state.api_key_managerawait plugin.resolve_identity(request,- api_key=ROOT_KEY,x_openviking_account="acme",x_openviking_user="alice",)- assert plugin._pending == {}+ await plugin.flush_trusted_identities()+ assert await _stored_users(auth_service, "acme") == []finally:await plugin.shutdown()@@ -1291,31 +1171,46 @@ async def test_trusted_identity_registration_retries_failed_batch_without_exceedplugin = TrustedAuthPlugin()await plugin.initialize(app, auth_service, config)try:- plugin._queue_trusted_identity("acme", "alice")- plugin._queue_trusted_identity("acme", "bob")- plugin._queue_trusted_identity("acme", "eve")- assert plugin._pending == {"acme": {"alice", "bob"}}+ for user_id in ("alice", "bob", "eve"):+ request = _make_request(+ "/api/v1/resources",+ headers={+ "X-OpenViking-Account": "acme",+ "X-OpenViking-User": user_id,+ },+ auth_enabled=False,+ auth_mode="trusted",+ )+ request.app.state.config = config+ await plugin.resolve_identity(+ request,+ x_openviking_account="acme",+ x_openviking_user=user_id,+ )- original_ensure = plugin._api_key_manager.ensure_trusted_identities+ original_ensure = APIKeyManager.ensure_trusted_identities+ failed = False- async def _fail_once(identities):- monkeypatch.setattr(plugin._api_key_manager, "ensure_trusted_identities", original_ensure)- raise RuntimeError("temporary storage failure")+ async def _fail_once(manager, identities):+ nonlocal failed+ if not failed:+ failed = True+ raise RuntimeError("temporary storage failure")+ return await original_ensure(manager, identities)- monkeypatch.setattr(plugin._api_key_manager, "ensure_trusted_identities", _fail_once)+ monkeypatch.setattr(APIKeyManager, "ensure_trusted_identities", _fail_once)await plugin.flush_trusted_identities()- assert plugin._pending == {"acme": {"alice", "bob"}}await plugin.flush_trusted_identities()- assert plugin._api_key_manager.has_user("acme", "alice")- assert plugin._api_key_manager.has_user("acme", "bob")+ assert await _stored_users(auth_service, "acme") == [+ {"user_id": "alice", "role": "user"},+ {"user_id": "bob", "role": "user"},+ ]finally:await plugin.shutdown()-def test_trusted_identity_registration_config_allows_disabling():- """A zero interval disables registration; negative values remain invalid."""- assert ServerConfig(trusted_identity_flush_interval_seconds=0).trusted_identity_flush_interval_seconds == 0+def test_trusted_identity_registration_config_rejects_invalid_limits():with pytest.raises(ValueError):ServerConfig(trusted_identity_flush_interval_seconds=-1)with pytest.raises(ValueError):@@ -1327,6 +1222,7 @@ async def test_trusted_mode_with_root_api_key_requires_matching_api_key():request = _make_request("/api/v1/resources",headers={+ "X-API-Key": "","X-OpenViking-Account": "acme","X-OpenViking-User": "alice",},@@ -1432,14 +1328,11 @@ async def test_trusted_mode_tenant_http_routes_require_explicit_identity_headersidentity=None,auth_enabled=False,auth_mode="trusted",- root_api_key=ROOT_KEY,)transport = httpx.ASGITransport(app=app)- async with httpx.AsyncClient(- transport=transport, headers={"X-API-Key": ROOT_KEY}, base_url="http://testserver"- ) as client:- response = await client.get("/api/v1/fs/ls")+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ response = await client.get("/api/v1/fs/ls", headers={"X-API-Key": ROOT_KEY})assert response.status_code == 400assert response.json()["error"]["code"] == "INVALID_ARGUMENT"@@ -1451,16 +1344,14 @@ async def test_trusted_mode_tenant_http_routes_accept_explicit_identity_headers(identity=None,auth_enabled=False,auth_mode="trusted",- root_api_key=ROOT_KEY,)transport = httpx.ASGITransport(app=app)- async with httpx.AsyncClient(- transport=transport, headers={"X-API-Key": ROOT_KEY}, base_url="http://testserver"- ) as client:+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:response = await client.get("/api/v1/fs/ls",headers={+ "X-API-Key": ROOT_KEY,"X-OpenViking-Account": "acme","X-OpenViking-User": "alice",},@@ -1476,14 +1367,14 @@ async def test_trusted_mode_http_routes_accept_explicit_identity_from_url():identity=None,auth_enabled=False,auth_mode="trusted",- root_api_key=ROOT_KEY,)transport = httpx.ASGITransport(app=app)- async with httpx.AsyncClient(- transport=transport, headers={"X-API-Key": ROOT_KEY}, base_url="http://testserver"- ) as client:- response = await client.get("/api/v1/test/accounts/acme/users/alice")+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ response = await client.get(+ "/api/v1/test/accounts/acme/users/alice",+ headers={"X-API-Key": ROOT_KEY},+ )assert response.status_code == 200assert response.json()["result"] == {@@ -1500,42 +1391,67 @@ async def test_trusted_mode_rejects_conflicting_header_and_url_identity():identity=None,auth_enabled=False,auth_mode="trusted",- root_api_key=ROOT_KEY,)transport = httpx.ASGITransport(app=app)- async with httpx.AsyncClient(- transport=transport, headers={"X-API-Key": ROOT_KEY}, base_url="http://testserver"- ) as client:+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:response = await client.get("/api/v1/test/accounts/acme/users/alice",- headers={"X-OpenViking-Account": "other-acct"},+ headers={+ "X-API-Key": ROOT_KEY,+ "X-OpenViking-Account": "other-acct",+ },)assert response.status_code == 400assert response.json()["error"]["code"] == "INVALID_ARGUMENT"[email protected]("api_key", [None, "wrong-key", ROOT_KEY])[email protected]("path", ["/api/v1/fs/ls", "/api/v1/test/accounts/acme/users/alice"])-async def test_trusted_mode_http_routes_require_matching_root_key(api_key, path):+async def test_trusted_mode_http_routes_require_api_key_when_root_key_configured():+ """Trusted mode HTTP routes should require the configured server API key when present."""app = _build_auth_http_test_app(- identity=None, auth_enabled=False, auth_mode="trusted", root_api_key=ROOT_KEY+ identity=None,+ auth_enabled=False,+ auth_mode="trusted",+ root_api_key=ROOT_KEY,)- headers = {"X-OpenViking-Account": "acme", "X-OpenViking-User": "alice"}- if api_key is not None:- headers["X-API-Key"] = api_key- async with httpx.AsyncClient(- transport=httpx.ASGITransport(app=app), base_url="http://testserver"- ) as client:- response = await client.get(path, headers=headers)- if api_key == ROOT_KEY:- assert response.status_code == 200- assert response.json()["result"]["account_id"] == "acme"- assert response.json()["result"]["user_id"] == "alice"- else:- assert response.status_code == 401- assert response.json()["error"]["code"] == "UNAUTHENTICATED"+ transport = httpx.ASGITransport(app=app)++ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ response = await client.get(+ "/api/v1/fs/ls",+ headers={+ "X-OpenViking-Account": "acme",+ "X-OpenViking-User": "alice",+ },+ )++ assert response.status_code == 401+ assert response.json()["error"]["code"] == "UNAUTHENTICATED"+++async def test_trusted_mode_http_routes_accept_api_key_when_root_key_configured():+ """Trusted mode HTTP routes should accept the configured server API key plus explicit identity headers."""+ app = _build_auth_http_test_app(+ identity=None,+ auth_enabled=False,+ auth_mode="trusted",+ root_api_key=ROOT_KEY,+ )+ transport = httpx.ASGITransport(app=app)++ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ response = await client.get(+ "/api/v1/fs/ls",+ headers={+ "X-API-Key": ROOT_KEY,+ "X-OpenViking-Account": "acme",+ "X-OpenViking-User": "alice",+ },+ )++ assert response.status_code == 200+ assert response.json()["result"] == {"account_id": "acme", "user_id": "alice"}# ---- _is_localhost tests ----@@ -1575,17 +1491,10 @@ def test_validate_with_key_any_host_passes():validate_server_config(config) # should not raise[email protected]("host", ["127.0.0.1", "localhost", "::1", "0.0.0.0"])[email protected]("root_key", [None, "", " ", ROOT_KEY])-async def test_validate_trusted_mode_requires_root_key_on_every_host(host, root_key):- from openviking.server.auth.health_check import HealthStatus, TrustedAuthChecker-- config = ServerConfig(host=host, root_api_key=root_key, auth_mode="trusted")- (check,) = await TrustedAuthChecker().run_checks(config)- assert check.status == (HealthStatus.PASS if root_key == ROOT_KEY else HealthStatus.FAIL)- if root_key == ROOT_KEY:- validate_server_config(config)- else:+def test_validate_trusted_mode_requires_root_key_on_every_host():+ """Trusted mode without root_api_key should fail on every host."""+ for host in ("127.0.0.1", "localhost", "::1", "0.0.0.0"):+ config = ServerConfig(host=host, root_api_key=None, auth_mode="trusted")with pytest.raises(SystemExit):validate_server_config(config)@@ -1597,16 +1506,31 @@ async def test_trusted_mode_admin_api_without_identity_defaults_to_root():headers={},auth_enabled=False,auth_mode="trusted",- root_api_key=ROOT_KEY,)- identity = await resolve_identity(request, x_api_key=ROOT_KEY)+ identity = await resolve_identity(request)assert identity.role == Role.ROOTassert identity.account_id == "trusted"assert identity.user_id == "trusted"+async def test_trusted_mode_admin_api_treats_partial_identity_as_target():+ """Trusted Admin paths treat account/user values as resource targets."""+ request = _make_request(+ "/api/v1/admin/accounts",+ headers={"X-OpenViking-Account": "acme"},+ auth_enabled=False,+ auth_mode="trusted",+ )++ identity = await resolve_identity(request, x_openviking_account="acme")++ assert identity.role == Role.ROOT+ assert identity.account_id == "acme"+ assert identity.user_id == "trusted"++async def test_trusted_mode_root_key_can_target_account_without_caller_identity():"""A verified Root key should not treat a target account as partial caller identity."""request = _make_request(@@ -1631,7 +1555,6 @@ async def test_trusted_mode_get_request_context_exempts_admin_paths():"/api/v1/admin/accounts",auth_enabled=False,auth_mode="trusted",- root_api_key=ROOT_KEY,)identity = ResolvedIdentity(role=Role.ROOT,@@ -1650,7 +1573,6 @@ async def test_trusted_mode_get_request_context_exempts_admin_paths():"/api/v1/fs/ls",auth_enabled=False,auth_mode="trusted",- root_api_key=ROOT_KEY,)incomplete_identity = ResolvedIdentity(role=Role.ROOT,@@ -1668,7 +1590,6 @@ async def test_trusted_mode_admin_api_http_route_without_identity():identity=None,auth_enabled=False,auth_mode="trusted",- root_api_key=ROOT_KEY,)# Add an admin route to the test app@@ -1685,101 +1606,14 @@ async def test_trusted_mode_admin_api_http_route_without_identity():transport = httpx.ASGITransport(app=app)- async with httpx.AsyncClient(- transport=transport, headers={"X-API-Key": ROOT_KEY}, base_url="http://testserver"- ) as client:- response = await client.get("/api/v1/admin/accounts")+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ response = await client.get(+ "/api/v1/admin/accounts",+ headers={"X-API-Key": ROOT_KEY},+ )assert response.status_code == 200assert response.json()["status"] == "ok"assert response.json()["result"]["role"] == "root"assert response.json()["result"]["account_id"] == "trusted"assert response.json()["result"]["user_id"] == "trusted"---# ---- API key store watcher (read-replica refresh) tests -----#-# When server.api_key_watch_enabled is set, the api_key plugin starts a-# background task that polls the shared key store and reloads the in-memory-# index on change, so read replicas converge on writer-side user changes.---class _FakeManager:- """Minimal APIKeyManager stand-in that records watcher interactions."""-- def __init__(self, signatures):- # signatures: list of signatures returned on successive calls; the last- # value is repeated once exhausted.- self._signatures = list(signatures)- self.reload_calls = 0- self.signature_calls = 0-- async def compute_store_signature(self):- self.signature_calls += 1- idx = min(self.signature_calls - 1, len(self._signatures) - 1)- return self._signatures[idx]-- async def reload(self):- self.reload_calls += 1---async def test_watcher_disabled_by_default(auth_service):- """No watch task should start when api_key_watch_enabled is unset."""- from openviking.server.auth.plugins import ApiKeyAuthPlugin-- app = create_app(config=ServerConfig(root_api_key=ROOT_KEY), service=auth_service)- plugin = ApiKeyAuthPlugin()- config = ServerConfig(root_api_key=ROOT_KEY)- await plugin.initialize(app, auth_service, config)- try:- assert plugin._watch_task is None- finally:- await plugin.shutdown()---async def test_watcher_reloads_on_signature_change(auth_service):- """The watcher reloads only when the store signature changes."""- from openviking.server.auth.plugins import ApiKeyAuthPlugin-- manager = _FakeManager(signatures=[("sig-a",), ("sig-b",)])- task = asyncio.create_task(ApiKeyAuthPlugin._watch_key_store(manager, interval=0.01))- try:- await asyncio.sleep(0.1)- finally:- task.cancel()- with pytest.raises(asyncio.CancelledError):- await task- # First signature is the baseline; the change to sig-b triggers a reload.- assert manager.reload_calls >= 1---async def test_watcher_skips_reload_when_unchanged(auth_service):- """A stable signature must not trigger any reload."""- from openviking.server.auth.plugins import ApiKeyAuthPlugin-- manager = _FakeManager(signatures=[("sig-stable",)])- task = asyncio.create_task(ApiKeyAuthPlugin._watch_key_store(manager, interval=0.01))- try:- await asyncio.sleep(0.08)- finally:- task.cancel()- with pytest.raises(asyncio.CancelledError):- await task- assert manager.reload_calls == 0---async def test_shutdown_cancels_watch_task(auth_service):- """shutdown() must cancel a running watch task and clear the handle."""- from openviking.server.auth.plugins import ApiKeyAuthPlugin-- app = create_app(config=ServerConfig(root_api_key=ROOT_KEY), service=auth_service)- plugin = ApiKeyAuthPlugin()- config = ServerConfig(- root_api_key=ROOT_KEY,- api_key_watch_enabled=True,- api_key_watch_interval_seconds=0.01,- )- await plugin.initialize(app, auth_service, config)- assert plugin._watch_task is not None- await plugin.shutdown()- assert plugin._watch_task is Nonediff --git a/tests/server/test_bot_studio.py b/tests/server/test_bot_studio.pyindex f270dd8f4..6b92208d4 100644--- a/tests/server/test_bot_studio.py+++ b/tests/server/test_bot_studio.py@@ -1,7 +1,7 @@"""The browser cannot elevate or cross accounts through Studio management."""from types import SimpleNamespace-from unittest.mock import AsyncMock, Mock+from unittest.mock import AsyncMockimport httpximport pytest@@ -74,17 +74,18 @@ async def test_reused_admin_users_support_safe_credential_status(role=Role.ROOT,)registry = SimpleNamespace(- refresh_account_users_from_store=AsyncMock(),- get_users_page=lambda *args, **kwargs: {- "users": [- {"user_id": "bot", "role": "user", "api_key": "private"},- {"user_id": "hashed", "role": "user", "key_prefix": "prefix"},- ],- "total": 2,- "account_total": 2,- "manager_count": 0,- "key_count": 2,- },+ list_users_page=AsyncMock(+ return_value={+ "users": [+ {"user_id": "bot", "role": "user", "api_key": "private"},+ {"user_id": "hashed", "role": "user", "key_prefix": "prefix"},+ ],+ "total": 2,+ "account_total": 2,+ "manager_count": 0,+ "key_count": 2,+ }+ ),)app.state.api_key_manager = registrymonkeypatch.setattr(admin, "_get_api_key_manager", lambda request: registry)@@ -121,8 +122,11 @@ async def test_selection_uses_current_account_registry(monkeypatch, user_id, accfrom fastapi import HTTPExceptionregistry = SimpleNamespace(- refresh_account_users_from_store=AsyncMock(),- get_users=lambda *a, **kw: [{"user_id": "bot", "api_key": "internal-key"}],+ list_users_page=AsyncMock(+ return_value={+ "users": [{"user_id": "bot", "api_key": "internal-key"}],+ }+ ),)monkeypatch.setattr(bot_studio, "get_api_key_manager_or_raise", lambda request: registry)monkeypatch.setattr(@@ -145,7 +149,6 @@ async def test_selection_uses_current_account_registry(monkeypatch, user_id, accwith pytest.raises(HTTPException) as exc:await bot_studio.selected_identity(request, ctx, user_id)assert exc.value.status_code == 400- registry.refresh_account_users_from_store.assert_awaited_with("a")async def test_hashed_key_is_not_treated_as_a_usable_credential(monkeypatch):@@ -164,8 +167,11 @@ async def test_hashed_key_is_not_treated_as_a_usable_credential(monkeypatch):async def test_trusted_selection_uses_keyless_root_identity(monkeypatch):registry = SimpleNamespace(- refresh_account_users_from_store=AsyncMock(),- get_users=Mock(return_value=[{"user_id": "bot", "key_prefix": "prefix"}]),+ list_users_page=AsyncMock(+ return_value={+ "users": [{"user_id": "bot", "key_prefix": "prefix"}],+ }+ ),)monkeypatch.setattr(bot_studio, "get_api_key_manager_or_raise", lambda request: registry)monkeypatch.setattr(@@ -177,8 +183,12 @@ async def test_trusted_selection_uses_keyless_root_identity(monkeypatch):identity = await bot_studio.selected_identity(request, ctx, "bot")- registry.get_users.assert_called_once_with(- "a", limit=None, role_filter="user", expose_key=False+ registry.list_users_page.assert_awaited_once_with(+ "a",+ limit=None,+ role_filter="user",+ expose_key=False,+ fresh=True,)assert identity == {"account_id": "a",diff --git a/tests/server/test_gateway_proxy.py b/tests/server/test_gateway_proxy.pyindex 45e0e0d20..74b647f49 100644--- a/tests/server/test_gateway_proxy.py+++ b/tests/server/test_gateway_proxy.py@@ -31,8 +31,9 @@ def app():app = FastAPI()app.include_router(gateway.router)app.state.api_key_manager = SimpleNamespace(- refresh_account_users_from_store=AsyncMock(),- get_users=lambda account_id, **kwargs: USERS[account_id],+ list_users_page=AsyncMock(+ side_effect=lambda account_id, **_kwargs: {"users": USERS[account_id]}+ ),)app.dependency_overrides[get_request_context] = lambda: RequestContext(user=UserIdentifier("a", "boss"), role=Role.ADMIN@@ -85,7 +86,13 @@ async def test_selected_user_is_replaced_with_their_stored_key(app, forwarded, uassert request.headers["X-OpenViking-Account"] == "a"assert json.loads(request.content) == {**SETTINGS, "openviking_key": key}assert key not in response.text- app.state.api_key_manager.refresh_account_users_from_store.assert_awaited_with("a")+ app.state.api_key_manager.list_users_page.assert_awaited_with(+ "a",+ limit=None,+ role_filter=None,+ expose_key=True,+ fresh=True,+ )@pytest.mark.parametrize("user_id", ["missing", "carol", "root"])@@ -115,7 +122,7 @@ async def test_root_cannot_choose_a_user(app, forwarded):assert response.status_code == 400assert "paste the user's OpenViking key" in response.json()["detail"]assert forwarded == []- app.state.api_key_manager.refresh_account_users_from_store.assert_not_called()+ app.state.api_key_manager.list_users_page.assert_not_called()async def test_user_and_pasted_key_together_are_rejected_without_echo(app, forwarded):@@ -145,7 +152,7 @@ async def test_other_requests_pass_through_unchanged(app, forwarded, method, patassert request.method == methodassert request.url.path == "/admin/" + pathassert request.content == body- app.state.api_key_manager.refresh_account_users_from_store.assert_not_called()+ app.state.api_key_manager.list_users_page.assert_not_called()@pytest.mark.parametrize("path", ["uploads", "v1/models"])diff --git a/tests/server/test_identity_auth.py b/tests/server/test_identity_auth.pynew file mode 100644index 000000000..5e4283b94--- /dev/null+++ b/tests/server/test_identity_auth.py@@ -0,0 +1,273 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++import asyncio+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+from starlette.requests import Request++from openviking.server.account_stores.base import AccountStore+from openviking.server.api_keys import APIKeyManager+from openviking.server.auth import (+ get_request_context,+ get_session_request_context,+)+from openviking.server.auth.plugin import AuthPlugin+from openviking.server.auth.plugins.api_key import ApiKeyAuthPlugin+from openviking.server.auth.plugins.trusted import TrustedAuthPlugin+from openviking.server.config import ServerConfig+from openviking.server.identity import ResolvedIdentity, Role+from openviking.server.store_assembly import build_api_key_manager+from openviking_cli.exceptions import (+ FailedPreconditionError,+ UnauthenticatedError,+)+from tests.server.account_store_fakes import InMemoryAGFS+++async def runtime():+ manager = build_api_key_manager(+ "root",+ SimpleNamespace(agfs=InMemoryAGFS()),+ )+ await manager.load()+ await manager.create_account("acme", "alice")+ yield manager+ await manager.close()+++async def make_request(+ runtime,+ mode="api_key",+ root="root",+ headers=(),+ path="/api/v1/content/read",+ trusted_flush_interval=0,+):+ config = ServerConfig(+ auth_mode=mode,+ root_api_key=root,+ trusted_identity_flush_interval_seconds=trusted_flush_interval,+ )+ plugin = TrustedAuthPlugin() if mode == "trusted" else ApiKeyAuthPlugin()+ state = SimpleNamespace(config=config, api_key_manager=runtime, auth_plugin=plugin)+ request = Request(+ {+ "type": "http",+ "method": "GET",+ "path": path,+ "headers": list(headers),+ "query_string": b"",+ "app": SimpleNamespace(state=state),+ }+ )+ if mode == "trusted":+ plugin._api_key_manager = runtime+ plugin._flush_interval_seconds = trusted_flush_interval+ if root is None:+ request.app.state.api_key_manager = None+ return request+++async def test_key_identity_and_groups_are_resolved_independently(runtime):+ key = await runtime.register_user("acme", "bob")+ await runtime.create_group("acme", "team")+ await runtime.add_group_member("acme", "team", "bob")+ request = await make_request(runtime, headers=[(b"x-openviking-user", b"spoof")])+ plugin = request.app.state.auth_plugin+ identity = await plugin.resolve_identity(+ request, api_key=key, x_openviking_user="spoof", x_openviking_account="spoof"+ )+ ctx = await get_request_context(request, identity, "peer", key, None)+ assert (ctx.user.user_id, ctx.role, ctx.group_ids) == ("bob", Role.USER, ("team",))+ assert ctx.actor_peer_id == "peer"+ assert ctx.api_key == key+ assert "x-openviking-user" not in request.headers+ session = await get_session_request_context(request, identity, key, None)+ assert session.actor_peer_id is None+++async def test_key_store_error_and_unknown_identity_fail_closed():+ store = AsyncMock(spec=AccountStore)+ store.verify_api_key.return_value = ("acme", "missing")+ store.get_user.return_value = None+ manager = APIKeyManager("root", store)+ request = await make_request(manager)+ with pytest.raises(UnauthenticatedError, match="Unknown"):+ await request.app.state.auth_plugin.resolve_identity(request, api_key="verified-key")+ store.get_user.side_effect = OSError("database offline")+ with pytest.raises(OSError, match="database offline"):+ await request.app.state.auth_plugin.resolve_identity(request, api_key="verified-key")+++async def test_trusted_explicit_user_role_with_root_key(runtime):+ request = await make_request(runtime, "trusted", "root")+ plugin = request.app.state.auth_plugin+ identity = await plugin.resolve_identity(+ request, api_key="root", x_openviking_account="acme", x_openviking_user="alice"+ )+ assert identity.role == Role.ADMIN+ asserted = await make_request(+ runtime, "trusted", "root", headers=[(b"x-openviking-role", b"user")]+ )+ identity = await plugin.resolve_identity(+ asserted,+ api_key="root",+ x_openviking_account="acme",+ x_openviking_user="alice",+ )+ assert identity.role == Role.USER+++async def test_trusted_unknown_user_cannot_bypass_account_deletion(runtime):+ """[defect-probing] Account fence also covers not-yet-registered trusted users."""+ await runtime.begin_deletion(+ "acme", None, task_id="delete", owner_account_id="system", owner_user_id="system"+ )+ request = await make_request(runtime, "trusted")+ identity = await request.app.state.auth_plugin.resolve_identity(+ request, api_key="root", x_openviking_account="acme", x_openviking_user="newcomer"+ )+ with pytest.raises(FailedPreconditionError) as exc:+ await get_request_context(request, identity, None, "root", None)+ assert exc.value.details["task_id"] == "delete"+++async def test_root_context_remains_available_while_default_account_is_deleting(runtime):+ if await runtime.get_registered_user_role("default", "default") is None:+ await runtime.register_user("default", "default", Role.ADMIN)+ await runtime.begin_deletion(+ "default",+ None,+ task_id="delete-default",+ owner_account_id="system",+ owner_user_id="system",+ )+ request = await make_request(runtime, path="/api/v1/admin/accounts")+ identity = await request.app.state.auth_plugin.resolve_identity(request, api_key="root")++ ctx = await get_request_context(request, identity, None, "root", None)++ assert (ctx.role, ctx.account_id, ctx.user.user_id, ctx.group_ids) == (+ Role.ROOT,+ "default",+ "default",+ (),+ )+++async def test_external_context_preserves_role_without_local_gate(runtime):+ class ExternalPlugin(AuthPlugin):+ auth_mode = "external"++ async def initialize(self, app, service, config):+ pass++ def validate_config(self, config):+ pass++ async def resolve_identity(self, request, **kwargs):+ return ResolvedIdentity(role=Role.USER, account_id="external", user_id="subject")++ request = await make_request(runtime, "external")+ plugin = ExternalPlugin()+ request.app.state.auth_plugin = plugin+ identity = await plugin.resolve_identity(request)+ ctx = await get_request_context(request, identity, None, None, None)+ assert (ctx.role, ctx.account_id, ctx.group_ids) == (Role.USER, "external", ())+++async def test_trusted_cancelled_flush_requeues_batch_and_shutdown_preserves_store(+ runtime, monkeypatch+):+ request = await make_request(runtime, "trusted", trusted_flush_interval=300)+ plugin = request.app.state.auth_plugin+ await plugin.resolve_identity(+ request,+ api_key="root",+ x_openviking_account="acme",+ x_openviking_user="bob",+ )+ entered = asyncio.Event()+ original = runtime.ensure_trusted_identities++ async def blocked_batch(identities):+ entered.set()+ await asyncio.Future()++ monkeypatch.setattr(runtime, "ensure_trusted_identities", blocked_batch)+ flush = asyncio.create_task(plugin.flush_trusted_identities())+ await entered.wait()+ flush.cancel()+ with pytest.raises(asyncio.CancelledError):+ await flush+ monkeypatch.setattr(runtime, "ensure_trusted_identities", original)+ await plugin.shutdown()+ assert await runtime.has_user("acme", "bob")+ assert await runtime.get_registered_user_role("acme", "alice") == Role.ADMIN+++ "mode,custom", [("oidc", False), ("oidc", True), ("ldap", False), ("ldap", True)]+)+async def test_builtin_external_mapping_preserves_identity_and_user_role(+ runtime, mode, custom, monkeypatch+):+ from openviking.server.auth.identity_mapping import IdentityMapper+ from openviking.server.auth.ldap_config import LDAPConfig+ from openviking.server.auth.oidc_config import OIDCConfig+ from openviking.server.auth.plugins import ldap as ldap_module+ from openviking.server.auth.plugins import oidc as oidc_module++ if mode == "oidc":+ plugin = oidc_module.OIDCAuthPlugin()+ config = OIDCConfig(issuer="https://issuer.test")+ headers = [(b"authorization", b"Bearer external.token.value")]+ monkeypatch.setattr(oidc_module, "_check_jwt_available", lambda: True)+ monkeypatch.setattr(+ plugin,+ "_validate_token",+ AsyncMock(return_value={"sub": "auth0|123", "org": "Team", "preferred": "Alice"}),+ )+ expected = ("default", "auth0_123")+ if custom:+ config.identity.account_id.source = "claim"+ config.identity.account_id.claim = "org"+ config.identity.account_id.normalize = "lowercase"+ config.identity.user_id.claims = ["preferred", "sub"]+ config.identity.user_id.prefix = "ext-"+ expected = ("team", "ext-Alice")+ else:+ plugin = ldap_module.LDAPAuthPlugin()+ config = LDAPConfig(host="directory.test", base_dn="dc=test")+ headers = [(b"authorization", b"Basic YWxpY2U6cGFzc3dvcmQ=")]+ monkeypatch.setattr(ldap_module, "LDAP_AVAILABLE", True)+ monkeypatch.setattr(+ plugin,+ "_authenticate_ldap",+ lambda *args: {+ "uid": [b"directory-user"],+ "dn": [b"cn=alice,ou=Team,dc=test"],+ },+ )+ expected = ("default", "directory-user")+ if custom:+ config.identity.user_id.source = "dn_attribute"+ config.identity.user_id.attribute = "cn"+ config.identity.account_id.source = "dn_attribute"+ config.identity.account_id.attribute = "ou"+ expected = ("Team", "alice")+ config.identity.role.source = "fixed"+ config.identity.role.value = "root"+ plugin._config = config+ plugin._mapper = IdentityMapper(config.identity)+ request = await make_request(runtime, mode, headers=headers)+ request.app.state.auth_plugin = plugin+ identity = await plugin.resolve_identity(request)+ assert (identity.account_id, identity.user_id) == expected+ assert identity.role == Role.USER+ ctx = await get_request_context(request, identity, None, None, None)+ assert ctx.role == Role.USERdiff --git a/tests/server/test_resources_temp_upload_token.py b/tests/server/test_resources_temp_upload_token.pyindex fea356870..3c35977a3 100644--- a/tests/server/test_resources_temp_upload_token.py+++ b/tests/server/test_resources_temp_upload_token.py@@ -28,7 +28,26 @@ def _reset_token_store():upload_token_store.clear()-async def test_token_upload_auto_ingests_and_returns_result(upload_temp_dir: Path, monkeypatch):+async def upload_api_key_manager():+ from types import SimpleNamespace++ from openviking.server.store_assembly import build_api_key_manager+ from tests.server.account_store_fakes import InMemoryAGFS++ manager = build_api_key_manager("test-root", SimpleNamespace(agfs=InMemoryAGFS()))+ await manager.load()+ try:+ await manager.create_account("acct", "owner")+ await manager.register_user("acct", "user", Role.ADMIN)+ yield manager+ finally:+ await manager.close()+++async def test_token_upload_auto_ingests_and_returns_result(+ upload_temp_dir: Path, monkeypatch, upload_api_key_manager+):"""An upload keeps the issuing authority, but cannot outlive a role downgrade."""from types import SimpleNamespacefrom unittest.mock import AsyncMock@@ -48,17 +67,12 @@ async def test_token_upload_auto_ingests_and_returns_result(upload_temp_dir: Patfrom openviking_cli.exceptions import OpenVikingErrorfrom openviking_cli.session.user_id import UserIdentifier- current_role = Role.ADMIN+ manager = upload_api_key_managerconfig = ServerConfig(auth_mode="api_key", root_api_key="test-root")app = FastAPI()app.state.config = configapp.state.auth_plugin = ApiKeyAuthPlugin()- app.state.api_key_manager = SimpleNamespace(- has_user=lambda *_: current_role is not None,- get_user_role=lambda *_: current_role,- get_user_group_ids=lambda *_: (),- is_deleting=lambda *_: False,- )+ app.state.api_key_manager = managerapp.include_router(router)@app.exception_handler(OpenVikingError)@@ -125,19 +139,30 @@ async def test_token_upload_auto_ingests_and_returns_result(upload_temp_dir: Pat# An outstanding token loses authority when its user is downgraded.identity.from_oauth = Falsetoken = await issue()- current_role = Role.USER+ await manager.set_role("acct", "user", Role.USER)assert (await upload(token)).status_code == 401# A token issued as USER does not gain ADMIN authority after promotion.identity.role = Role.USERtoken = await issue()- current_role = Role.ADMIN+ await manager.set_role("acct", "user", Role.ADMIN)assert (await upload(token)).status_code == 403- # Removing the user also invalidates an outstanding token.+ # Deletion fences also apply to outstanding upload tokens.identity.role = Role.ADMINtoken = await issue()- current_role = None+ await manager.begin_deletion(+ "acct",+ "user",+ task_id="delete-upload-user",+ owner_account_id="acct",+ owner_user_id="owner",+ )+ assert (await upload(token)).status_code == 412++ # Removing the user invalidates another outstanding token.+ token = await issue()+ assert await manager.finish_deletion("acct", "user", "delete-upload-user")assert (await upload(token)).status_code == 401assert imported == [b"hello world"]diff --git a/tests/server/test_server_health.py b/tests/server/test_server_health.pyindex 66ec8927f..d0e78b960 100644--- a/tests/server/test_server_health.py+++ b/tests/server/test_server_health.py@@ -237,7 +237,9 @@ async def test_process_time_header(client: httpx.AsyncClient):async def test_openviking_error_handler(client: httpx.AsyncClient):"""Requesting a non-existent resource should return structured error."""- resp = await client.get("/api/v1/fs/stat", params={"uri": "viking://nonexistent/path"})+ resp = await client.get(+ "/api/v1/fs/stat", params={"uri": "viking://resources/nonexistent/path"}+ )assert resp.status_code == 404body = resp.json()assert body["status"] == "error"@@ -249,15 +251,26 @@ async def test_404_for_unknown_route(client: httpx.AsyncClient):assert resp.status_code == 404-async def test_lifespan_shutdown_ignores_cancelled_service_close():+async def test_lifespan_shutdown_ignores_cancelled_service_close(monkeypatch):class _Service:async def initialize(self):pass+ async def apply_agent_evolution_config(self):+ pass++ viking_fs = None+ _queue_manager = None+async def close(self):raise asyncio.CancelledError("shutdown")- app = create_app(config=ServerConfig(), service=_Service())+ monkeypatch.setattr("openviking.server.app.OpenVikingService", _Service)+ monkeypatch.setattr(+ "openviking.server.app.get_task_tracker",+ lambda: SimpleNamespace(start_cleanup_loop=lambda: None, stop_cleanup_loop=lambda: None),+ )+ app = create_app(config=ServerConfig())async with app.router.lifespan_context(app):pass@@ -367,7 +380,7 @@ async def test_slow_init_does_not_block_health(monkeypatch):async def test_initialize_runtime_state_loads_api_key_manager(monkeypatch):- """API key auth must finish manager loading before the app is considered ready."""+ """The auth plugin must publish its manager before deletion setup."""class MockService:def __init__(self):@@ -377,17 +390,17 @@ async def test_initialize_runtime_state_loads_api_key_manager(monkeypatch):async def initialize(self):self._initialized = True- class FakeAPIKeyManager:- def __init__(self, root_key, viking_fs, api_key_hashing_enabled):- self.root_key = root_key- self.viking_fs = viking_fs- self.api_key_hashing_enabled = api_key_hashing_enabled- self.loaded = False+ async def apply_agent_evolution_config(self):+ pass++ manager = object()+ setup = AsyncMock(return_value=None)+ monkeypatch.setattr("openviking.service.deletion.setup_deletion", setup)- async def load(self):- self.loaded = True+ async def initialize_plugin(app, service, config):+ app.state.api_key_manager = manager- monkeypatch.setattr("openviking.server.app.APIKeyManager", FakeAPIKeyManager)+ monkeypatch.setattr("openviking.server.app._initialize_auth_plugin", initialize_plugin)app = SimpleNamespace(state=SimpleNamespace(api_key_manager=None))service = MockService()@@ -396,5 +409,5 @@ async def test_initialize_runtime_state_loads_api_key_manager(monkeypatch):await _initialize_runtime_state(app, service, config)assert service._initialized is True- assert app.state.api_key_manager is not None- assert app.state.api_key_manager.loaded is True+ assert app.state.api_key_manager is manager+ assert setup.await_args.kwargs["manager"] is managerdiff --git a/tests/server/test_store_assembly.py b/tests/server/test_store_assembly.pynew file mode 100644index 000000000..fbc3925b5--- /dev/null+++ b/tests/server/test_store_assembly.py@@ -0,0 +1,44 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++from types import SimpleNamespace++import pytest++from openviking.server.api_keys.legacy import FileStore+from openviking.server.config import AccountStoreConfig+from openviking.server.store_assembly import (+ build_account_store,+ build_api_key_manager,+)+from openviking_cli.exceptions import InvalidArgumentError+from tests.server.account_store_fakes import InMemoryAGFS+++def test_unknown_account_store_is_rejected():+ with pytest.raises(InvalidArgumentError, match="Unknown account store provider"):+ build_account_store(+ viking_fs=SimpleNamespace(agfs=InMemoryAGFS()),+ api_key_hashing_enabled=False,+ account_store_provider="missing",+ account_store_params=None,+ account_store_watch_enabled=False,+ account_store_watch_interval_seconds=30,+ )++[email protected]("injected", [False, True])+async def test_assembled_manager_supports_account_authentication(injected):+ account_store = FileStore(SimpleNamespace(agfs=InMemoryAGFS()))+ manager = build_api_key_manager(+ "root",+ None if injected else SimpleNamespace(agfs=InMemoryAGFS()),+ account_store_provider=AccountStoreConfig(provider=" FILE ").provider,+ account_store=account_store if injected else None,+ )+ await manager.load()+ try:+ key = await manager.create_account("acme", "alice")+ assert (await manager.resolve_identity(key)).user_id == "alice"+ finally:+ await manager.close()