Skip to content

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

feat(encryption): make apikey hash encryption as single switch (#1736)

baojun-zhang64682ae1899d
diff --git a/docs/design/multi-tenant-design.md b/docs/design/multi-tenant-design.md
index 32f75e7f7..f5f487bb8 100644
--- a/docs/design/multi-tenant-design.md
+++ b/docs/design/multi-tenant-design.md
@@ -65,10 +65,21 @@ Request
用户的角色(ADMIN / USER)不由 key 决定,而是存储在 account 内的用户注册表中。
**Key 加密存储**:
-- 支持 Argon2id 哈希存储 User Key(可选,通过 `encryption_enabled` 启用)
+- 支持 Argon2id 哈希存储 User Key(可选,通过 `encryption.api_key_hashing.enabled` 启用)
- 加密时存储:`key_prefix`(前 8 字符) + `key_hash`(Argon2id 哈希)
- 验证时:先用 key_prefix 快速定位候选 entry,再用 Argon2id 验证
+**两层加密架构**:
+| 加密层 | 配置项 | 算法 | 可逆性 | 说明 |
+|--------|--------|------|--------|------|
+| **文件层** | `encryption.enabled` | AES-GCM | ✅ 可逆 | 保护整个存储文件 |
+| **API key 字段层** | `encryption.api_key_hashing.enabled` | Argon2id | ❌ 不可逆 | 保护 API key 本身 |
+
+**默认行为**:`encryption.api_key_hashing.enabled = false`
+- API key 以明文存储在 JSON 文件中
+- 但整个文件被 AES-GCM 加密保护
+- `ov admin list-users` 可以显示完整的 API key
+
### 2.2 User Key 机制
注册用户时生成新版格式 key,存入对应 account 的 `users.json`。验证时优先走快速路径(直接解析),回退到前缀索引查找。
@@ -166,7 +177,7 @@ from .legacy import LegacyAPIKeyManager
class APIKeyManager:
"""API Key 生命周期管理与解析(新版实现)"""
- def __init__(self, root_key: str, viking_fs: VikingFS, encryption_enabled: bool = False)
+ def __init__(self, root_key: str, viking_fs: VikingFS, api_key_hashing_enabled: bool = False)
async def load() # 加载所有 account 的 users.json 到内存
def resolve(api_key: str) -> ResolvedIdentity # Key → 身份 + 角色(支持新版/旧版两种格式)
async def create_account(account_id: str, admin_user_id: str, namespace_policy=None) -> str
@@ -203,9 +214,10 @@ def generate_api_key(account_id: str, user_id: str) -> str
```python
class Role(str, Enum):
ROOT = "root"
- ADMIN = "admin" # account 内的管理员(用户属性,非 key 类型)
+ ADMIN = "admin" # account 内的管理员(用户属性,非 key 类型)
USER = "user"
+
@dataclass
class ResolvedIdentity:
role: Role
@@ -213,9 +225,10 @@ class ResolvedIdentity:
user_id: Optional[str] = None
agent_id: Optional[str] = None # 来自 X-OpenViking-Agent header
+
@dataclass
class RequestContext:
- user: UserIdentifier # account_id + user_id + agent_id
+ user: UserIdentifier # account_id + user_id + agent_id
role: Role
```
@@ -331,6 +344,7 @@ def user_space_name(self) -> str:
"""用户级 space,不含 agent_id"""
return f"{self._account_id}_{hashlib.md5(self._user_id.encode()).hexdigest()[:8]}"
+
def agent_space_name(self) -> str:
"""Agent 级 space,受 memory.agent_scope_mode 控制"""
if config.memory.agent_scope_mode == "agent":
@@ -387,17 +401,19 @@ async def ls(self, uri: str, ctx: RequestContext) -> List[str]:
uris = [self._path_to_uri(e, account_id=ctx.account_id) for e in entries]
return [u for u in uris if self._is_accessible(u, ctx)] # 权限过滤,见 5.4
+
# 内部方法:只接收 account_id,不依赖 ctx
def _uri_to_path(self, uri: str, account_id: str = "") -> str:
- remainder = uri[len("viking://"):].strip("/")
+ remainder = uri[len("viking://") :].strip("/")
if account_id:
return f"/local/{account_id}/{remainder}" if remainder else f"/local/{account_id}"
return f"/local/{remainder}" if remainder else "/local"
+
def _path_to_uri(self, path: str, account_id: str = "") -> str:
- inner = path[len("/local/"):] # "acme/user/{space}/memories/x"
+ inner = path[len("/local/") :] # "acme/user/{space}/memories/x"
if account_id and inner.startswith(account_id + "/"):
- inner = inner[len(account_id) + 1:] # "user/{space}/memories/x"
+ inner = inner[len(account_id) + 1 :] # "user/{space}/memories/x"
return f"viking://{inner}"
```
@@ -529,7 +545,7 @@ _is_accessible 检查: owner_space 匹配 OR space in shared_spaces
class ServerConfig:
host: str = "0.0.0.0"
port: int = 1933
- root_api_key: Optional[str] = None # 替代原 api_key
+ root_api_key: Optional[str] = None # 替代原 api_key
cors_origins: List[str] = field(default_factory=lambda: ["*"])
```
@@ -557,8 +573,8 @@ class ServerConfig:
# 多租户后:身份由服务端从 api_key 解析
client = ov.SyncHTTPClient(
url="http://localhost:1933",
- api_key="7f3a9c1e...", # 服务端查表解析出 account_id + user_id
- agent_id="coding-agent", # 可选,默认 "default"
+ api_key="7f3a9c1e...", # 服务端查表解析出 account_id + user_id
+ agent_id="coding-agent", # 可选,默认 "default"
)
```
@@ -589,6 +605,7 @@ client = ov.Client(path="/data/openviking")
# 多租户(指定身份)
from openviking_cli.session.user_id import UserIdentifier
+
user = UserIdentifier("acme", "alice", "coding-agent")
client = ov.Client(path="/data/openviking", user=user)
```
@@ -677,23 +694,28 @@ from dataclasses import dataclass
from typing import Optional
from openviking.session.user_id import UserIdentifier
+
class Role(str, Enum):
ROOT = "root"
- ADMIN = "admin" # account 内的管理员(用户属性,非 key 类型)
+ ADMIN = "admin" # account 内的管理员(用户属性,非 key 类型)
USER = "user"
+
@dataclass
class ResolvedIdentity:
"""认证中间件的输出:从 API Key 解析出的原始身份信息"""
+
role: Role
- account_id: Optional[str] = None # ROOT 可能无 account_id
- user_id: Optional[str] = None # ROOT 可能无 user_id
- agent_id: Optional[str] = None # 来自 X-OpenViking-Agent header
+ account_id: Optional[str] = None # ROOT 可能无 account_id
+ user_id: Optional[str] = None # ROOT 可能无 user_id
+ agent_id: Optional[str] = None # 来自 X-OpenViking-Agent header
+
@dataclass
class RequestContext:
"""请求级上下文,贯穿 Router → Service → VikingFS 全链路"""
- user: UserIdentifier # 完整三元组(account_id, user_id, agent_id)
+
+ user: UserIdentifier # 完整三元组(account_id, user_id, agent_id)
role: Role
@property
@@ -717,15 +739,16 @@ class RequestContext:
class ServerConfig:
host: str = "0.0.0.0"
port: int = 1933
- api_key: Optional[str] = None # ← 删除
+ api_key: Optional[str] = None # ← 删除
cors_origins: List[str] = field(default_factory=lambda: ["*"])
+
# 改后
@dataclass
class ServerConfig:
host: str = "0.0.0.0"
port: int = 1933
- root_api_key: Optional[str] = None # ← 替代 api_key
+ root_api_key: Optional[str] = None # ← 替代 api_key
cors_origins: List[str] = field(default_factory=lambda: ["*"])
```
@@ -734,7 +757,7 @@ class ServerConfig:
config = ServerConfig(
host=server_data.get("host", "0.0.0.0"),
port=server_data.get("port", 1933),
- root_api_key=server_data.get("root_api_key"), # ← 改
+ root_api_key=server_data.get("root_api_key"), # ← 改
cors_origins=server_data.get("cors_origins", ["*"]),
)
```
@@ -754,7 +777,7 @@ Per-account 存储,两级文件:
{
"accounts": {
"default": {"created_at": "2026-02-12T10:00:00Z"},
- "acme": {"created_at": "2026-02-13T08:00:00Z"}
+ "acme": {"created_at": "2026-02-13T08:00:00Z"},
}
}
@@ -762,7 +785,7 @@ Per-account 存储,两级文件:
{
"users": {
"alice": {"role": "admin", "key": "YWNtZQ==.YWxpY2U=.OWFmZTEy..."},
- "bob": {"role": "user", "key": "YWNtZQ==.Ym9i.ZWgyZDRm..."}
+ "bob": {"role": "user", "key": "YWNtZQ==.Ym9i.ZWgyZDRm..."},
}
}
@@ -770,7 +793,7 @@ Per-account 存储,两级文件:
{
"users": {
"alice": {"role": "admin", "key": "$argon2id$v=19$...", "key_prefix": "YWNtZQ=="},
- "bob": {"role": "user", "key": "$argon2id$v=19$...", "key_prefix": "YWNtZQ=="}
+ "bob": {"role": "user", "key": "$argon2id$v=19$...", "key_prefix": "YWNtZQ=="},
}
}
```
@@ -778,12 +801,12 @@ Per-account 存储,两级文件:
内存索引(启动时从所有 account 加载):
```python
self._prefix_index: Dict[str, List[UserKeyEntry]] = {} # {key_prefix -> [entries]}
-self._accounts: Dict[str, AccountInfo] = {} # {account_id -> AccountInfo(users)}
+self._accounts: Dict[str, AccountInfo] = {} # {account_id -> AccountInfo(users)}
```
##### 方法逻辑(新版 NewAPIKeyManager)
-**`__init__(root_key, viking_fs, encryption_enabled=False)`**:
+**`__init__(root_key, viking_fs, api_key_hashing_enabled=False)`**:
- 存储 root_key
- 接收 VikingFS 实例(而非 AGFS URL)
- 可选启用 Argon2id 加密存储
@@ -792,7 +815,7 @@ self._accounts: Dict[str, AccountInfo] = {} # {account_id -> AccountI
- 从 AGFS 读取 `/_system/accounts.json`,若不存在则创建 default account
- 遍历每个 account,读取 `/{account_id}/_system/users.json`
- 构建前缀索引:key 前 8 字符 → [UserKeyEntry]
-- 支持自动迁移:plaintext key → hashed key(当 encryption_enabled=True 时)
+- 支持自动迁移:plaintext key → hashed key(当 api_key_hashing_enabled=True 时)
**`resolve(api_key) -> ResolvedIdentity`**:
```
@@ -905,6 +928,7 @@ def require_role(*allowed_roles: Role):
if ctx.role not in allowed_roles:
raise PermissionDeniedError(f"Requires role: {allowed_roles}")
return ctx
+
return _check
```
@@ -963,6 +987,7 @@ async def ls(uri: str, _: bool = Depends(verify_api_key)):
result = await service.fs.ls(uri)
...
+
# Phase 1 改后(ctx 接收但不传递)
@router.get("/ls")
async def ls(uri: str, _ctx: RequestContext = Depends(get_request_context)):
@@ -1082,6 +1107,7 @@ HTTP 模式新增 `agent_id` 参数,通过 `X-OpenViking-Agent` header 发送
def __init__(self, url=None, api_key=None, agent_id=None):
self._agent_id = agent_id
+
# headers 构建
headers = {}
if self._api_key:
@@ -1239,18 +1265,19 @@ VikingFS 有以下公开方法需要加 `ctx: RequestContext` 参数:
```python
def _uri_to_path(self, uri: str, account_id: str = "") -> str:
- remainder = uri[len("viking://"):].strip("/")
+ remainder = uri[len("viking://") :].strip("/")
if account_id:
return f"/local/{account_id}/{remainder}" if remainder else f"/local/{account_id}"
return f"/local/{remainder}" if remainder else "/local"
+
def _path_to_uri(self, path: str, account_id: str = "") -> str:
if path.startswith("viking://"):
return path
elif path.startswith("/local/"):
inner = path[7:] # 去掉 /local/
if account_id and inner.startswith(account_id + "/"):
- inner = inner[len(account_id) + 1:] # 去掉 account_id 前缀
+ inner = inner[len(account_id) + 1 :] # 去掉 account_id 前缀
return f"viking://{inner}"
...
```
@@ -1290,8 +1317,8 @@ def _path_to_uri(self, path: str, account_id: str = "") -> str:
`openviking/core/context.py` 中 `Context` 类需增加两个字段:
```python
-account_id: str = "" # 所属 account
-owner_space: str = "" # 所有者的 user_space_name() 或 agent_space_name()
+account_id: str = "" # 所属 account
+owner_space: str = "" # 所有者的 user_space_name() 或 agent_space_name()
```
`to_dict()` 输出包含这两个字段,`EmbeddingMsgConverter.from_context()` 无需改动即可透传到 VectorDB。
@@ -1406,10 +1433,12 @@ async def initialize_account_directories(self, ctx: RequestContext) -> int:
"""初始化 account 级公共根目录"""
...
+
async def initialize_user_directories(self, ctx: RequestContext) -> int:
"""初始化 user space 子目录"""
...
+
async def initialize_agent_directories(self, ctx: RequestContext) -> int:
"""初始化 agent space 子目录"""
...
diff --git a/docs/en/guides/08-encryption.md b/docs/en/guides/08-encryption.md
index e7aaf297d..20995f9b1 100644
--- a/docs/en/guides/08-encryption.md
+++ b/docs/en/guides/08-encryption.md
@@ -66,6 +66,84 @@ asyncio.run(test())
Done! Now all written data is automatically encrypted.
+## API Key Hashing Configuration
+
+OpenViking provides two layers of encryption protection:
+
+| Encryption Layer | Config | Algorithm | Reversible | Description |
+|------------------|--------|-----------|------------|-------------|
+| **File Layer** | `encryption.enabled` | AES-GCM | ✅ Yes | Protects entire storage files |
+| **API Key Field Layer** | `encryption.api_key_hashing.enabled` | Argon2id | ❌ No | Protects API keys themselves |
+
+### ⚠️ Breaking Change Notice
+
+**Version Change**: OpenViking v0.3.12 → later versions
+
+**Behavior Change**:
+- **Before**: `encryption.enabled = true` implicitly enabled API key Argon2id hashing
+- **Now**: You must explicitly configure `encryption.api_key_hashing.enabled`
+
+**Impact**:
+- After upgrade, if `encryption.enabled = true` but `encryption.api_key_hashing.enabled` is not explicitly set to `true`, you will see the following warning log on startup:
+ ```
+ API key hashing is disabled while file encryption is enabled.
+ Previously, encryption.enabled=true implicitly enabled API key Argon2id hashing.
+ Now, API keys will be stored in plaintext within AES-GCM encrypted files.
+ To maintain the previous behavior, set encryption.api_key_hashing.enabled=true.
+ ```
+
+**Migration Options**:
+
+| Option | Config | Behavior |
+|--------|--------|----------|
+| **Maintain Previous Behavior** | `api_key_hashing.enabled = true` | API keys stored using Argon2id hashing |
+| **Recommended New Behavior** | `api_key_hashing.enabled = false` (default) | API keys stored in plaintext (file layer still encrypted) |
+
+### Default Behavior
+
+**By default, `encryption.api_key_hashing.enabled = false`**:
+- API keys are stored in plaintext within JSON files
+- If `encryption.enabled = true`, the entire file is protected by AES-GCM encryption
+- `ov admin list-users` can display the full API key
+
+### Enabling Argon2id Hashing
+
+For maximum API key protection, you can enable Argon2id one-way hashing:
+
+```json
+{
+ "encryption": {
+ "enabled": true,
+ "api_key_hashing": {
+ "enabled": true
+ }
+ }
+}
+```
+
+**Note**: When enabled:
+- API keys are stored using Argon2id one-way hashing
+- Plaintext keys cannot be recovered from hash values
+- `ov admin list-users` only shows `key_prefix` instead of the full API key
+- Plaintext keys are only visible when creating users or regenerating keys
+
+### Configuration Example
+
+```json
+{
+ "encryption": {
+ "enabled": true,
+ "provider": "local",
+ "local": {
+ "key_file": "~/.openviking/master.key"
+ },
+ "api_key_hashing": {
+ "enabled": false
+ }
+ }
+}
+```
+
## Choosing a Key Provider
| Provider | Use Case | Pros | Cons |
diff --git a/docs/zh/guides/08-encryption.md b/docs/zh/guides/08-encryption.md
index 9e8d60fb5..88313bd0c 100644
--- a/docs/zh/guides/08-encryption.md
+++ b/docs/zh/guides/08-encryption.md
@@ -66,6 +66,84 @@ asyncio.run(test())
完成!现在所有写入的数据都会自动加密。
+## API Key 哈希配置
+
+OpenViking 提供两层加密保护:
+
+| 加密层 | 配置项 | 算法 | 可逆性 | 说明 |
+|--------|--------|------|--------|------|
+| **文件层** | `encryption.enabled` | AES-GCM | ✅ 可逆 | 保护整个存储文件 |
+| **API key 字段层** | `encryption.api_key_hashing.enabled` | Argon2id | ❌ 不可逆 | 保护 API key 本身 |
+
+### ⚠️ Breaking Change 说明
+
+**版本变更**:OpenViking v0.3.12 → later versions
+
+**行为变化**:
+- **之前**:`encryption.enabled = true` 隐式启用 API key Argon2id 哈希
+- **现在**:需要显式配置 `encryption.api_key_hashing.enabled`
+
+**影响**:
+- 升级后,如果 `encryption.enabled = true` 但 `encryption.api_key_hashing.enabled` 未显式配置为 `true`,会在启动时看到以下警告日志:
+ ```
+ API key hashing is disabled while file encryption is enabled.
+ Previously, encryption.enabled=true implicitly enabled API key Argon2id hashing.
+ Now, API keys will be stored in plaintext within AES-GCM encrypted files.
+ To maintain the previous behavior, set encryption.api_key_hashing.enabled=true.
+ ```
+
+**迁移选项**:
+
+| 选项 | 配置 | 行为 |
+|------|------|------|
+| **保持原有行为** | `api_key_hashing.enabled = true` | API key 使用 Argon2id 哈希存储 |
+| **推荐新行为** | `api_key_hashing.enabled = false`(默认) | API key 明文存储(文件层仍加密) |
+
+### 默认行为
+
+**默认情况下,`encryption.api_key_hashing.enabled = false`**:
+- API key 以明文存储在 JSON 文件中
+- 如果 `encryption.enabled = true`,整个文件会被 AES-GCM 加密保护
+- `ov admin list-users` 可以显示完整的 API key
+
+### 启用 Argon2id 哈希
+
+如果需要最高级别的 API key 保护,可以启用 Argon2id 单向哈希:
+
+```json
+{
+ "encryption": {
+ "enabled": true,
+ "api_key_hashing": {
+ "enabled": true
+ }
+ }
+}
+```
+
+**注意**:启用后:
+- API key 使用 Argon2id 单向哈希存储
+- 无法从哈希值还原出明文 key
+- `ov admin list-users` 只显示 `key_prefix` 而不是完整的 API key
+- 只有在创建用户或重新生成 key 时才能看到明文 key
+
+### 配置示例
+
+```json
+{
+ "encryption": {
+ "enabled": true,
+ "provider": "local",
+ "local": {
+ "key_file": "~/.openviking/master.key"
+ },
+ "api_key_hashing": {
+ "enabled": false
+ }
+ }
+}
+```
+
## 密钥提供程序选择
| 提供程序 | 适用场景 | 优点 | 缺点 |
diff --git a/examples/ov.conf.example b/examples/ov.conf.example
index 08ba4cf44..7e3ee09a3 100644
--- a/examples/ov.conf.example
+++ b/examples/ov.conf.example
@@ -244,6 +244,9 @@
"provider": "local",
"local": {
"key_file": "~/.openviking/master.key"
+ },
+ "api_key_hashing": {
+ "enabled": false
}
},
"encryption_vault_example": {
diff --git a/openviking/server/api_keys/legacy.py b/openviking/server/api_keys/legacy.py
index d01539649..3d59cacef 100644
--- a/openviking/server/api_keys/legacy.py
+++ b/openviking/server/api_keys/legacy.py
@@ -51,18 +51,19 @@ class LegacyAPIKeyManager:
self,
root_key: str,
viking_fs: VikingFS,
- encryption_enabled: bool = False,
+ api_key_hashing_enabled: bool = False,
):
"""Initialize APIKeyManager.
Args:
root_key: Global root API key for administrative access.
viking_fs: VikingFS client for persistent storage of user keys.
- encryption_enabled: Whether API key hashing is enabled.
+ 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_key
self._viking_fs = viking_fs
- self._encryption_enabled = encryption_enabled
+ self._api_key_hashing_enabled = api_key_hashing_enabled
self._accounts: Dict[str, AccountInfo] = {}
# Prefix index: key_prefix -> list[UserKeyEntry]
self._prefix_index: Dict[str, list[UserKeyEntry]] = {}
@@ -115,8 +116,8 @@ class LegacyAPIKeyManager:
key_prefix = user_info.get("key_prefix", "")
else:
# Plaintext key
- if self._encryption_enabled:
- # If encryption enabled, migrate to hashed
+ if self._api_key_hashing_enabled:
+ # If API key hashing enabled, migrate to hashed
stored_key = self._hash_api_key(key_or_hash)
is_hashed = True
key_prefix = self._get_key_prefix(key_or_hash)
@@ -128,7 +129,7 @@ class LegacyAPIKeyManager:
"Migrated API key for user %s in account %s", user_id, account_id
)
else:
- # If encryption not enabled, keep as plaintext
+ # If API key hashing not enabled, keep as plaintext
stored_key = key_or_hash
is_hashed = False
# For plaintext keys, compute prefix on the fly for indexing
@@ -236,7 +237,7 @@ class LegacyAPIKeyManager:
key = self._generate_api_key()
policy = namespace_policy or AccountNamespacePolicy()
- if self._encryption_enabled:
+ if self._api_key_hashing_enabled:
stored_key = self._hash_api_key(key)
is_hashed = True
key_prefix = self._get_key_prefix(key)
@@ -249,7 +250,7 @@ class LegacyAPIKeyManager:
"role": "admin",
"key": stored_key,
}
- if self._encryption_enabled:
+ if self._api_key_hashing_enabled:
user_info["key_prefix"] = key_prefix
self._accounts[account_id] = AccountInfo(
@@ -319,7 +320,7 @@ class LegacyAPIKeyManager:
key = self._generate_api_key()
- if self._encryption_enabled:
+ if self._api_key_hashing_enabled:
stored_key = self._hash_api_key(key)
is_hashed = True
key_prefix = self._get_key_prefix(key)
@@ -332,7 +333,7 @@ class LegacyAPIKeyManager:
"role": role,
"key": stored_key,
}
- if self._encryption_enabled:
+ if self._api_key_hashing_enabled:
user_info["key_prefix"] = key_prefix
account.users[user_id] = user_info
@@ -413,7 +414,7 @@ class LegacyAPIKeyManager:
# Generate new key
new_key = self._generate_api_key()
- if self._encryption_enabled:
+ 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)
@@ -424,10 +425,10 @@ class LegacyAPIKeyManager:
# Update user info
account.users[user_id]["key"] = new_stored_key
- if self._encryption_enabled:
+ if self._api_key_hashing_enabled:
account.users[user_id]["key_prefix"] = new_key_prefix
else:
- # Remove key_prefix if encryption is disabled
+ # Remove key_prefix if API key hashing is disabled
if "key_prefix" in account.users[user_id]:
del account.users[user_id]["key_prefix"]
@@ -535,6 +536,7 @@ class LegacyAPIKeyManager:
if key:
if key.startswith("$argon2"):
# Hashed key - show key_prefix
+
key_prefix = user_info.get("key_prefix")
if key_prefix:
user_data["key_prefix"] = key_prefix
diff --git a/openviking/server/api_keys/new.py b/openviking/server/api_keys/new.py
index 9a3d83cf2..9d62392f4 100644
--- a/openviking/server/api_keys/new.py
+++ b/openviking/server/api_keys/new.py
@@ -81,17 +81,20 @@ class NewAPIKeyManager:
self,
root_key: str,
viking_fs: VikingFS,
- encryption_enabled: bool = False,
+ api_key_hashing_enabled: bool = False,
):
"""Initialize NewAPIKeyManager.
Args:
root_key: Global root API key for administrative access.
viking_fs: VikingFS client for persistent storage of user keys.
- encryption_enabled: Whether API key hashing is enabled.
+ api_key_hashing_enabled: Whether API key Argon2id hashing is enabled.
+ Default: false - rely on file-level AES encryption for protection.
"""
# Delegate to legacy manager for all core functionality
- self._legacy = LegacyAPIKeyManager(root_key, viking_fs, encryption_enabled)
+ 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."""
@@ -194,7 +197,7 @@ class NewAPIKeyManager:
now = datetime.now(timezone.utc).isoformat()
- if self._legacy._encryption_enabled:
+ if self._legacy._api_key_hashing_enabled:
stored_key = self._legacy._hash_api_key(key)
is_hashed = True
key_prefix = self._legacy._get_key_prefix(key)
@@ -207,7 +210,7 @@ class NewAPIKeyManager:
"role": "admin",
"key": stored_key,
}
- if self._legacy._encryption_enabled:
+ if self._legacy._api_key_hashing_enabled:
user_info["key_prefix"] = key_prefix
# Add to legacy's data structures
@@ -260,7 +263,7 @@ class NewAPIKeyManager:
# Generate new format key
key = generate_api_key(account_id, user_id)
- if self._legacy._encryption_enabled:
+ if self._legacy._api_key_hashing_enabled:
stored_key = self._legacy._hash_api_key(key)
is_hashed = True
key_prefix = self._legacy._get_key_prefix(key)
@@ -273,7 +276,7 @@ class NewAPIKeyManager:
"role": role,
"key": stored_key,
}
- if self._legacy._encryption_enabled:
+ if self._legacy._api_key_hashing_enabled:
user_info["key_prefix"] = key_prefix
account.users[user_id] = user_info
@@ -335,7 +338,7 @@ class NewAPIKeyManager:
# Generate new key in new format
new_key = generate_api_key(account_id, user_id)
- if self._legacy._encryption_enabled:
+ if self._legacy._api_key_hashing_enabled:
new_stored_key = self._legacy._hash_api_key(new_key)
new_is_hashed = True
new_key_prefix = self._legacy._get_key_prefix(new_key)
@@ -346,7 +349,7 @@ class NewAPIKeyManager:
# Update user info
account.users[user_id]["key"] = new_stored_key
- if self._legacy._encryption_enabled:
+ if self._legacy._api_key_hashing_enabled:
account.users[user_id]["key_prefix"] = new_key_prefix
else:
if "key_prefix" in account.users[user_id]:
@@ -422,8 +425,8 @@ class NewAPIKeyManager:
return self._legacy._root_key
@property
- def _encryption_enabled(self):
- return self._legacy._encryption_enabled
+ def _api_key_hashing_enabled(self):
+ return self._legacy._api_key_hashing_enabled
# ---- Helper method proxies for backward compatibility ----
diff --git a/openviking/server/app.py b/openviking/server/app.py
index 8c04d136e..d8941fa04 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -87,13 +87,13 @@ def create_app(
api_key_manager = APIKeyManager(
root_key=config.root_api_key,
viking_fs=service.viking_fs,
- encryption_enabled=config.encryption_enabled,
+ api_key_hashing_enabled=config.api_key_hashing_enabled,
)
await api_key_manager.load()
app.state.api_key_manager = api_key_manager
logger.info(
- "APIKeyManager initialized with encryption_enabled=%s",
- config.encryption_enabled,
+ "APIKeyManager initialized with api_key_hashing_enabled=%s",
+ config.api_key_hashing_enabled,
)
elif effective_auth_mode == AuthMode.TRUSTED:
app.state.api_key_manager = None
diff --git a/openviking/server/config.py b/openviking/server/config.py
index 6f1153192..546408805 100644
--- a/openviking/server/config.py
+++ b/openviking/server/config.py
@@ -103,7 +103,8 @@ class ServerConfig(BaseModel):
cors_origins: List[str] = Field(default_factory=lambda: ["*"])
with_bot: bool = False # Enable Bot API proxy to Vikingbot
bot_api_url: str = "http://localhost:18790" # Vikingbot OpenAPIChannel URL (default port)
- encryption_enabled: bool = False # Whether API key hashing is enabled
+ encryption_enabled: bool = False # Whether file-level AES encryption is enabled
+ api_key_hashing_enabled: bool = False # Whether API key Argon2id hashing is enabled (default: false, rely on file encryption)
observability: ObservabilityConfig = Field(default_factory=ObservabilityConfig)
model_config = {"extra": "forbid"}
@@ -172,6 +173,24 @@ def load_server_config(config_path: Optional[str] = None) -> ServerConfig:
# Get encryption enabled from config data directly (for test compatibility)
encryption_enabled = data.get("encryption", {}).get("enabled", False)
+ # Get API key hashing enabled from config data directly (under encryption namespace)
+ # Default: false - rely on file-level encryption for API key protection
+ api_key_hashing_enabled = (
+ data.get("encryption", {}).get("api_key_hashing", {}).get("enabled", False)
+ )
+
+ # BREAKING CHANGE: Previously, encryption.enabled=true implicitly enabled API key Argon2id hashing.
+ # Now, you must explicitly configure encryption.api_key_hashing.enabled=true to enable hashing.
+ # When encryption.enabled=true but api_key_hashing.enabled=false (default),
+ # API keys will be stored in plaintext within AES-GCM encrypted files.
+ if encryption_enabled and not api_key_hashing_enabled:
+ logger.info(
+ "API key hashing is disabled while file encryption is enabled. "
+ "Previously, encryption.enabled=true implicitly enabled API key Argon2id hashing. "
+ "Now, API keys will be stored in plaintext within AES-GCM encrypted files. "
+ "To maintain the previous behavior, set encryption.api_key_hashing.enabled=true. "
+ "See documentation for more details."
+ )
try:
config = ServerConfig.model_validate(server_data)
@@ -181,7 +200,12 @@ def load_server_config(config_path: Optional[str] = None) -> ServerConfig:
f"{format_validation_error(root_model=ServerConfig, error=e, path_prefix='server')}"
) from e
- return config.model_copy(update={"encryption_enabled": encryption_enabled})
+ return config.model_copy(
+ update={
+ "encryption_enabled": encryption_enabled,
+ "api_key_hashing_enabled": api_key_hashing_enabled,
+ }
+ )
_LOCALHOST_HOSTS = {"127.0.0.1", "localhost", "::1"}
diff --git a/openviking_cli/utils/config/encryption_config.py b/openviking_cli/utils/config/encryption_config.py
index 2fb3f60d0..7ec227a04 100644
--- a/openviking_cli/utils/config/encryption_config.py
+++ b/openviking_cli/utils/config/encryption_config.py
@@ -45,6 +45,23 @@ class VolcengineKMSEncryptionProviderConfig(BaseModel):
secret_key: Optional[str] = Field(default=None, description="Volcengine secret access key")
+class APIKeyHashingConfig(BaseModel):
+ """API key hashing configuration.
+
+ Controls whether API keys are hashed using Argon2id before storage.
+ When disabled (default), API keys are stored in plaintext within
+ AES-GCM encrypted files, allowing admin users to retrieve full keys.
+ When enabled, API keys are hashed with Argon2id (one-way),
+ providing maximum security but preventing key recovery.
+ """
+
+ enabled: bool = Field(
+ default=False,
+ description="Whether API key Argon2id hashing is enabled. "
+ "Default: false - rely on file-level AES encryption for protection.",
+ )
+
+
class EncryptionConfig(BaseModel):
"""Configuration for encryption module.
@@ -98,6 +115,12 @@ class EncryptionConfig(BaseModel):
description="Volcengine KMS provider configuration",
)
+ api_key_hashing: APIKeyHashingConfig = Field(
+ default_factory=APIKeyHashingConfig,
+ description="API key hashing configuration. "
+ "Controls whether API keys are hashed using Argon2id before storage.",
+ )
+
params: Dict[str, Any] = Field(
default_factory=dict, description="Additional encryption-specific parameters"
)
diff --git a/tests/server/test_api_key_manager.py b/tests/server/test_api_key_manager.py
index 833a7690c..b86a1fb21 100644
--- a/tests/server/test_api_key_manager.py
+++ b/tests/server/test_api_key_manager.py
@@ -264,10 +264,10 @@ async def test_legacy_account_without_settings_infers_user_and_agent_policy(mana
async def test_create_account_with_encryption_enabled(manager_service):
- """create_account with encryption_enabled=True should create hashed keys."""
+ """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, encryption_enabled=True
+ root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=True
)
await mgr.load()
@@ -287,10 +287,10 @@ async def test_create_account_with_encryption_enabled(manager_service):
async def test_register_user_with_encryption_enabled(manager_service):
- """register_user with encryption_enabled=True should create hashed keys."""
+ """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, encryption_enabled=True
+ root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=True
)
await mgr.load()
@@ -308,10 +308,10 @@ async def test_register_user_with_encryption_enabled(manager_service):
async def test_regenerate_key_with_encryption_enabled(manager_service):
- """regenerate_key with encryption_enabled=True should create new hashed key."""
+ """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, encryption_enabled=True
+ root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=True
)
await mgr.load()
@@ -341,19 +341,19 @@ async def test_regenerate_key_with_encryption_enabled(manager_service):
async def test_migrate_plaintext_keys_to_encrypted(manager_service):
- """Keys created with encryption disabled should be migrated when encryption is enabled."""
+ """Keys created with api_key_hashing disabled should be migrated when api_key_hashing is enabled."""
acct = _uid()
- # First, create a key with encryption disabled
+ # First, create a key with api_key_hashing disabled
mgr1 = APIKeyManager(
- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, encryption_enabled=False
+ 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 encryption enabled - should migrate the key
+ # Now, reload with api_key_hashing enabled - should migrate the key
mgr2 = APIKeyManager(
- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, encryption_enabled=True
+ root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=True
)
await mgr2.load()
@@ -366,7 +366,7 @@ async def test_migrate_plaintext_keys_to_encrypted(manager_service):
async def test_persistence_with_encryption_enabled(manager_service):
"""Hashed keys should survive manager reload from AGFS."""
mgr1 = APIKeyManager(
- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, encryption_enabled=True
+ root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=True
)
await mgr1.load()
@@ -379,7 +379,7 @@ async def test_persistence_with_encryption_enabled(manager_service):
# Create new manager instance and reload
mgr2 = APIKeyManager(
- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, encryption_enabled=True
+ root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=True
)
await mgr2.load()
@@ -514,7 +514,7 @@ async def test_regenerate_key_upgrades_to_new_format(manager_service):
# First create a legacy key using LegacyAPIKeyManager
legacy_mgr = LegacyAPIKeyManager(
- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, encryption_enabled=False
+ 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")
@@ -523,7 +523,7 @@ async def test_regenerate_key_upgrades_to_new_format(manager_service):
# Now load with NewAPIKeyManager and regenerate
new_mgr = APIKeyManager(
- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, encryption_enabled=False
+ root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=False
)
await new_mgr.load()
@@ -556,7 +556,7 @@ async def test_mixed_key_formats(manager_service):
# Create account with legacy manager
legacy_mgr = LegacyAPIKeyManager(
- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, encryption_enabled=False
+ 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")
@@ -564,7 +564,7 @@ async def test_mixed_key_formats(manager_service):
# Add another user with new format using NewAPIKeyManager
new_mgr = APIKeyManager(
- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, encryption_enabled=False
+ 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")
@@ -584,7 +584,7 @@ async def test_new_format_with_encryption(manager_service):
acct = _uid()
mgr = APIKeyManager(
- root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, encryption_enabled=True
+ root_key=ROOT_KEY, viking_fs=manager_service.viking_fs, api_key_hashing_enabled=True
)
await mgr.load()