Skip to content

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

fix(auth): reveal only the caller's own user API key in admin listings (#6610)

MaojiaShengd6271e630b04
diff --git a/crates/ov_cli/src/commands/admin.rs b/crates/ov_cli/src/commands/admin.rs
index 4d33b9628..fa8eb282e 100644
--- a/crates/ov_cli/src/commands/admin.rs
+++ b/crates/ov_cli/src/commands/admin.rs
@@ -5,7 +5,7 @@ use crate::theme;
use colored::Colorize;
use serde_json::{Value, json};
-const SECRET_PLACEHOLDER: &str = "********";
+const SECRET_MASK_NOTICE: &str = "Note: API keys are masked by default. Pass --reveal-api-keys to reveal plaintext (ROOT sees every key; ADMIN/USER only its own).";
pub async fn create_account(
client: &HttpClient,
@@ -104,13 +104,20 @@ pub async fn list_users(
name: Option<String>,
role: Option<String>,
page: u32,
+ reveal_api_keys: bool,
output_format: OutputFormat,
compact: bool,
) -> Result<()> {
let response = client
.admin_list_users(account_id, limit, name, role, page)
.await?;
- let response = list_users_response_for_output(response, output_format);
+ let (mut response, masked) = list_users_response_for_output(response, reveal_api_keys);
+ if matches!(output_format, OutputFormat::Table) {
+ merge_key_prefix_into_api_key(&mut response);
+ }
+ if masked {
+ eprintln!("{SECRET_MASK_NOTICE}");
+ }
output_success(&response, output_format, compact);
Ok(())
}
@@ -348,37 +355,88 @@ fn contains_non_empty_user_key(value: &Value) -> bool {
}
}
-fn list_users_response_for_output(mut response: Value, output_format: OutputFormat) -> Value {
- if matches!(output_format, OutputFormat::Table) {
- redact_plaintext_api_keys(&mut response);
+fn list_users_response_for_output(mut response: Value, reveal_api_keys: bool) -> (Value, bool) {
+ if reveal_api_keys {
+ return (response, false);
+ }
+ let masked = mask_plaintext_api_keys(&mut response);
+ (response, masked)
+}
+
+/// Collapse the server's `key_prefix`/`api_key` fields into a single `api_key`
+/// table column; the JSON response shape is left untouched.
+fn merge_key_prefix_into_api_key(value: &mut Value) {
+ fn normalize_row(row: &mut Value) {
+ let Some(object) = row.as_object_mut() else {
+ return;
+ };
+ if !object.contains_key("api_key") {
+ if let Some(prefix) = object.remove("key_prefix") {
+ object.insert("api_key".to_string(), prefix);
+ }
+ } else {
+ object.remove("key_prefix");
+ }
+ }
+ match value {
+ Value::Array(users) => users.iter_mut().for_each(normalize_row),
+ Value::Object(object) => {
+ if let Some(users) = object.get_mut("users").and_then(Value::as_array_mut) {
+ users.iter_mut().for_each(normalize_row);
+ }
+ }
+ _ => {}
}
- response
}
-fn redact_plaintext_api_keys(value: &mut Value) {
+fn mask_plaintext_api_keys(value: &mut Value) -> bool {
match value {
Value::Object(object) => {
+ let mut masked = false;
for (key, child) in object {
- if key == "api_key"
- && child
- .as_str()
- .is_some_and(|api_key| !api_key.trim().is_empty())
- {
- *child = Value::String(SECRET_PLACEHOLDER.to_string());
- } else {
- redact_plaintext_api_keys(child);
+ if key == "api_key" {
+ if let Some(api_key) = child.as_str() {
+ if !api_key.trim().is_empty() {
+ *child = Value::String(mask_api_key(api_key));
+ masked = true;
+ }
+ }
+ } else if mask_plaintext_api_keys(child) {
+ masked = true;
}
}
+ masked
}
Value::Array(items) => {
+ let mut masked = false;
for item in items {
- redact_plaintext_api_keys(item);
+ if mask_plaintext_api_keys(item) {
+ masked = true;
+ }
}
+ masked
}
- _ => {}
+ _ => false,
}
}
+/// Match `openviking/server/api_keys/new.py:mask_api_key` so CLI and API output look the same.
+fn mask_api_key(api_key: &str) -> String {
+ let parts: Vec<&str> = api_key.split('.').collect();
+ if api_key.is_empty() || parts.len() != 3 {
+ return "*".repeat(api_key.chars().count());
+ }
+
+ let secret_chars: Vec<char> = parts[2].chars().collect();
+ let visible_length = if secret_chars.len() > 4 { 4 } else { 0 };
+ let hidden_length = secret_chars.len() - visible_length;
+
+ let mut masked = format!("{}.{}.", parts[0], parts[1]);
+ masked.push_str(&"*".repeat(hidden_length));
+ masked.push_str(&secret_chars[hidden_length..].iter().collect::<String>());
+ masked
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -463,43 +521,139 @@ mod tests {
}
#[test]
- fn list_users_table_output_redacts_plaintext_api_keys() {
+ fn mask_api_key_matches_server_format() {
+ let cases = [
+ (
+ "YWNtZQ.YWxpY2U.abcdefghijklmnop",
+ "YWNtZQ.YWxpY2U.************mnop",
+ ),
+ ("YWNtZQ.YWxpY2U.abcdefgh", "YWNtZQ.YWxpY2U.****efgh"),
+ ("YWNtZQ.YWxpY2U.abcde", "YWNtZQ.YWxpY2U.*bcde"),
+ ("YWNtZQ.YWxpY2U.abcd", "YWNtZQ.YWxpY2U.****"),
+ ("YWNtZQ.YWxpY2U.a", "YWNtZQ.YWxpY2U.*"),
+ ("legacy-secret", "*************"),
+ ("two.parts", "*********"),
+ ("abcd", "****"),
+ ("a", "*"),
+ ];
+
+ for (key, expected) in cases {
+ assert_eq!(mask_api_key(key), expected, "masking {key}");
+ }
+ }
+
+ #[test]
+ fn list_users_table_output_masks_plaintext_api_keys() {
let response = json!([
- {"user_id": "alice", "role": "admin", "api_key": "plain-secret"},
+ {"user_id": "alice", "role": "admin", "api_key": "YWNtZQ.YWxpY2U.abcdefgh"},
{"user_id": "bob", "role": "user", "key_prefix": "prefix123"}
]);
- let sanitized = list_users_response_for_output(response, OutputFormat::Table);
+ let (sanitized, masked) = list_users_response_for_output(response, false);
+ assert!(masked);
assert_eq!(
sanitized,
json!([
- {"user_id": "alice", "role": "admin", "api_key": "********"},
+ {"user_id": "alice", "role": "admin", "api_key": "YWNtZQ.YWxpY2U.****efgh"},
{"user_id": "bob", "role": "user", "key_prefix": "prefix123"}
])
);
}
#[test]
- fn list_users_table_output_preserves_empty_api_keys() {
+ fn list_users_json_output_uses_the_same_masking() {
let response = json!([
- {"user_id": "alice", "role": "admin", "api_key": ""},
- {"user_id": "bob", "role": "user", "api_key": " "}
+ {"user_id": "alice", "role": "admin", "api_key": "YWNtZQ.YWxpY2U.abcdefgh"}
+ ]);
+
+ let (sanitized, masked) = list_users_response_for_output(response, false);
+
+ assert!(masked);
+ assert_eq!(
+ sanitized,
+ json!([
+ {"user_id": "alice", "role": "admin", "api_key": "YWNtZQ.YWxpY2U.****efgh"}
+ ])
+ );
+ }
+
+ #[test]
+ fn list_users_reveal_flag_preserves_plaintext_api_keys() {
+ let response = json!([
+ {"user_id": "alice", "role": "admin", "api_key": "YWNtZQ.YWxpY2U.abcdefgh"}
+ ]);
+
+ let (sanitized, masked) = list_users_response_for_output(response.clone(), true);
+
+ assert!(!masked);
+ assert_eq!(sanitized, response);
+ }
+
+ #[test]
+ fn list_users_admin_prefixes_are_not_remasked() {
+ let response = json!([
+ {"user_id": "alice", "role": "admin", "key_prefix": "YWNtZQ.YWxpY2U.****efgh"}
]);
- let sanitized = list_users_response_for_output(response.clone(), OutputFormat::Table);
+ let (sanitized, masked) = list_users_response_for_output(response.clone(), false);
+ assert!(!masked);
assert_eq!(sanitized, response);
}
#[test]
- fn list_users_json_output_preserves_plaintext_api_keys() {
+ fn list_users_table_merges_key_prefix_into_api_key_column() {
+ let mut response = json!([
+ {"user_id": "alice", "role": "admin", "api_key": "YWNtZQ.YWxpY2U.plaintext-secret"},
+ {"user_id": "bob", "role": "user", "key_prefix": "YWNtZQ.Ym9i.****wxyz"},
+ {"user_id": "carol", "role": "user"}
+ ]);
+
+ merge_key_prefix_into_api_key(&mut response);
+
+ assert_eq!(
+ response,
+ json!([
+ {"user_id": "alice", "role": "admin", "api_key": "YWNtZQ.YWxpY2U.plaintext-secret"},
+ {"user_id": "bob", "role": "user", "api_key": "YWNtZQ.Ym9i.****wxyz"},
+ {"user_id": "carol", "role": "user"}
+ ])
+ );
+ }
+
+ #[test]
+ fn list_users_table_merges_key_prefix_inside_summary_object() {
+ let mut response = json!({
+ "total": 1,
+ "users": [
+ {"user_id": "bob", "role": "user", "key_prefix": "YWNtZQ.Ym9i.****wxyz"}
+ ]
+ });
+
+ merge_key_prefix_into_api_key(&mut response);
+
+ assert_eq!(
+ response,
+ json!({
+ "total": 1,
+ "users": [
+ {"user_id": "bob", "role": "user", "api_key": "YWNtZQ.Ym9i.****wxyz"}
+ ]
+ })
+ );
+ }
+
+ #[test]
+ fn list_users_masking_preserves_empty_api_keys() {
let response = json!([
- {"user_id": "alice", "role": "admin", "api_key": "plain-secret"}
+ {"user_id": "alice", "role": "admin", "api_key": ""},
+ {"user_id": "bob", "role": "user", "api_key": " "}
]);
- let sanitized = list_users_response_for_output(response.clone(), OutputFormat::Json);
+ let (sanitized, masked) = list_users_response_for_output(response.clone(), false);
+ assert!(!masked);
assert_eq!(sanitized, response);
}
}
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index 4ca1ba961..5c2632176 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -648,6 +648,7 @@ pub async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {
name,
role,
page,
+ reveal_api_keys,
} => {
commands::admin::list_users(
&client,
@@ -656,6 +657,7 @@ pub async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {
name,
role,
page,
+ reveal_api_keys,
ctx.output_format,
ctx.compact,
)
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 45148da0d..521a1176b 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -2185,6 +2185,9 @@ enum AdminCommands {
/// 1-based page number (requires --limit)
#[arg(long, default_value = "1", value_name = "n")]
page: u32,
+ /// Show plaintext API keys instead of masked values (ROOT sees all keys; ADMIN/USER only its own)
+ #[arg(long)]
+ reveal_api_keys: bool,
},
/// Create an empty account-scoped group
CreateGroup {
diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.md
index 4ceb5d013..387262c7a 100644
--- a/docs/en/api/08-admin.md
+++ b/docs/en/api/08-admin.md
@@ -1593,7 +1593,7 @@ List active users in a workspace. Users with deletion in progress are omitted.
2. Call API Key Manager to get active users list (in creation order)
3. Apply optional filters (name, role)
4. Apply optional `limit`/`page` pagination
-5. Return users list (trusted mode omits user_key)
+5. Return users list with role-based credential visibility (trusted mode omits credentials)
**Code Entry Points:**
- `openviking/server/routers/admin.py:list_users` - HTTP route
@@ -1611,14 +1611,18 @@ 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. `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. |
+| include_credentials | bool | No | true | HTTP-only. ROOT receives all available plaintext keys; ADMIN receives its own plaintext key and masked prefixes for other users. 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. |
| 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 |
**Notes:**
- Results are returned in creation order
- ADMIN can only list users in their own account
-- In `trusted` mode, `user_key` is omitted from the response
+- ROOT receives every stored key as plaintext in `api_key`. A non-ROOT caller receives plaintext in `api_key` only for its own row; every other user (including other ADMIN users) is returned as a masked `key_prefix`. Self-matching is strict: the listing account, the row's user ID, and the account/user segments embedded in the three-segment key must all equal the caller's authenticated identity; otherwise the row is masked. Three-segment keys retain the first two segments and only the last four characters of the secret segment; every preceding secret character is replaced by `*`. Secrets of four characters or fewer are completely hidden. Keys that are not in the three-segment format are fully masked. Hash-only credentials retain their existing prefix.
+- Masking is enforced by the server for HTTP and MCP `list_users(include_credentials=true)`, so it also applies to CLI/SDK JSON output. Clients must treat `key_prefix` as display-only and require a supplied key to switch identities.
+- `ov admin list-users` additionally masks the plaintext `api_key` rows client-side by default, in both table and JSON output, and prints a notice on stderr. Pass `--reveal-api-keys` to emit plaintext: ROOT then shows every key, while an ADMIN/USER caller still sees only its own key (other rows are masked by the server). The flag affects CLI rendering only and does not change the server response. In table output the server's `api_key` (plaintext or client-masked) and `key_prefix` fields are merged into a single `api_key` column; JSON output keeps the server field names.
+- This restriction applies to stored-key listing. Registration and key regeneration still return the newly issued key to ROOT or ADMIN; ordinary USER self-service key rotation is not yet available.
+- In `trusted` mode, both `api_key` and `key_prefix` are omitted from the response
- Users whose deletion has started are no longer returned
**Summary responses (HTTP):** Set `include_summary=true` to return an object in `result` with `users` (the current page), `total` (matching users), `account_total`, `manager_count` (admin/root), and `key_count` (users with a visible key or prefix). Account statistics ignore search/role filters and exclude deleting users; `key_count` is zero when key exposure is disabled. The default remains a user array for existing callers.
@@ -1688,6 +1692,8 @@ fmt.Println(users)
ov admin list-users acme
# If using root_api_key (--sudo):
ov --sudo admin list-users acme
+# Show plaintext keys instead of masked values (ROOT: all keys; ADMIN/USER: own key only)
+ov --sudo admin list-users acme --reveal-api-keys
# Filter by wildcard name
ov admin list-users acme --name '*ali*'
# Paginated
diff --git a/docs/en/guides/04-authentication.md b/docs/en/guides/04-authentication.md
index f416bd86c..2dae1a4cb 100644
--- a/docs/en/guides/04-authentication.md
+++ b/docs/en/guides/04-authentication.md
@@ -52,6 +52,8 @@ openviking-server
User keys are generated by the Admin API. By default they use random secret material; Admin API callers may also provide a `seed` to derive a predictable key secret from `sha256(user_id + "\0" + seed)`. The server still verifies the resulting key against the stored key or key hash.
+User keys use the three-segment format `base64url(account).base64url(user).base64url(secret)`. Only this format is accepted; bare or otherwise malformed keys are rejected with `401 Invalid API key`.
+
### Managing Accounts and Users
Use the root key to create accounts (workspaces) and users via the Admin API:
diff --git a/docs/en/guides/06-mcp-integration.md b/docs/en/guides/06-mcp-integration.md
index 81fefc928..434ee366a 100644
--- a/docs/en/guides/06-mcp-integration.md
+++ b/docs/en/guides/06-mcp-integration.md
@@ -215,7 +215,9 @@ not echo resolved secrets in chat. Tree and upsert return no stored values.
All account users may call `list_users` and `list_groups`; neither tool accepts a different account.
The default output contains only user IDs and a matching total, or group IDs. Even administrators
-must explicitly set `include_credentials=true` to include available credentials. A USER requesting
+must explicitly set `include_credentials=true` to include credential fields: ROOT receives
+every available plaintext key in `api_key`; ADMIN receives its own plaintext key and masked
+`key_prefix` values for every other user. A USER requesting
credentials receives `PERMISSION_DENIED`, even when the query matches no users. Trusted auth mode
forbids credential disclosure. Group membership remains available through the admin API.
diff --git a/docs/en/guides/08-encryption.md b/docs/en/guides/08-encryption.md
index ea971ce81..9f3a28ba1 100644
--- a/docs/en/guides/08-encryption.md
+++ b/docs/en/guides/08-encryption.md
@@ -101,7 +101,7 @@ File encryption and API key hashing are independent controls:
**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
+- `ov admin list-users` can display the full API key when run with `--reveal-api-keys`
- If `encryption.enabled = true` and API key hashing stays disabled, the server writes an informational log line about this at startup
### Enabling Argon2id Hashing
@@ -122,7 +122,7 @@ Enable Argon2id one-way hashing to stop storing recoverable API key values:
**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
+- `ov admin list-users` only shows `key_prefix` instead of the full API key (a caller's own row cannot be revealed either, since no plaintext is stored)
- Plaintext keys are only visible when creating users or regenerating keys
### Configuration Example
diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.md
index a3d98d18a..3b0bd6b18 100644
--- a/docs/zh/api/08-admin.md
+++ b/docs/zh/api/08-admin.md
@@ -1449,7 +1449,7 @@ ov admin register-user acme bob-private --role user \
2. 调用 API Key Manager 获取活跃用户列表(按创建顺序排列)
3. 应用可选的过滤条件(name、role)
4. 应用可选的 `limit`/`page` 分页
-5. 返回用户列表(trusted 模式下不包含 user_key)
+5. 按调用者角色返回密钥信息(trusted 模式下不包含密钥信息)
**代码入口:**
- `openviking/server/routers/admin.py:list_users` - HTTP 路由
@@ -1467,14 +1467,18 @@ 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`,不返回密钥或前缀;仅当服务端能读取完整 key 并用于服务端绑定时 `api_key_available` 才为 true,仅存哈希的凭据返回 false;默认保持现有按鉴权模式返回字段的行为。 |
+| include_credentials | bool | 否 | true | 仅 HTTP。ROOT 可获取可用的明文密钥,ADMIN 仅获取打码后的前缀。设为 false 时仅返回 `user_id`、`role` 和 `api_key_available`,不返回密钥或前缀;仅当服务端能读取完整 key 并用于服务端绑定时 `api_key_available` 才为 true,仅存哈希的凭据返回 false。 |
| limit | int | 否 | null | 每页数量(≥1)。省略则返回所有匹配项 |
| page | int | 否 | 1 | 从 1 开始的页码;仅在设置了 `limit` 时生效 |
**说明:**
- 结果按创建顺序返回
- ADMIN 只能列出自己所属的 account 中的用户
-- 在 `trusted` 模式下,响应中不会包含 `user_key` 字段
+- ROOT 可通过 `api_key` 获取全部已存储的明文密钥。非 ROOT 调用方只有自身那一行返回 `api_key` 明文,其他用户(包括其他 ADMIN)均返回打码后的 `key_prefix`。自身匹配是严格匹配:列表 account、行内 user ID 以及三段式 key 内嵌的 account/user 段必须全部等于调用方认证身份,否则该行仍打码。三段式密钥保留前两段和 secret 的最后 4 个字符,secret 中其余每个字符均替换为 `*`;secret 不超过 4 个字符时完全隐藏。非三段式密钥完全隐藏;仅存哈希的凭据沿用已有前缀。
+- 打码在服务端执行,同时覆盖 HTTP 和 MCP 的 `list_users(include_credentials=true)`,因此 CLI/SDK 的 JSON 输出也受保护。客户端只能将 `key_prefix` 用于展示,切换身份时需要另行提供可用密钥。
+- `ov admin list-users` 默认还会在 CLI 侧对明文 `api_key` 行使用相同格式打码,table 和 JSON 输出保持一致,并在 stderr 打印提示。传入 `--reveal-api-keys` 可输出明文:ROOT 会显示全部密钥,ADMIN/USER 调用方仍只能看到自身密钥(其他行由服务端打码)。该 flag 只影响 CLI 渲染,不改变服务端响应。table 输出会把服务端的 `api_key`(明文或 CLI 打码值)与 `key_prefix` 合并为同一个 `api_key` 列;JSON 输出保留服务端的字段名。
+- 本限制针对已存储密钥的列表浏览。创建用户与重置密钥仍会向 ROOT 或 ADMIN 返回新密钥;普通 USER 尚无自助轮换接口。
+- 在 `trusted` 模式下,响应中不会包含 `api_key` 或 `key_prefix` 字段
- 用户删除开始后,不再出现在该列表中
**带统计的响应(HTTP):** 设置 `include_summary=true` 后,`result` 返回对象:`users` 为当前页,`total` 为匹配人数,`account_total` 为账号总人数,`manager_count` 为 admin/root 人数,`key_count` 为具有可见密钥或前缀的用户数。账号统计不受搜索和角色过滤影响,并排除正在删除的用户;禁用密钥展示时 `key_count` 为零。默认仍返回用户数组,兼容现有调用。
@@ -1544,6 +1548,8 @@ fmt.Println(users)
ov admin list-users acme
# 如果使用 root_api_key(--sudo):
ov --sudo admin list-users acme
+# 输出明文密钥而不是打码值(仅 ROOT)
+ov --sudo admin list-users acme --reveal-api-keys
# 按通配符 name 过滤
ov admin list-users acme --name '*ali*'
# 分页
diff --git a/docs/zh/guides/04-authentication.md b/docs/zh/guides/04-authentication.md
index db6135039..e46592130 100644
--- a/docs/zh/guides/04-authentication.md
+++ b/docs/zh/guides/04-authentication.md
@@ -51,6 +51,8 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \
创建账号后,保存响应中的 `user_key`,将它用于 CLI、SDK 和数据 API。root key 不用于租户数据读写。
+User key 采用三段式格式 `base64url(account).base64url(user).base64url(secret)`。服务端只接受该格式;裸密钥或其他格式一律以 `401 Invalid API key` 拒绝。
+
### 方案二:OIDC(企业 SSO)
OIDC 和 LDAP 需要可选认证依赖。在运行服务端的 Python 环境中安装:
diff --git a/docs/zh/guides/06-mcp-integration.md b/docs/zh/guides/06-mcp-integration.md
index da7a43749..cc8db58e2 100644
--- a/docs/zh/guides/06-mcp-integration.md
+++ b/docs/zh/guides/06-mcp-integration.md
@@ -203,7 +203,8 @@ tree 和 resolve 标记为只读,upsert 标记为可能覆盖数据的写入
`list_users`、`list_groups` 对当前 account 的普通用户开放,不接受跨 account 查询参数。
`list_users` 默认仅返回 `user_id` 和匹配总数,`list_groups` 仅返回 `group_id`。
-管理员也必须显式传 `include_credentials=true` 才会返回可用的凭证字段;普通用户传该参数会得到
+管理员也必须显式传 `include_credentials=true` 才会返回凭证字段:ROOT 可获得全部 `api_key` 明文,
+ADMIN 仅自身记录为 `api_key` 明文,其他用户一律为打码后的 `key_prefix`;普通用户传该参数会得到
`PERMISSION_DENIED`,即使查询结果为空也一样。trusted 鉴权模式禁止返回凭证。
组成员管理和成员名单查询仍使用管理员接口。
diff --git a/docs/zh/guides/08-encryption.md b/docs/zh/guides/08-encryption.md
index 4c1efffc2..6c47a83df 100644
--- a/docs/zh/guides/08-encryption.md
+++ b/docs/zh/guides/08-encryption.md
@@ -101,7 +101,7 @@ test()
**默认情况下,`encryption.api_key_hashing.enabled = false`**:
- API key 以明文存储在 JSON 文件中
- 如果 `encryption.enabled = true`,整个文件会被 AES-GCM 加密保护
-- `ov admin list-users` 可以显示完整的 API key
+- `ov admin list-users` 传入 `--reveal-api-keys` 后可以显示完整的 API key
- 如果 `encryption.enabled = true` 且未启用 API key 哈希,服务端启动时会输出一条说明此情况的 INFO 日志
### 启用 Argon2id 哈希
@@ -122,7 +122,7 @@ test()
**注意**:启用后:
- API key 使用 Argon2id 单向哈希存储
- 无法从哈希值还原出明文 key
-- `ov admin list-users` 只显示 `key_prefix` 而不是完整的 API key
+- `ov admin list-users` 只显示 `key_prefix` 而不是完整的 API key(调用方自身的行也无法显示明文,因为服务端未存储明文)
- 只有在创建用户或重新生成 key 时才能看到明文 key
### 配置示例
diff --git a/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs b/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs
index 107ed1db1..f1278aff7 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs
@@ -171,7 +171,7 @@ function headTail(value, keep = 4) {
* Describe an API key for display without revealing it.
*
* three-segment key → account=<decoded> user=<decoded> secret=abcd…wxyz
- * single-segment key → abcd…wxyz (64 chars, legacy format)
+ * other shapes → abcd…wxyz (N chars, unsupported format)
*
* The three-segment format is base64url(account).base64url(user).base64url(secret);
* the first two segments carry no secret and are decoded so the operator can see
@@ -203,9 +203,9 @@ export function describeApiKey(rawKey) {
if (!parts[2]) info.problems.push("secret segment is empty");
info.display = `account=${accountText} user=${userText} secret=${headTail(parts[2])}`;
} else {
- info.format = "legacy";
- if (parts.length !== 1) info.problems.push(`unexpected shape: ${parts.length} dot-separated segments (expected 1 or 3)`);
- info.display = `${headTail(key)} (${key.length} chars, ${parts.length === 1 ? "legacy single-segment" : "unrecognised"} format)`;
+ info.format = "unsupported";
+ info.problems.push(`unsupported shape: ${parts.length} dot-separated segment(s); expected 3`);
+ info.display = `${headTail(key)} (${key.length} chars, unsupported format)`;
}
return info;
}
diff --git a/examples/claude-code-memory-plugin/skills/ov-memory-doctor/SKILL.md b/examples/claude-code-memory-plugin/skills/ov-memory-doctor/SKILL.md
index 140de38f2..0e742e9fd 100644
--- a/examples/claude-code-memory-plugin/skills/ov-memory-doctor/SKILL.md
+++ b/examples/claude-code-memory-plugin/skills/ov-memory-doctor/SKILL.md
@@ -64,8 +64,8 @@ rerun it from the path it prints — Claude Code executes hooks from that copy.
The API key is never printed in full. Three-segment keys are shown as
`account=<a> user=<u> secret=abcd…wxyz` (the first two segments are just
base64url identity, decoded so the user can see which account/user the key
-claims); legacy keys as `abcd…wxyz (64 chars)`. Keep it that way in anything
-you show the user.
+claims). Other shapes are shown as `abcd…wxyz (N chars, unsupported format)`.
+Keep it that way in anything you show the user.
## Step 2 — map findings to causes
diff --git a/examples/claude-code-memory-plugin/skills/ov-memory-doctor/reference.md b/examples/claude-code-memory-plugin/skills/ov-memory-doctor/reference.md
index 04c78ecc9..3b900deb1 100644
--- a/examples/claude-code-memory-plugin/skills/ov-memory-doctor/reference.md
+++ b/examples/claude-code-memory-plugin/skills/ov-memory-doctor/reference.md
@@ -83,10 +83,9 @@ That file and the registry file whose path the doctor prints are the whole surfa
| `api_key` | key required | from the key; account/user headers are silently stripped |
| `trusted` | root key optional | from the headers; missing → 400 `Trusted mode requests must include X-OpenViking-Account …` |
-Key formats: `base64url(account).base64url(user).base64url(secret)` (three
-segments, identity readable) or a bare 64-hex legacy key (identity only via
-server lookup). Both fail identically as `401 Invalid API Key` when unknown —
-there is no "wrong account" error.
+Key format: `base64url(account).base64url(user).base64url(secret)` (three
+segments, identity readable). Other shapes are rejected as
+`401 Invalid API Key` — there is no "wrong account" error.
`role: root` keys are allowed only on `/api/v1/system/status`, `/api/v1/admin/*`,
`/api/v1/observer/*`, `/api/v1/tasks/*` and a few system paths; everything the
diff --git a/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs b/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs
index 107ed1db1..f1278aff7 100644
--- a/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs
@@ -171,7 +171,7 @@ function headTail(value, keep = 4) {
* Describe an API key for display without revealing it.
*
* three-segment key → account=<decoded> user=<decoded> secret=abcd…wxyz
- * single-segment key → abcd…wxyz (64 chars, legacy format)
+ * other shapes → abcd…wxyz (N chars, unsupported format)
*
* The three-segment format is base64url(account).base64url(user).base64url(secret);
* the first two segments carry no secret and are decoded so the operator can see
@@ -203,9 +203,9 @@ export function describeApiKey(rawKey) {
if (!parts[2]) info.problems.push("secret segment is empty");
info.display = `account=${accountText} user=${userText} secret=${headTail(parts[2])}`;
} else {
- info.format = "legacy";
- if (parts.length !== 1) info.problems.push(`unexpected shape: ${parts.length} dot-separated segments (expected 1 or 3)`);
- info.display = `${headTail(key)} (${key.length} chars, ${parts.length === 1 ? "legacy single-segment" : "unrecognised"} format)`;
+ info.format = "unsupported";
+ info.problems.push(`unsupported shape: ${parts.length} dot-separated segment(s); expected 3`);
+ info.display = `${headTail(key)} (${key.length} chars, unsupported format)`;
}
return info;
}
diff --git a/examples/codex-memory-plugin/skills/ov-memory-doctor/SKILL.md b/examples/codex-memory-plugin/skills/ov-memory-doctor/SKILL.md
index 1e1ca5623..1db885b75 100644
--- a/examples/codex-memory-plugin/skills/ov-memory-doctor/SKILL.md
+++ b/examples/codex-memory-plugin/skills/ov-memory-doctor/SKILL.md
@@ -67,9 +67,9 @@ several sections (a bad key → "api key rejected" + "system/status → 401").
The API key is never printed in full. Three-segment keys are shown as
`account=<a> user=<u> secret=abcd…wxyz` (the first two segments are base64url
-identity, decoded so the user can see which account/user the key claims);
-legacy keys as `abcd…wxyz (64 chars)`. Keep it that way in anything you show
-the user.
+identity, decoded so the user can see which account/user the key claims).
+Other shapes are shown as `abcd…wxyz (N chars, unsupported format)`. Keep it
+that way in anything you show the user.
## Step 2 — map findings to causes
diff --git a/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.md b/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.md
index 4aa9403e1..f2f9e45ff 100644
--- a/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.md
+++ b/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.md
@@ -94,10 +94,9 @@ That file and the registry file whose path the doctor prints are the whole surfa
| `api_key` | key required | from the key; account/user headers are silently stripped |
| `trusted` | root key optional | from the headers; missing → 400 `Trusted mode requests must include X-OpenViking-Account …` |
-Key formats: `base64url(account).base64url(user).base64url(secret)` (three
-segments, identity readable) or a bare 64-hex legacy key. Both fail
-identically as `401 Invalid API Key` when unknown — there is no "wrong
-account" error.
+Key format: `base64url(account).base64url(user).base64url(secret)` (three
+segments, identity readable). Other shapes are rejected as
+`401 Invalid API Key` — there is no "wrong account" error.
`role: root` keys are refused on everything the plugin uses (`/api/v1/sessions`,
`/api/v1/search`, `/api/v1/fs`, `/mcp`) with
diff --git a/examples/memory-plugin-shared/doctor-core.test.mjs b/examples/memory-plugin-shared/doctor-core.test.mjs
index 86d8bf55b..3d3b05b41 100644
--- a/examples/memory-plugin-shared/doctor-core.test.mjs
+++ b/examples/memory-plugin-shared/doctor-core.test.mjs
@@ -63,13 +63,14 @@ test("describeApiKey decodes identity segments and masks the secret", () => {
assert.deepEqual(info.problems, []);
});
-test("describeApiKey shows head/tail only for legacy keys", () => {
+test("describeApiKey reports unsupported key shapes", () => {
const key = "ff6e58" + "a".repeat(54) + "f956";
const info = describeApiKey(key);
- assert.equal(info.format, "legacy");
- assert.equal(info.display, "ff6e…f956 (64 chars, legacy single-segment format)");
+ assert.equal(info.format, "unsupported");
+ assert.equal(info.display, "ff6e…f956 (64 chars, unsupported format)");
+ assert.ok(info.problems.some((p) => p.includes("unsupported shape")));
assert.equal(describeApiKey("").present, false);
- assert.equal(describeApiKey("short").display, "***** (5 chars, legacy single-segment format)");
+ assert.equal(describeApiKey("short").display, "***** (5 chars, unsupported format)");
});
test("describeApiKey flags copy/paste damage", () => {
diff --git a/examples/memory-plugin-shared/lib/doctor-core.mjs b/examples/memory-plugin-shared/lib/doctor-core.mjs
index e9b0d684e..0a22efe3a 100644
--- a/examples/memory-plugin-shared/lib/doctor-core.mjs
+++ b/examples/memory-plugin-shared/lib/doctor-core.mjs
@@ -170,7 +170,7 @@ function headTail(value, keep = 4) {
* Describe an API key for display without revealing it.
*
* three-segment key → account=<decoded> user=<decoded> secret=abcd…wxyz
- * single-segment key → abcd…wxyz (64 chars, legacy format)
+ * other shapes → abcd…wxyz (N chars, unsupported format)
*
* The three-segment format is base64url(account).base64url(user).base64url(secret);
* the first two segments carry no secret and are decoded so the operator can see
@@ -202,9 +202,9 @@ export function describeApiKey(rawKey) {
if (!parts[2]) info.problems.push("secret segment is empty");
info.display = `account=${accountText} user=${userText} secret=${headTail(parts[2])}`;
} else {
- info.format = "legacy";
- if (parts.length !== 1) info.problems.push(`unexpected shape: ${parts.length} dot-separated segments (expected 1 or 3)`);
- info.display = `${headTail(key)} (${key.length} chars, ${parts.length === 1 ? "legacy single-segment" : "unrecognised"} format)`;
+ info.format = "unsupported";
+ info.problems.push(`unsupported shape: ${parts.length} dot-separated segment(s); expected 3`);
+ info.display = `${headTail(key)} (${key.length} chars, unsupported format)`;
}
return info;
}
diff --git a/openviking/server/api_keys/legacy.py b/openviking/server/account_stores/file.py
similarity index 99%
rename from openviking/server/api_keys/legacy.py
rename to openviking/server/account_stores/file.py
index 34addea88..ca2aaca6e 100644
--- a/openviking/server/api_keys/legacy.py
+++ b/openviking/server/account_stores/file.py
@@ -55,24 +55,12 @@ GROUPS_PATH_TEMPLATE = "/local/{account_id}/_system/groups.json"
_MAX_FILE_ACCOUNT_ID_BYTES = 255
-# Argon2id parameters - export with LEGACY_ prefix for reuse in new.py
+# Argon2id parameters shared with API key hashing.
ARGON2_TIME_COST = 3
ARGON2_MEMORY_COST = 65536
ARGON2_PARALLELISM = 2
ARGON2_HASH_LENGTH = 32
-# Also export with LEGACY_ prefix for clarity when imported by new.py
-LEGACY_ARGON2_TIME_COST = ARGON2_TIME_COST
-LEGACY_ARGON2_MEMORY_COST = ARGON2_MEMORY_COST
-LEGACY_ARGON2_PARALLELISM = ARGON2_PARALLELISM
-LEGACY_ARGON2_HASH_LENGTH = ARGON2_HASH_LENGTH
-
-
-def derive_seeded_api_key_secret(user_id: str, seed: str) -> str:
- if not isinstance(seed, str) or seed == "":
- raise InvalidArgumentError("seed must not be empty")
- return hashlib.sha256(f"{user_id}\0{seed}".encode("utf-8")).hexdigest()
-
def validate_file_account_id(account_id: str) -> None:
"""Reject new account IDs that cannot be used as file path components."""
@@ -97,7 +85,7 @@ def _paginate(items: list, limit: int | None, page: int) -> list:
class FileStore(AccountStore):
- """File-backed account and API key store over the legacy AGFS layout."""
+ """File-backed account and API key store over the AGFS registry layout."""
def __init__(
self,
diff --git a/openviking/server/api_keys/new.py b/openviking/server/api_keys/new.py
index f7c6e0db1..112f4b0f9 100644
--- a/openviking/server/api_keys/new.py
+++ b/openviking/server/api_keys/new.py
@@ -3,6 +3,7 @@
"""API key operations over a complete account store."""
import base64
+import hashlib
import hmac
import secrets
from typing import Optional, Tuple
@@ -10,12 +11,10 @@ from typing import Optional, Tuple
from typing_extensions import deprecated
from openviking.server.account_stores.base import AccountStore
-from openviking.server.api_keys.legacy import (
- derive_seeded_api_key_secret,
-)
from openviking.server.identity import ResolvedIdentity, Role
from openviking_cli.exceptions import (
FailedPreconditionError,
+ InvalidArgumentError,
NotFoundError,
UnauthenticatedError,
)
@@ -48,6 +47,12 @@ def parse_api_key(api_key: str) -> Tuple[str, str, str]:
)
+def derive_seeded_api_key_secret(user_id: str, seed: str) -> str:
+ if not isinstance(seed, str) or seed == "":
+ raise InvalidArgumentError("seed must not be empty")
+ return hashlib.sha256(f"{user_id}\0{seed}".encode("utf-8")).hexdigest()
+
+
def generate_api_key(account_id: str, user_id: str, seed: Optional[str] = None) -> str:
secret = (
derive_seeded_api_key_secret(user_id, seed) if seed is not None else secrets.token_hex(32)
@@ -55,6 +60,16 @@ def generate_api_key(account_id: str, user_id: str, seed: Optional[str] = None)
return ".".join(map(_encode_segment, (account_id, user_id, secret)))
+def mask_api_key(api_key: str) -> str:
+ """Mask every secret character except the last four; fully hide malformed keys."""
+ if not is_new_format_key(api_key):
+ return "*" * len(api_key)
+ account, user, secret = api_key.split(".")
+ visible_length = 4 if len(secret) > 4 else 0
+ hidden_length = len(secret) - visible_length
+ return f"{account}.{user}.{'*' * hidden_length}{secret[hidden_length:]}"
+
+
class APIKeyManager:
"""Coordinate API key operations over an already-constructed account store."""
@@ -120,13 +135,12 @@ class APIKeyManager:
)
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(key)
- except (ValueError, UnicodeError):
- raise UnauthenticatedError("Invalid API key") from None
+ if not is_new_format_key(key):
+ raise UnauthenticatedError("Invalid API key")
+ try:
+ 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
)
@@ -233,6 +247,11 @@ class APIKeyManager:
async def list_users_page(self, account_id, **filters):
expose_key = filters.pop("expose_key", True)
+ mask_keys = filters.pop("mask_keys", False)
+ # The masked view still shows the caller's own stored key in plaintext,
+ # but only when account and user match the key's embedded identity.
+ viewer_account_id = filters.pop("viewer_account_id", None)
+ viewer_user_id = filters.pop("viewer_user_id", None)
store_filters = {
name: filters[name]
for name in (
@@ -253,8 +272,40 @@ class APIKeyManager:
for user in page["users"]:
user.pop("api_key", None)
user.pop("key_prefix", None)
+ elif mask_keys:
+ for user in page["users"]:
+ if api_key := user.pop("api_key", None):
+ if self._is_viewer_own_key(
+ api_key,
+ account_id,
+ user.get("user_id"),
+ viewer_account_id,
+ viewer_user_id,
+ ):
+ user["api_key"] = api_key
+ else:
+ user["key_prefix"] = mask_api_key(api_key)
return page
+ @staticmethod
+ def _is_viewer_own_key(
+ api_key,
+ account_id,
+ row_user_id,
+ viewer_account_id,
+ viewer_user_id,
+ ) -> bool:
+ """Strict account/user match between the caller and a listed key."""
+ if not viewer_account_id or not viewer_user_id:
+ return False
+ if account_id != viewer_account_id or row_user_id != viewer_user_id:
+ return False
+ try:
+ key_account_id, key_user_id, _ = parse_api_key(api_key)
+ except (ValueError, UnicodeError):
+ return False
+ return key_account_id == viewer_account_id and key_user_id == viewer_user_id
+
async def has_user(self, account_id, user_id):
return await self.get_user(account_id, user_id) is not None
diff --git a/openviking/server/auth/plugins/trusted.py b/openviking/server/auth/plugins/trusted.py
index 0c9b85ff5..7176ef015 100644
--- a/openviking/server/auth/plugins/trusted.py
+++ b/openviking/server/auth/plugins/trusted.py
@@ -19,7 +19,7 @@ from openviking.core.identifiers import (
validate_user_id,
)
from openviking.server.api_keys import APIKeyManager
-from openviking.server.api_keys.legacy import validate_file_account_id
+from openviking.server.account_stores.file import validate_file_account_id
from openviking.server.auth.plugin import AuthPlugin
from openviking.server.identity import ResolvedIdentity, Role
from openviking.server.store_assembly import build_api_key_manager
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py
index 767e7dcd8..61feb8ffc 100644
--- a/openviking/server/mcp_endpoint.py
+++ b/openviking/server/mcp_endpoint.py
@@ -372,7 +372,9 @@ async def list_users(
"""Find users to grant access to in the caller's account. Returns user_id and
matching total by default, including for administrators. query matches a
substring of user_id. include_credentials=true requires ADMIN or ROOT and
- returns available credentials; it is forbidden in trusted auth mode.
+ returns plaintext for every key to ROOT, and to ADMIN only the caller's own
+ key with masked key_prefix for every other user; it is forbidden in trusted
+ auth mode.
Resource manage permission does not grant account administrator privileges.
"""
ctx = _get_ctx()
@@ -388,6 +390,9 @@ async def list_users(
page=page,
query_filter=query,
expose_key=include_credentials,
+ mask_keys=ctx.role != Role.ROOT,
+ viewer_account_id=ctx.account_id,
+ viewer_user_id=ctx.user.user_id,
)
fields = ("user_id", "role", "api_key", "key_prefix") if include_credentials else ("user_id",)
return {
diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.py
index 5569c24fe..1b0a32c02 100644
--- a/openviking/server/routers/admin.py
+++ b/openviking/server/routers/admin.py
@@ -1013,7 +1013,11 @@ async def list_users(
limit: int | None = Query(None, ge=1, description="Page size; omit to return all"),
include_credentials: bool = Query(
True,
- description="Include credentials when permitted; false returns only credential availability",
+ description=(
+ "Include credentials: ROOT receives all plaintext keys; ADMIN/USER receive the "
+ "caller's own plaintext key and masked key_prefix for other users; "
+ "false returns only availability"
+ ),
),
name: str | None = None,
role: str | None = None,
@@ -1033,6 +1037,9 @@ async def list_users(
name_filter=name,
role_filter=role,
expose_key=should_expose_user_key(request) or not include_credentials,
+ mask_keys=include_credentials and ctx.role != Role.ROOT,
+ viewer_account_id=ctx.account_id,
+ viewer_user_id=ctx.user.user_id,
page=page,
query_filter=query,
)
diff --git a/openviking/server/store_assembly.py b/openviking/server/store_assembly.py
index 4fbbd0dd7..9b462f6c5 100644
--- a/openviking/server/store_assembly.py
+++ b/openviking/server/store_assembly.py
@@ -7,7 +7,7 @@ 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.server.account_stores.file import FileStore
from openviking.storage.viking_fs import VikingFS
from openviking_cli.exceptions import InvalidArgumentError
diff --git a/tests/server/test_account_services.py b/tests/server/test_account_services.py
index c7a4c24a7..4a5ede6d9 100644
--- a/tests/server/test_account_services.py
+++ b/tests/server/test_account_services.py
@@ -12,9 +12,9 @@ import pytest
from sqlalchemy import delete, func, select
from sqlalchemy.ext.asyncio import create_async_engine
+from openviking.server.account_stores.file import FileStore
from openviking.server.account_stores.mysql_schema import Account, Base, Credential, GroupMember
-from openviking.server.api_keys import APIKeyManager
-from openviking.server.api_keys.legacy import FileStore
+from openviking.server.api_keys import APIKeyManager, generate_api_key
from openviking.server.identity import Role
from openviking.server.store_assembly import build_api_key_manager
from openviking_cli.exceptions import (
@@ -37,15 +37,16 @@ def _file_store() -> FileStore:
pytest.param("acme", "u" * 1024, id="long-existing-user"),
],
)
-async def test_legacy_user_without_role_defaults_to_user_during_authentication(account_id, user_id):
+async def test_user_without_role_defaults_to_user_during_authentication(account_id, user_id):
agfs = InMemoryAGFS()
agfs.write(
"/local/_system/accounts.json",
- json.dumps({"accounts": {account_id: {"created_at": "legacy"}}}).encode(),
+ json.dumps({"accounts": {account_id: {"created_at": "existing"}}}).encode(),
)
+ api_key = generate_api_key(account_id, user_id)
agfs.write(
f"/local/{account_id}/_system/users.json",
- json.dumps({"users": {user_id: {"key": "legacy-key"}}}).encode(),
+ json.dumps({"users": {user_id: {"key": api_key}}}).encode(),
)
manager = build_api_key_manager("root", SimpleNamespace(agfs=agfs))
await manager.load()
@@ -54,7 +55,7 @@ async def test_legacy_user_without_role_defaults_to_user_during_authentication(a
"created_accounts": 0,
"created_users": 0,
}
- identity = await manager.resolve_identity("legacy-key")
+ identity = await manager.resolve_identity(api_key)
assert (identity.account_id, identity.user_id, identity.role) == (
account_id,
user_id,
@@ -64,6 +65,25 @@ async def test_legacy_user_without_role_defaults_to_user_during_authentication(a
await manager.close()
+async def test_legacy_key_format_is_rejected_during_authentication():
+ agfs = InMemoryAGFS()
+ agfs.write(
+ "/local/_system/accounts.json",
+ json.dumps({"accounts": {"acme": {"created_at": "existing"}}}).encode(),
+ )
+ agfs.write(
+ "/local/acme/_system/users.json",
+ json.dumps({"users": {"alice": {"key": "legacy-key", "role": "user"}}}).encode(),
+ )
+ manager = build_api_key_manager("root", SimpleNamespace(agfs=agfs))
+ await manager.load()
+ try:
+ with pytest.raises(UnauthenticatedError):
+ await manager.resolve_identity("legacy-key")
+ finally:
+ await manager.close()
+
+
async def test_file_provider_keeps_existing_registry_paths():
fs = SimpleNamespace(agfs=InMemoryAGFS())
manager = build_api_key_manager("root", fs)
diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.py
index eae7162e4..fb71c3234 100644
--- a/tests/server/test_admin_api.py
+++ b/tests/server/test_admin_api.py
@@ -2883,6 +2883,164 @@ async def test_list_users(admin_client: httpx.AsyncClient):
assert user_ids == {"alice", "bob"}
[email protected]("include_summary", [False, True])
[email protected]("include_credentials", [None, True, False])
+async def test_user_list_masks_credentials_for_admin_only(
+ lightweight_admin_client, lightweight_admin_app, include_summary, include_credentials
+):
+ manager = lightweight_admin_app.state.api_key_manager
+ account = _uid()
+ admin_key = await manager.create_account(account, "owner")
+ keys = {"owner": admin_key}
+ keys["alice"] = await manager.register_user(account, "alice")
+ keys["manager"] = await manager.register_user(account, "manager", Role.ADMIN)
+ params = {"include_summary": include_summary, "limit": 2, "page": 1}
+ if include_credentials is not None:
+ params["include_credentials"] = include_credentials
+ url = f"/api/v1/admin/accounts/{account}/users"
+
+ # Each ADMIN sees its own stored key in plaintext and only masked key_prefix
+ # for every other user; ROOT sees every plaintext key.
+ callers = [
+ (admin_key, "owner", False),
+ (keys["manager"], "manager", False),
+ (ROOT_KEY, None, True),
+ ]
+ for caller_key, caller_id, is_root in callers:
+ users = []
+ for page in (1, 2):
+ response = await lightweight_admin_client.get(
+ url, params={**params, "page": page}, headers={"X-API-Key": caller_key}
+ )
+ assert response.status_code == 200
+ result = response.json()["result"]
+ if include_summary:
+ assert result["total"] == result["account_total"] == result["key_count"] == 3
+ result = result["users"]
+ users.extend(result)
+ assert len(users) == 3
+ for user in users:
+ key = keys[user["user_id"]]
+ if include_credentials is False:
+ assert user["api_key_available"] is True
+ assert "api_key" not in user and "key_prefix" not in user
+ elif is_root or user["user_id"] == caller_id:
+ assert user["api_key"] == key
+ assert "key_prefix" not in user
+ else:
+ account_part, user_part, secret = key.split(".")
+ assert user["key_prefix"] == (
+ f"{account_part}.{user_part}.{'*' * (len(secret) - 4)}{secret[-4:]}"
+ )
+ assert "api_key" not in user
+ assert key not in json.dumps(users)
+ assert secret not in json.dumps(users)
+ if not is_root and include_credentials is not False:
+ payload = json.dumps(users)
+ assert keys[caller_id] in payload
+ for other_id, other_key in keys.items():
+ if other_id != caller_id:
+ assert other_key not in payload
+ assert other_key.split(".")[2] not in payload
+ assert (await manager.resolve_identity(keys["alice"])).user_id == "alice"
+ response = await lightweight_admin_client.get(url, headers={"X-API-Key": keys["alice"]})
+ assert response.status_code == 403
+
+
+ "key,expected",
+ [
+ ("YWNtZQ.YWxpY2U.abcdefghijklmnop", "YWNtZQ.YWxpY2U.************mnop"),
+ ("YWNtZQ.YWxpY2U.abcdefgh", "YWNtZQ.YWxpY2U.****efgh"),
+ ("YWNtZQ.YWxpY2U.abcde", "YWNtZQ.YWxpY2U.*bcde"),
+ ("YWNtZQ.YWxpY2U.abcd", "YWNtZQ.YWxpY2U.****"),
+ ("YWNtZQ.YWxpY2U.a", "YWNtZQ.YWxpY2U.*"),
+ ("legacy-secret", "*************"),
+ ("two.parts", "*********"),
+ ("abcd", "****"),
+ ("a", "*"),
+ ],
+)
+async def test_user_key_mask_handles_malformed_and_short_keys(key, expected):
+ from openviking.server.api_keys import APIKeyManager
+
+ store = Mock()
+ store.list_users_page = AsyncMock(
+ return_value={
+ "users": [
+ {"user_id": "alice", "api_key": key},
+ {"user_id": "hashed", "key_prefix": "existing-prefix"},
+ {"user_id": "keyless"},
+ ],
+ "key_count": 2,
+ }
+ )
+ result = await APIKeyManager("root", store).list_users_page("acme", mask_keys=True)
+ assert result["users"] == [
+ {"user_id": "alice", "key_prefix": expected},
+ {"user_id": "hashed", "key_prefix": "existing-prefix"},
+ {"user_id": "keyless"},
+ ]
+ assert result["key_count"] == 2
+ store.list_users_page.assert_awaited_once_with("acme")
+
+
+async def test_user_key_mask_reveals_only_the_viewers_own_key():
+ from openviking.server.api_keys import APIKeyManager
+ from openviking.server.api_keys.new import generate_api_key, mask_api_key
+
+ alice_key = generate_api_key("acme", "alice")
+ bob_key = generate_api_key("acme", "bob")
+ other_alice_key = generate_api_key("other", "alice")
+ rows = {
+ "users": [
+ {"user_id": "alice", "api_key": alice_key},
+ {"user_id": "bob", "api_key": bob_key},
+ # Stored key that does not belong to the row's declared identity.
+ {"user_id": "carol", "api_key": other_alice_key},
+ {"user_id": "hashed", "key_prefix": "existing-prefix"},
+ ],
+ "key_count": 3,
+ }
+
+ def store_with_rows():
+ store = Mock()
+ store.list_users_page = AsyncMock(return_value=deepcopy(rows))
+ return store
+
+ # Matching viewer: only the viewer's own row stays plaintext.
+ result = await APIKeyManager("root", store_with_rows()).list_users_page(
+ "acme", mask_keys=True, viewer_account_id="acme", viewer_user_id="alice"
+ )
+ assert result["users"] == [
+ {"user_id": "alice", "api_key": alice_key},
+ {"user_id": "bob", "key_prefix": mask_api_key(bob_key)},
+ {"user_id": "carol", "key_prefix": mask_api_key(other_alice_key)},
+ {"user_id": "hashed", "key_prefix": "existing-prefix"},
+ ]
+
+ # Account mismatch suppresses the plaintext reveal.
+ result = await APIKeyManager("root", store_with_rows()).list_users_page(
+ "acme", mask_keys=True, viewer_account_id="other", viewer_user_id="alice"
+ )
+ assert result["users"][0] == {"user_id": "alice", "key_prefix": mask_api_key(alice_key)}
+
+ # User-only mismatch (row belongs to another account's identity) never reveals.
+ result = await APIKeyManager("root", store_with_rows()).list_users_page(
+ "acme", mask_keys=True, viewer_account_id="acme", viewer_user_id="carol"
+ )
+ assert result["users"][2] == {
+ "user_id": "carol",
+ "key_prefix": mask_api_key(other_alice_key),
+ }
+
+ # Without viewer identity everything is masked, including the caller's row.
+ result = await APIKeyManager("root", store_with_rows()).list_users_page(
+ "acme", mask_keys=True
+ )
+ assert result["users"][0] == {"user_id": "alice", "key_prefix": mask_api_key(alice_key)}
+
+
async def test_remove_user(
admin_client: httpx.AsyncClient,
admin_service: OpenVikingService,
@@ -3648,7 +3806,15 @@ async def test_user_page_summary_and_search_preserve_legacy_response(
credentials = await mcp_endpoint.list_users(
context, query="user-112", include_credentials=True
)
- assert credentials["users"][0]["api_key"] == last_key
+ if role == Role.ROOT:
+ assert credentials["users"][0]["api_key"] == last_key
+ else:
+ account_part, user_part, secret = last_key.split(".")
+ assert credentials["users"][0]["key_prefix"] == (
+ f"{account_part}.{user_part}.{'*' * (len(secret) - 4)}{secret[-4:]}"
+ )
+ assert "api_key" not in credentials["users"][0]
+ assert last_key not in json.dumps(credentials)
original_config = lightweight_admin_app.state.config
lightweight_admin_app.state.config = ServerConfig(
auth_mode="trusted", root_api_key=ROOT_KEY
diff --git a/tests/server/test_api_key_manager.py b/tests/server/test_api_key_manager.py
index 184eb2891..01b170b2f 100644
--- a/tests/server/test_api_key_manager.py
+++ b/tests/server/test_api_key_manager.py
@@ -724,7 +724,7 @@ async def test_is_new_format_key_validation():
valid_key = generate_api_key("account", "user")
assert is_new_format_key(valid_key)
- # Legacy format (64 hex chars)
+ # Bare single-segment keys are not accepted
assert not is_new_format_key("a" * 64)
# Empty string
diff --git a/tests/server/test_identity_auth.py b/tests/server/test_identity_auth.py
index f84d71102..1ee876266 100644
--- a/tests/server/test_identity_auth.py
+++ b/tests/server/test_identity_auth.py
@@ -10,7 +10,7 @@ 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.api_keys import APIKeyManager, generate_api_key
from openviking.server.auth import (
get_request_context,
get_session_request_context,
@@ -98,11 +98,12 @@ async def test_key_store_error_and_unknown_identity_fail_closed():
store.get_user.return_value = None
manager = APIKeyManager("root", store)
request = await make_request(manager)
+ key = generate_api_key("acme", "missing")
with pytest.raises(UnauthenticatedError, match="Unknown"):
- await request.app.state.auth_plugin.resolve_identity(request, api_key="verified-key")
+ await request.app.state.auth_plugin.resolve_identity(request, api_key=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")
+ await request.app.state.auth_plugin.resolve_identity(request, api_key=key)
async def test_trusted_explicit_user_role_with_root_key(runtime):
diff --git a/tests/server/test_store_assembly.py b/tests/server/test_store_assembly.py
index 35dc99168..3af815c68 100644
--- a/tests/server/test_store_assembly.py
+++ b/tests/server/test_store_assembly.py
@@ -11,8 +11,8 @@ from openviking.scheduling.expiry.config import ExpiryRedisConfig
from openviking.scheduling.expiry.keys import ExpiryKeys
from openviking.scheduling.expiry.metrics import ExpiryMetrics
from openviking.scheduling.expiry.redis_store import RedisExpiryStore
+from openviking.server.account_stores.file import FileStore
from openviking.server.account_stores.redis_client import create_redis_client
-from openviking.server.api_keys.legacy import FileStore
from openviking.server.config import AccountStoreConfig
from openviking.server.store_assembly import (
build_account_store,