Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(auth): support seeded API key generation (#2932)
Qin Haojie8186cfbdebaa
diff --git a/crates/ov_cli/README.md b/crates/ov_cli/README.mdindex a7dadbde6..2fda33a2f 100644--- a/crates/ov_cli/README.md+++ b/crates/ov_cli/README.md@@ -104,6 +104,11 @@ ov read viking://resources/...- `config show` - Show configuration- `config validate` - Validate config+### Admin+- `admin create-account` - Create an account and first admin user+- `admin register-user` - Register a user+- `admin regenerate-key` - Rotate a user's API key+### Display- `language` (`lang`) - Choose CLI display language (`en` / `zh-CN`)@@ -136,6 +141,11 @@ ov ls viking://resources --recursive# Temporarily override identity from CLI flagsov --account acme --user alice ls viking://+# Create predictable API keys from a seed+ov --sudo admin create-account acme --admin alice --seed alice-seed+ov admin register-user acme bob --role user --seed bob-seed+ov admin regenerate-key acme bob --seed bob-new-seed+# Glob searchov glob "**/*.md" --uri viking://resourcesdiff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex f558de69f..3efbd7c1d 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -1251,6 +1251,7 @@ impl HttpClient {&self,account_id: &str,admin_user_id: &str,+ seed: Option<&str>,user_config: Option<&Value>,) -> Result<Value> {let mut body = Map::new();@@ -1265,6 +1266,9 @@ impl HttpClient {if let Some(config) = user_config {body.insert("user_config".to_string(), config.clone());}+ if let Some(seed) = seed {+ body.insert("seed".to_string(), Value::String(seed.to_string()));+ }self.post("/api/v1/admin/accounts", &Value::Object(body)).await}@@ -1283,6 +1287,7 @@ impl HttpClient {account_id: &str,user_id: &str,role: &str,+ seed: Option<&str>,user_config: Option<&Value>,) -> Result<Value> {let path = format!("/api/v1/admin/accounts/{}/users", account_id);@@ -1292,6 +1297,9 @@ impl HttpClient {if let Some(config) = user_config {body.insert("user_config".to_string(), config.clone());}+ if let Some(seed) = seed {+ body.insert("seed".to_string(), Value::String(seed.to_string()));+ }self.post(&path, &Value::Object(body)).await}@@ -1332,12 +1340,21 @@ impl HttpClient {self.put(&path, &body).await}- pub async fn admin_regenerate_key(&self, account_id: &str, user_id: &str) -> Result<Value> {+ pub async fn admin_regenerate_key(+ &self,+ account_id: &str,+ user_id: &str,+ seed: Option<&str>,+ ) -> Result<Value> {let path = format!("/api/v1/admin/accounts/{}/users/{}/key",account_id, user_id);- self.post(&path, &serde_json::json!({})).await+ let body = match seed {+ Some(seed) => serde_json::json!({ "seed": seed }),+ None => serde_json::json!({}),+ };+ self.post(&path, &body).await}pub async fn admin_migrate(&self, cleanup: bool) -> Result<Value> {@@ -1798,6 +1815,39 @@ mod tests {assert!(!request.contains("include_mod_time_iso="));}+ #[tokio::test]+ async fn admin_seed_payloads_are_sent() {+ let (base_url, request_rx) = spawn_request_capture_server().await;+ let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None);+ client+ .admin_create_account("acct", "admin", Some("admin-seed"), None)+ .await+ .expect("create account should succeed");+ let request = request_rx.await.expect("request should be captured");+ assert!(request.starts_with("POST /api/v1/admin/accounts "));+ assert!(request.contains(r#""seed":"admin-seed""#));++ let (base_url, request_rx) = spawn_request_capture_server().await;+ let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None);+ client+ .admin_register_user("acct", "alice", "admin", Some("alice-seed"), None)+ .await+ .expect("register user should succeed");+ let request = request_rx.await.expect("request should be captured");+ assert!(request.starts_with("POST /api/v1/admin/accounts/acct/users "));+ assert!(request.contains(r#""seed":"alice-seed""#));++ let (base_url, request_rx) = spawn_request_capture_server().await;+ let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None);+ client+ .admin_regenerate_key("acct", "alice", Some("new-seed"))+ .await+ .expect("regenerate key should succeed");+ let request = request_rx.await.expect("request should be captured");+ assert!(request.starts_with("POST /api/v1/admin/accounts/acct/users/alice/key "));+ assert!(request.contains(r#""seed":"new-seed""#));+ }+#[test]fn standard_error_envelope_formats_api_error() {let body = json!({diff --git a/crates/ov_cli/src/commands/admin.rs b/crates/ov_cli/src/commands/admin.rsindex 07747dfb0..bb8cf4de2 100644--- a/crates/ov_cli/src/commands/admin.rs+++ b/crates/ov_cli/src/commands/admin.rs@@ -11,13 +11,14 @@ pub async fn create_account(client: &HttpClient,account_id: &str,admin_user_id: &str,+ seed: Option<&str>,user_config_json: Option<&str>,output_format: OutputFormat,compact: bool,) -> Result<()> {let user_config = parse_user_config_json(user_config_json, "--user-config-json")?;let response = client- .admin_create_account(account_id, admin_user_id, user_config.as_ref())+ .admin_create_account(account_id, admin_user_id, seed, user_config.as_ref()).await?;output_success(&response, output_format, compact);print_admin_user_key_notice(&response, output_format, false);@@ -67,13 +68,14 @@ pub async fn register_user(account_id: &str,user_id: &str,role: &str,+ seed: Option<&str>,user_config_json: Option<&str>,output_format: OutputFormat,compact: bool,) -> Result<()> {let user_config = parse_user_config_json(user_config_json, "--user-config-json")?;let response = client- .admin_register_user(account_id, user_id, role, user_config.as_ref())+ .admin_register_user(account_id, user_id, role, seed, user_config.as_ref()).await?;output_success(&response, output_format, compact);print_admin_user_key_notice(&response, output_format, false);@@ -144,10 +146,13 @@ pub async fn regenerate_key(client: &HttpClient,account_id: &str,user_id: &str,+ seed: Option<&str>,output_format: OutputFormat,compact: bool,) -> Result<()> {- let response = client.admin_regenerate_key(account_id, user_id).await?;+ let response = client+ .admin_regenerate_key(account_id, user_id, seed)+ .await?;output_success(&response, output_format, compact);print_admin_user_key_notice(&response, output_format, true);Ok(())diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rsindex 84fb38a4b..4db9559a6 100644--- a/crates/ov_cli/src/handlers.rs+++ b/crates/ov_cli/src/handlers.rs@@ -505,12 +505,14 @@ pub async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {AdminCommands::CreateAccount {account_id,admin_user_id,+ seed,user_config_json,} => {commands::admin::create_account(&client,&account_id,&admin_user_id,+ seed.as_deref(),user_config_json.as_deref(),ctx.output_format,ctx.compact,@@ -531,6 +533,7 @@ pub async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {account_id,user_id,role,+ seed,user_config_json,} => {commands::admin::register_user(@@ -538,6 +541,7 @@ pub async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {&account_id,&user_id,&role,+ seed.as_deref(),user_config_json.as_deref(),ctx.output_format,ctx.compact,@@ -592,11 +596,13 @@ pub async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {AdminCommands::RegenerateKey {account_id,user_id,+ seed,} => {commands::admin::regenerate_key(&client,&account_id,&user_id,+ seed.as_deref(),ctx.output_format,ctx.compact,)diff --git a/crates/ov_cli/src/help_ui.rs b/crates/ov_cli/src/help_ui.rsindex a3738ee08..a45f90594 100644--- a/crates/ov_cli/src/help_ui.rs+++ b/crates/ov_cli/src/help_ui.rs@@ -70,7 +70,8 @@ const CORE_WORKFLOW: &[HelpCommand] = help_commands!["add-memory",];-const FILESYSTEM: &[HelpCommand] = help_commands!["ls", "tree", "mkdir", "rm", "mv", "stat", "get"];+const FILESYSTEM: &[HelpCommand] =+ help_commands!["ls", "tree", "mkdir", "rm", "mv", "stat", "attrs", "get"];const SEARCH_CONTEXT: &[HelpCommand] = help_commands!["find", "search", "grep", "glob", "abstract", "overview", "read"@@ -321,6 +322,30 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[},],},+ CommandHelpSpec {+ path: &["attrs"],+ purpose: "Get or update logical extended attributes for a resource.",+ examples: &[+ HelpItem {+ label: "ov attrs get viking://projects/acme/spec.md",+ description: "Show all logical attributes for a resource.",+ },+ HelpItem {+ label: "ov attrs set-tags viking://projects/acme/spec.md --tags team=search",+ description: "Set retrieval tags on a resource.",+ },+ ],+ next_steps: &[+ HelpItem {+ label: "ov stat <uri>",+ description: "Inspect resource metadata.",+ },+ HelpItem {+ label: "ov find \"query\" -u <uri>",+ description: "Search with updated context.",+ },+ ],+ },CommandHelpSpec {path: &["read"],purpose: "Read exact Level 2 file content from a Viking URI.",@@ -1151,6 +1176,10 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[label: "ov admin register-user <account> <user>",description: "Register a user in an account.",},+ HelpItem {+ label: "ov admin regenerate-key <account> <user> --seed <seed>",+ description: "Regenerate a predictable API key from a seed.",+ },HelpItem {label: "ov admin migrate --sudo",description: "Start legacy agent/session migration.",diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex db9f6835b..42d830bf4 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -1533,6 +1533,9 @@ enum AdminCommands {/// First admin user ID#[arg(long = "admin", value_name = "user-id")]admin_user_id: String,+ /// Deterministic API key seed+ #[arg(long, value_name = "seed")]+ seed: Option<String>,/// Initial config for the first admin user as JSON#[arg(long = "user-config-json", value_name = "json")]user_config_json: Option<String>,@@ -1562,6 +1565,9 @@ enum AdminCommands {/// Role: admin or user#[arg(long, default_value = "user", value_name = "role")]role: String,+ /// Deterministic API key seed+ #[arg(long, value_name = "seed")]+ seed: Option<String>,/// Initial config for the new user as JSON#[arg(long = "user-config-json", value_name = "json")]user_config_json: Option<String>,@@ -1610,6 +1616,9 @@ enum AdminCommands {/// User ID#[arg(value_name = "user-id")]user_id: String,+ /// Deterministic API key seed+ #[arg(long, value_name = "seed")]+ seed: Option<String>,},}diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.mdindex a8cf0d52f..be13ec156 100644--- a/docs/en/api/08-admin.md+++ b/docs/en/api/08-admin.md@@ -84,10 +84,12 @@ Create a new workspace with its first admin user.|-----------|------|----------|---------|-------------|| account_id | str | Yes | - | Workspace ID || admin_user_id | str | Yes | - | First admin user ID |+| seed | str | No | `null` | Optional deterministic API key seed. When set, the key secret is `sha256(user_id + "\0" + seed)` || user_config | object | No | `null` | Initial config for the first admin user. Currently supports `add_targets.resource_uri` and `add_targets.skill_uri` |**Notes:**- In `trusted` mode, `user_key` is omitted from the response+- Omit `seed` for the default random API key. Treat seed values as secret material; short seeds can make the key guessable.- Account-level namespace isolation settings are no longer supported. User memory uses user-scoped namespaces, and one-to-many external participants are represented with `peer_id`.- `user_config.add_targets.resource_uri` must be a writable resource directory URI: `viking://resources` or `viking://resources/...`, `viking://user/resources` or `viking://user/resources/...`, `viking://user/{user_id}/resources` or `viking://user/{user_id}/resources/...`, or `viking://user/{user_id}/peers/{peer_id}/resources` or `viking://user/{user_id}/peers/{peer_id}/resources/...`.- `user_config.add_targets.skill_uri` must be `viking://user/skills` or `viking://agent/skills`. Explicit `viking://user/{user_id}/skills` is not accepted in v1.@@ -106,7 +108,8 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \-H "X-API-Key: <root-key>" \-d '{"account_id": "acme",- "admin_user_id": "alice"+ "admin_user_id": "alice",+ "seed": "alice-seed"}'```@@ -160,7 +163,7 @@ import openviking as ovclient = ov.SyncHTTPClient(api_key="<root-key>")client.initialize()-result = client.admin_create_account("acme", "alice")+result = client.admin_create_account("acme", "alice", seed="alice-seed")print(f"Account created: {result['account_id']}")print(f"Admin user: {result['admin_user_id']}")print(f"User key: {result.get('user_key', '(not exposed in trusted mode)')}")@@ -186,7 +189,9 @@ if err != nil {}fmt.Println(result["account_id"])+seed := "alice-seed"result, err = client.AdminCreateAccountWithOptions(ctx, "acme-private", "alice", &openviking.AdminCreateAccountOptions{+ Seed: &seed,UserConfig: map[string]any{"add_targets": map[string]any{"resource_uri": "viking://user/resources",@@ -201,6 +206,7 @@ result, err = client.AdminCreateAccountWithOptions(ctx, "acme-private", "alice",```bash# Requires ROOT privileges, use --sudoov --sudo admin create-account acme --admin alice+ov --sudo admin create-account acme --admin alice --seed alice-seedov --sudo admin create-account acme-private --admin alice \--user-config-json '{"add_targets":{"resource_uri":"viking://user/resources","skill_uri":"viking://user/skills"}}'@@ -414,10 +420,12 @@ Register a new user in a workspace.| account_id | str | Yes | - | Workspace ID || user_id | str | Yes | - | User ID || role | str | No | "user" | Role to assign. `ROOT` and same-account `ADMIN` may register `"user"` or `"admin"`. `"root"` must be assigned through the dedicated role-change endpoint. |+| seed | str | No | `null` | Optional deterministic API key seed. When set, the key secret is `sha256(user_id + "\0" + seed)` || user_config | object | No | `null` | Initial config for the new user. Currently supports `add_targets.resource_uri` and `add_targets.skill_uri` |**Notes:**- In `trusted` mode, `user_key` is omitted from the response+- Omit `seed` for the default random API key. Treat seed values as secret material; short seeds can make the key guessable.- ADMIN can only register users in their own account- The `"root"` role cannot be minted through user registration- `user_config.add_targets.resource_uri` must be a writable resource directory URI: `viking://resources` or `viking://resources/...`, `viking://user/resources` or `viking://user/resources/...`, `viking://user/{user_id}/resources` or `viking://user/{user_id}/resources/...`, or `viking://user/{user_id}/peers/{peer_id}/resources` or `viking://user/{user_id}/peers/{peer_id}/resources/...`.@@ -437,7 +445,8 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users \-H "X-API-Key: <root-or-admin-key>" \-d '{"user_id": "bob",- "role": "user"+ "role": "user",+ "seed": "bob-seed"}'```@@ -449,7 +458,7 @@ import openviking as ovclient = ov.SyncHTTPClient(api_key="<root-or-admin-key>")client.initialize()-result = client.admin_register_user("acme", "bob", role="user")+result = client.admin_register_user("acme", "bob", role="user", seed="bob-seed")print(f"User registered: {result['user_id']}")print(f"User key: {result.get('user_key', '(not exposed in trusted mode)')}")@@ -470,7 +479,9 @@ if err != nil {}fmt.Println(result["user_id"])+seed := "bob-seed"result, err = client.AdminRegisterUserWithOptions(ctx, "acme", "bob-private", "user", &openviking.AdminRegisterUserOptions{+ Seed: &seed,UserConfig: map[string]any{"add_targets": map[string]any{"resource_uri": "viking://user/resources/project-a"},},@@ -483,6 +494,7 @@ result, err = client.AdminRegisterUserWithOptions(ctx, "acme", "bob-private", "u# Either ROOT or account ADMIN can execute# If using regular user's api_key who is an ADMIN of acme:ov admin register-user acme bob --role user+ov admin register-user acme bob --role user --seed bob-seed# If using root_api_key (--sudo):ov --sudo admin register-user acme bob --role user@@ -808,10 +820,12 @@ Regenerate a user's API key. The old key is immediately invalidated.|-----------|------|----------|---------|-------------|| account_id | str | Yes | - | Workspace ID || user_id | str | Yes | - | User ID |+| seed | str | No | `null` | Optional deterministic API key seed in the JSON request body. When set, the key secret is `sha256(user_id + "\0" + seed)` |**Notes:**- ADMIN can only regenerate keys for users in their own account- Old key is immediately invalidated, clients using it need to be updated+- Omit `seed` for the default random regenerated key.#### 3. Usage Examples@@ -824,7 +838,8 @@ POST /api/v1/admin/accounts/{account_id}/users/{user_id}/key```bashcurl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users/bob/key \-H "Content-Type: application/json" \- -H "X-API-Key: <root-or-admin-key>"+ -H "X-API-Key: <root-or-admin-key>" \+ -d '{"seed": "bob-new-seed"}'```**Python SDK**@@ -835,7 +850,7 @@ import openviking as ovclient = ov.SyncHTTPClient(api_key="<root-or-admin-key>")client.initialize()-result = client.admin_regenerate_key("acme", "bob")+result = client.admin_regenerate_key("acme", "bob", seed="bob-new-seed")print(f"New user key: {result['user_key']}")```@@ -847,6 +862,11 @@ if err != nil {return err}fmt.Println(result["user_key"])++seed := "bob-new-seed"+result, err = client.AdminRegenerateKeyWithOptions(ctx, "acme", "bob", &openviking.AdminRegenerateKeyOptions{+ Seed: &seed,+})```**CLI**@@ -855,6 +875,7 @@ fmt.Println(result["user_key"])# Either ROOT or account ADMIN can execute# If using regular user's api_key who is an ADMIN of acme:ov admin regenerate-key acme bob+ov admin regenerate-key acme bob --seed bob-new-seed# If using root_api_key (--sudo):ov --sudo admin regenerate-key acme bob```diff --git a/docs/en/guides/04-authentication.md b/docs/en/guides/04-authentication.mdindex e2c2c3d96..117b971bc 100644--- a/docs/en/guides/04-authentication.md+++ b/docs/en/guides/04-authentication.md@@ -11,7 +11,10 @@ OpenViking uses a two-layer API key system:| Root Key | Server config (`root_api_key`) | ROOT | Account management + selected system/monitoring operations || User Key | Admin API | ADMIN or USER | Per-account data access; ADMIN can also manage users in its account |-All API keys are plain random tokens with no embedded identity. The server resolves identity by first comparing against the root key, then looking up the user key index.+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.## Authentication Modes@@ -99,7 +102,7 @@ Custom roles work with `require_role()` and `require_auth_role()` decorators out## Managing Accounts and Users-Normal requests in both `api_key` and `trusted` modes do not need Admin API as a prerequisite for ordinary reads, writes, search, or session access. Admin API is still the place to create accounts, register users, change roles, and issue user keys.+Normal requests in both `api_key` and `trusted` modes do not need Admin API as a prerequisite for ordinary reads, writes, search, or session access. Admin API is still the place to create accounts, register users, change roles, and issue or regenerate user keys.Use the root key to create accounts (workspaces) and users via the Admin API:diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.mdindex ea6c47c8b..5076c4de5 100644--- a/docs/zh/api/08-admin.md+++ b/docs/zh/api/08-admin.md@@ -84,10 +84,12 @@ Admin API 用于多租户环境下的账户和用户管理。包括工作区(a|------|------|------|--------|------|| account_id | str | 是 | - | 工作区 ID || admin_user_id | str | 是 | - | 首个管理员用户 ID |+| seed | str | 否 | `null` | 可选的确定性 API Key seed。传入后,key secret 为 `sha256(user_id + "\0" + seed)` || user_config | object | 否 | `null` | 首个管理员用户的初始配置。当前支持 `add_targets.resource_uri` 和 `add_targets.skill_uri` |**说明:**- 在 `trusted` 模式下,响应中不会包含 `user_key` 字段+- 省略 `seed` 时使用默认随机 API Key。seed 应视为密钥材料;过短的 seed 会让 key 更容易被猜测。- 不再支持 account 级 namespace 隔离配置。用户记忆使用 user-scoped namespace,一对多外部参与者通过 `peer_id` 表达。- `user_config.add_targets.resource_uri` 必须是可写资源目录 URI:`viking://resources` 或 `viking://resources/...`、`viking://user/resources` 或 `viking://user/resources/...`、`viking://user/{user_id}/resources` 或 `viking://user/{user_id}/resources/...`、`viking://user/{user_id}/peers/{peer_id}/resources` 或 `viking://user/{user_id}/peers/{peer_id}/resources/...`。- `user_config.add_targets.skill_uri` 只能是 `viking://user/skills` 或 `viking://agent/skills`。v1 不支持显式写成 `viking://user/{user_id}/skills`。@@ -106,7 +108,8 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \-H "X-API-Key: <root-key>" \-d '{"account_id": "acme",- "admin_user_id": "alice"+ "admin_user_id": "alice",+ "seed": "alice-seed"}'```@@ -160,7 +163,7 @@ import openviking as ovclient = ov.SyncHTTPClient(api_key="<root-key>")client.initialize()-result = client.admin_create_account("acme", "alice")+result = client.admin_create_account("acme", "alice", seed="alice-seed")print(f"Account created: {result['account_id']}")print(f"Admin user: {result['admin_user_id']}")print(f"User key: {result.get('user_key', '(not exposed in trusted mode)')}")@@ -186,7 +189,9 @@ if err != nil {}fmt.Println(result["account_id"])+seed := "alice-seed"result, err = client.AdminCreateAccountWithOptions(ctx, "acme-private", "alice", &openviking.AdminCreateAccountOptions{+ Seed: &seed,UserConfig: map[string]any{"add_targets": map[string]any{"resource_uri": "viking://user/resources",@@ -201,6 +206,7 @@ result, err = client.AdminCreateAccountWithOptions(ctx, "acme-private", "alice",```bash# 需要 ROOT 权限,使用 --sudoov --sudo admin create-account acme --admin alice+ov --sudo admin create-account acme --admin alice --seed alice-seedov --sudo admin create-account acme-private --admin alice \--user-config-json '{"add_targets":{"resource_uri":"viking://user/resources","skill_uri":"viking://user/skills"}}'@@ -412,10 +418,12 @@ ov --sudo admin delete-account acme| account_id | str | 是 | - | 工作区 ID || user_id | str | 是 | - | 用户 ID || role | str | 否 | "user" | 要分配的角色。`ROOT` 和同 account 的 `ADMIN` 可直接注册 `"user"` 或 `"admin"`。`"root"` 必须通过专门的改角色接口分配。 |+| seed | str | 否 | `null` | 可选的确定性 API Key seed。传入后,key secret 为 `sha256(user_id + "\0" + seed)` || user_config | object | 否 | `null` | 新用户的初始配置。当前支持 `add_targets.resource_uri` 和 `add_targets.skill_uri` |**说明:**- 在 `trusted` 模式下,响应中不会包含 `user_key` 字段+- 省略 `seed` 时使用默认随机 API Key。seed 应视为密钥材料;过短的 seed 会让 key 更容易被猜测。- ADMIN 只能在自己所属的 account 中注册用户- 无法通过用户注册接口直接创建 `"root"` 角色- `user_config.add_targets.resource_uri` 必须是可写资源目录 URI:`viking://resources` 或 `viking://resources/...`、`viking://user/resources` 或 `viking://user/resources/...`、`viking://user/{user_id}/resources` 或 `viking://user/{user_id}/resources/...`、`viking://user/{user_id}/peers/{peer_id}/resources` 或 `viking://user/{user_id}/peers/{peer_id}/resources/...`。@@ -435,7 +443,8 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users \-H "X-API-Key: <root-or-admin-key>" \-d '{"user_id": "bob",- "role": "user"+ "role": "user",+ "seed": "bob-seed"}'```@@ -447,7 +456,7 @@ import openviking as ovclient = ov.SyncHTTPClient(api_key="<root-or-admin-key>")client.initialize()-result = client.admin_register_user("acme", "bob", role="user")+result = client.admin_register_user("acme", "bob", role="user", seed="bob-seed")print(f"User registered: {result['user_id']}")print(f"User key: {result.get('user_key', '(not exposed in trusted mode)')}")@@ -468,7 +477,9 @@ if err != nil {}fmt.Println(result["user_id"])+seed := "bob-seed"result, err = client.AdminRegisterUserWithOptions(ctx, "acme", "bob-private", "user", &openviking.AdminRegisterUserOptions{+ Seed: &seed,UserConfig: map[string]any{"add_targets": map[string]any{"resource_uri": "viking://user/resources/project-a"},},@@ -481,6 +492,7 @@ result, err = client.AdminRegisterUserWithOptions(ctx, "acme", "bob-private", "u# ROOT 或本账户的 ADMIN 都可以执行# 如果使用普通用户的 api_key 但该用户是 acme 的 ADMIN:ov admin register-user acme bob --role user+ov admin register-user acme bob --role user --seed bob-seed# 如果使用 root_api_key(--sudo):ov --sudo admin register-user acme bob --role user@@ -805,10 +817,12 @@ ov --sudo admin set-role acme bob admin|------|------|------|--------|------|| account_id | str | 是 | - | 工作区 ID || user_id | str | 是 | - | 用户 ID |+| seed | str | 否 | `null` | JSON request body 中可选的确定性 API Key seed。传入后,key secret 为 `sha256(user_id + "\0" + seed)` |**说明:**- ADMIN 只能为自己所属的 account 中的用户重新生成密钥- 旧密钥会立即失效,需要更新使用该密钥的客户端+- 省略 `seed` 时使用默认随机重新生成逻辑。#### 3. 使用示例@@ -821,7 +835,8 @@ POST /api/v1/admin/accounts/{account_id}/users/{user_id}/key```bashcurl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users/bob/key \-H "Content-Type: application/json" \- -H "X-API-Key: <root-or-admin-key>"+ -H "X-API-Key: <root-or-admin-key>" \+ -d '{"seed": "bob-new-seed"}'```**Python SDK**@@ -832,7 +847,7 @@ import openviking as ovclient = ov.SyncHTTPClient(api_key="<root-or-admin-key>")client.initialize()-result = client.admin_regenerate_key("acme", "bob")+result = client.admin_regenerate_key("acme", "bob", seed="bob-new-seed")print(f"New user key: {result['user_key']}")```@@ -844,6 +859,11 @@ if err != nil {return err}fmt.Println(result["user_key"])++seed := "bob-new-seed"+result, err = client.AdminRegenerateKeyWithOptions(ctx, "acme", "bob", &openviking.AdminRegenerateKeyOptions{+ Seed: &seed,+})```**CLI**@@ -852,6 +872,7 @@ fmt.Println(result["user_key"])# ROOT 或本账户的 ADMIN 都可以执行# 如果使用普通用户的 api_key 但该用户是 acme 的 ADMIN:ov admin regenerate-key acme bob+ov admin regenerate-key acme bob --seed bob-new-seed# 如果使用 root_api_key(--sudo):ov --sudo admin regenerate-key acme bob```diff --git a/docs/zh/guides/04-authentication.md b/docs/zh/guides/04-authentication.mdindex 1e27f421c..c5d8f73b1 100644--- a/docs/zh/guides/04-authentication.md+++ b/docs/zh/guides/04-authentication.md@@ -11,7 +11,9 @@ OpenViking 使用两层 API Key 体系:| Root Key | 服务端配置(`root_api_key`) | ROOT | 账户管理 + 少量 system/monitoring 操作 || User Key | Admin API | ADMIN 或 USER | 租户内数据访问;ADMIN 还可管理本 account 下的用户 |-所有 API Key 均为纯随机 token,不携带身份信息。服务端通过先比对 root key、再查 user key 索引的方式确定身份。+User key 由 Admin API 生成。默认使用随机 secret;Admin API 调用方也可以传入+`seed`,用 `sha256(user_id + "\0" + seed)` 生成可预测的 key secret。服务端仍然+会用存储的 key 或 key hash 校验最终 API Key。## 认证模式@@ -99,7 +101,7 @@ Role.register("operator", rank=1) # 权限介于 USER (0) 与 ADMIN (1) 之间## 管理账户和用户-普通读写、检索、会话等数据请求在 `api_key` 和 `trusted` 两种模式下都不依赖 Admin API 预注册。Admin API 仍然负责创建 account、注册用户、修改角色以及签发 user key。+普通读写、检索、会话等数据请求在 `api_key` 和 `trusted` 两种模式下都不依赖 Admin API 预注册。Admin API 仍然负责创建 account、注册用户、修改角色以及签发或重新生成 user key。使用 root key 通过 Admin API 创建工作区和用户:diff --git a/openviking/server/api_keys/legacy.py b/openviking/server/api_keys/legacy.pyindex 9b4694f3d..a13aa939d 100644--- a/openviking/server/api_keys/legacy.py+++ b/openviking/server/api_keys/legacy.py@@ -45,6 +45,12 @@ LEGACY_ARGON2_PARALLELISM = ARGON2_PARALLELISMLEGACY_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()++class LegacyAPIKeyManager:"""Manages API keys for multi-tenant authentication (legacy implementation)."""@@ -209,6 +215,7 @@ class LegacyAPIKeyManager:self,account_id: str,admin_user_id: str,+ seed: Optional[str] = None,) -> str:"""Create a new account (workspace) with its first admin user.@@ -226,7 +233,11 @@ class LegacyAPIKeyManager:raise AlreadyExistsError(account_id, "account")now = datetime.now(timezone.utc).isoformat()- key = self._generate_api_key()+ 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)@@ -280,7 +291,13 @@ class LegacyAPIKeyManager:await self._save_accounts_json()- async def register_user(self, account_id: str, user_id: str, role: str = "user") -> str:+ async def register_user(+ 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)."""# Validate user_id formatverr = validate_user_id(user_id)@@ -293,7 +310,11 @@ class LegacyAPIKeyManager:if user_id in account.users:raise AlreadyExistsError(user_id, "user")- key = self._generate_api_key()+ 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)@@ -360,7 +381,7 @@ class LegacyAPIKeyManager:await self._save_users_json(account_id)- async def regenerate_key(self, account_id: str, user_id: str) -> str:+ 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."""account = self._accounts.get(account_id)if account is None:@@ -387,7 +408,11 @@ class LegacyAPIKeyManager:del self._prefix_index[old_key_prefix]# Generate new key- new_key = self._generate_api_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)diff --git a/openviking/server/api_keys/new.py b/openviking/server/api_keys/new.pyindex 6f97d1dfa..f37595d51 100644--- a/openviking/server/api_keys/new.py+++ b/openviking/server/api_keys/new.py@@ -13,6 +13,7 @@ from typing import Optional, Tuplefrom openviking.server.api_keys.legacy import (LegacyAPIKeyManager,+ derive_seeded_api_key_secret,)from openviking.server.api_keys.models import AccountInfo, UserKeyEntryfrom openviking.server.identity import ResolvedIdentity, Role@@ -58,12 +59,15 @@ def parse_api_key(api_key: str) -> Tuple[str, str, str]:return account_id, user_id, secret-def generate_api_key(account_id: str, user_id: str) -> str:+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)- # Generate a 32-byte random secret and encode it- secret = secrets.token_hex(32)+ secret = (+ 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}"@@ -161,6 +165,7 @@ class NewAPIKeyManager:self,account_id: str,admin_user_id: str,+ seed: Optional[str] = None,) -> str:"""Create a new account (workspace) with its first admin user.@@ -175,7 +180,7 @@ class NewAPIKeyManager:raise InvalidArgumentError(verr)# Generate new format key- key = generate_api_key(account_id, admin_user_id)+ key = generate_api_key(account_id, admin_user_id, seed)# Use legacy to create account but with our new key# We temporarily replace the generate method, call, then restore@@ -239,7 +244,13 @@ class NewAPIKeyManager:"""Delete an account and remove all its user keys from the index."""await self._legacy.delete_account(account_id)- async def register_user(self, account_id: str, user_id: str, role: str = "user") -> str:+ async def register_user(+ 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 in new format."""# Validate user_id formatverr = validate_user_id(user_id)@@ -258,7 +269,7 @@ class NewAPIKeyManager:raise AlreadyExistsError(user_id, "user")# Generate new format key- key = generate_api_key(account_id, user_id)+ key = generate_api_key(account_id, user_id, seed)if self._legacy._api_key_hashing_enabled:stored_key = self._legacy._hash_api_key(key)@@ -298,7 +309,12 @@ class NewAPIKeyManager:"""Remove a user from an account."""await self._legacy.remove_user(account_id, user_id)- async def regenerate_key(self, account_id: str, user_id: str) -> str:+ 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.Generates new format key regardless of original format.@@ -333,7 +349,7 @@ class NewAPIKeyManager:del self._legacy._prefix_index[old_key_prefix]# Generate new key in new format- new_key = generate_api_key(account_id, user_id)+ new_key = generate_api_key(account_id, user_id, seed)if self._legacy._api_key_hashing_enabled:new_stored_key = self._legacy._hash_api_key(new_key)diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.pyindex ce197c30e..0e08ed3a8 100644--- a/openviking/server/routers/admin.py+++ b/openviking/server/routers/admin.py@@ -4,7 +4,7 @@import asyncio-from fastapi import APIRouter, Depends, Path, Request+from fastapi import APIRouter, Body, Depends, Path, Requestfrom pydantic import BaseModelfrom openviking.server.auth import (@@ -43,12 +43,14 @@ router = APIRouter(prefix="/api/v1/admin", tags=["admin"])class CreateAccountRequest(BaseModel):account_id: stradmin_user_id: str+ seed: str | None = Noneuser_config: UserConfig | None = Noneclass RegisterUserRequest(BaseModel):user_id: strrole: str = "user"+ seed: str | None = Noneuser_config: UserConfig | None = None@@ -56,6 +58,10 @@ class SetRoleRequest(BaseModel):role: str+class RegenerateKeyRequest(BaseModel):+ seed: str | None = None++class MigrateLegacyDataRequest(BaseModel):action: str = "migrate"@@ -170,6 +176,7 @@ async def create_account(user_key = await manager.create_account(body.account_id,body.admin_user_id,+ seed=body.seed,)await service.initialize_account_directories(account_ctx)await service.initialize_user_directories(account_ctx)@@ -308,7 +315,12 @@ async def register_user()_validate_initial_user_config(service, user_ctx, body.user_config)manager = _get_api_key_manager(request)- user_key = await manager.register_user(account_id, body.user_id, str(resolved_role))+ user_key = await manager.register_user(+ account_id,+ body.user_id,+ str(resolved_role),+ seed=body.seed,+ )await service.initialize_user_directories(user_ctx)await _write_initial_user_config(service, user_ctx, body.user_config)result = {@@ -381,6 +393,7 @@ async def set_user_role(@require_auth_root_or_adminasync def regenerate_key(request: Request,+ body: RegenerateKeyRequest | None = Body(default=None),account_id: str = Path(..., description="Account ID"),user_id: str = Path(..., description="User ID"),ctx: RequestContext = Depends(get_request_context),@@ -388,5 +401,9 @@ async def regenerate_key("""Regenerate a user's API key. Old key is immediately invalidated."""_check_account_access(ctx, account_id)manager = _get_api_key_manager(request)- new_key = await manager.regenerate_key(account_id, user_id)+ new_key = await manager.regenerate_key(+ account_id,+ user_id,+ seed=body.seed if body is not None else None,+ )return Response(status="ok", result={"user_key": new_key})diff --git a/sdk/go/README.md b/sdk/go/README.mdindex f916b511c..ab5ef23ca 100644--- a/sdk/go/README.md+++ b/sdk/go/README.md@@ -116,7 +116,7 @@ Implemented:| Sessions and tasks | `CreateSession`, `ListSessions`, `GetSession`, `SessionExists`, `GetSessionContext`, `GetSessionArchive`, `DeleteSession`, `AddMessage`, `BatchAddMessages`, `CommitSession`, `GetTask`, `ListTasks` || Packs | `ExportOVPack`, `BackupOVPack`, `ImportOVPack`, `RestoreOVPack` || System and observer | `Health`, `CheckConsistency`, `GetStatus`, `IsHealthy`, `QueueStatus`, `VikingDBStatus`, `ModelsStatus` |-| Admin | `AdminCreateAccount`, `AdminCreateAccountWithOptions`, `AdminListAccounts`, `AdminDeleteAccount`, `AdminRegisterUser`, `AdminRegisterUserWithOptions`, `AdminListUsers`, `AdminRemoveUser`, `AdminSetRole`, `AdminRegenerateKey`, `AdminMigrate` |+| Admin | `AdminCreateAccount`, `AdminCreateAccountWithOptions`, `AdminListAccounts`, `AdminDeleteAccount`, `AdminRegisterUser`, `AdminRegisterUserWithOptions`, `AdminListUsers`, `AdminRemoveUser`, `AdminSetRole`, `AdminRegenerateKey`, `AdminRegenerateKeyWithOptions`, `AdminMigrate` |Not implemented in Go SDK v1:@@ -135,16 +135,28 @@ config. Ordinary add calls do not need SDK defaults; omit `To` / `TargetURI`and let the server resolve user and deployment defaults.```go+seed := "alice-seed"_, err := client.AdminRegisterUserWithOptions(ctx, "acme", "alice", "user", &openviking.AdminRegisterUserOptions{- UserConfig: map[string]any{+ Seed: &seed,+ UserConfig: map[string]any{"add_targets": map[string]any{"resource_uri": "viking://user/resources/project-a","skill_uri": "viking://user/skills",},},})++newSeed := "alice-new-seed"+_, err = client.AdminRegenerateKeyWithOptions(ctx, "acme", "alice", &openviking.AdminRegenerateKeyOptions{+ Seed: &newSeed,+})```+When `Seed` is set, the returned API key is derived from+`sha256(user_id + "\0" + seed)`; omit it for random key generation.+Use `nil` to omit `Seed`; set `Seed` to a string pointer to send it, including+an empty string that the server rejects.+## Files, Directories, and Packs`AddResource` and `AddSkill` accept local files and directories. Directorydiff --git a/sdk/go/README_CN.md b/sdk/go/README_CN.mdindex bb74b1e8d..9c94829fe 100644--- a/sdk/go/README_CN.md+++ b/sdk/go/README_CN.md@@ -45,7 +45,7 @@ Go SDK 仅支持 HTTP 模式,不支持 Python embedded 模式,也不保留| 会话和任务 | `CreateSession`, `ListSessions`, `GetSession`, `SessionExists`, `GetSessionContext`, `GetSessionArchive`, `DeleteSession`, `AddMessage`, `BatchAddMessages`, `CommitSession`, `GetTask`, `ListTasks` || OVPack | `ExportOVPack`, `BackupOVPack`, `ImportOVPack`, `RestoreOVPack` || 系统和 observer | `Health`, `CheckConsistency`, `GetStatus`, `IsHealthy`, `QueueStatus`, `VikingDBStatus`, `ModelsStatus` |-| 管理接口 | `AdminCreateAccount`, `AdminCreateAccountWithOptions`, `AdminListAccounts`, `AdminDeleteAccount`, `AdminRegisterUser`, `AdminRegisterUserWithOptions`, `AdminListUsers`, `AdminRemoveUser`, `AdminSetRole`, `AdminRegenerateKey`, `AdminMigrate` |+| 管理接口 | `AdminCreateAccount`, `AdminCreateAccountWithOptions`, `AdminListAccounts`, `AdminDeleteAccount`, `AdminRegisterUser`, `AdminRegisterUserWithOptions`, `AdminListUsers`, `AdminRemoveUser`, `AdminSetRole`, `AdminRegenerateKey`, `AdminRegenerateKeyWithOptions`, `AdminMigrate` |## 暂未实现接口@@ -64,7 +64,9 @@ Go SDK v1 的边界是对齐当前 Python HTTP client,不覆盖所有 server创建用户时如需写入初始服务端用户配置,使用 options 版本。普通 add 调用不需要 SDK 侧默认值;省略 `To` / `TargetURI`,让服务端解析用户和部署默认值。```go+seed := "alice-seed"_, err := client.AdminRegisterUserWithOptions(ctx, "acme", "alice", "user", &openviking.AdminRegisterUserOptions{+ Seed: &seed,UserConfig: map[string]any{"add_targets": map[string]any{"resource_uri": "viking://user/resources/project-a",@@ -72,8 +74,16 @@ _, err := client.AdminRegisterUserWithOptions(ctx, "acme", "alice", "user", &ope},},})++newSeed := "alice-new-seed"+_, err = client.AdminRegenerateKeyWithOptions(ctx, "acme", "alice", &openviking.AdminRegenerateKeyOptions{+ Seed: &newSeed,+})```+传入 `Seed` 时,返回的 API Key 会基于 `sha256(user_id + "\0" + seed)` 生成;省略时仍使用随机生成逻辑。+使用 `nil` 表示不传 `Seed`;传入字符串指针表示显式发送 seed,包括会被服务端拒绝的空字符串。+## 技能和 Watch 示例```godiff --git a/sdk/go/admin.go b/sdk/go/admin.goindex 450b171cb..10186e30a 100644--- a/sdk/go/admin.go+++ b/sdk/go/admin.go@@ -20,6 +20,9 @@ func (c *Client) AdminCreateAccountWithOptions(ctx context.Context, accountID, aif opts != nil && opts.UserConfig != nil {payload["user_config"] = opts.UserConfig}+ if opts != nil && opts.Seed != nil {+ payload["seed"] = *opts.Seed+ }var result map[string]anyerr := c.doJSON(ctx, http.MethodPost, "/api/v1/admin/accounts", nil, payload, &result)return result, err@@ -56,6 +59,9 @@ func (c *Client) AdminRegisterUserWithOptions(ctx context.Context, accountID, usif opts != nil && opts.UserConfig != nil {payload["user_config"] = opts.UserConfig}+ if opts != nil && opts.Seed != nil {+ payload["seed"] = *opts.Seed+ }var result map[string]anyerr := c.doJSON(ctx, http.MethodPost, "/api/v1/admin/accounts/"+url.PathEscape(accountID)+"/users", nil, payload, &result)return result, err@@ -86,8 +92,17 @@ func (c *Client) AdminSetRole(ctx context.Context, accountID, userID, role strin// AdminRegenerateKey regenerates a user's API key.func (c *Client) AdminRegenerateKey(ctx context.Context, accountID, userID string) (map[string]any, error) {+ return c.AdminRegenerateKeyWithOptions(ctx, accountID, userID, nil)+}++// AdminRegenerateKeyWithOptions regenerates a user's API key.+func (c *Client) AdminRegenerateKeyWithOptions(ctx context.Context, accountID, userID string, opts *AdminRegenerateKeyOptions) (map[string]any, error) {+ var payload map[string]any+ if opts != nil && opts.Seed != nil {+ payload = map[string]any{"seed": *opts.Seed}+ }var result map[string]any- err := c.doJSON(ctx, http.MethodPost, "/api/v1/admin/accounts/"+url.PathEscape(accountID)+"/users/"+url.PathEscape(userID)+"/key", nil, nil, &result)+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/admin/accounts/"+url.PathEscape(accountID)+"/users/"+url.PathEscape(userID)+"/key", nil, payload, &result)return result, err}diff --git a/sdk/go/client_test.go b/sdk/go/client_test.goindex 2c29e168c..0193b2211 100644--- a/sdk/go/client_test.go+++ b/sdk/go/client_test.go@@ -201,6 +201,88 @@ func TestAdminCreatePathsAcceptInitialUserConfig(t *testing.T) {}}+func TestAdminSeedPayloads(t *testing.T) {+ var seen []map[string]any+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/api/v1/admin/accounts",+ "/api/v1/admin/accounts/acct/users",+ "/api/v1/admin/accounts/acct/users/alice/key":+ default:+ t.Fatalf("path = %s", r.URL.Path)+ }+ if r.Method != http.MethodPost {+ t.Fatalf("method = %s", r.Method)+ }+ body := readJSONBody(t, r)+ seen = append(seen, body)+ writeOK(t, w, body)+ }))+ defer closeServer()++ adminSeed := "admin-seed"+ if _, err := client.AdminCreateAccountWithOptions(context.Background(), "acct", "admin", &AdminCreateAccountOptions{+ Seed: &adminSeed,+ }); err != nil {+ t.Fatal(err)+ }+ aliceSeed := "alice-seed"+ if _, err := client.AdminRegisterUserWithOptions(context.Background(), "acct", "alice", "admin", &AdminRegisterUserOptions{+ Seed: &aliceSeed,+ }); err != nil {+ t.Fatal(err)+ }+ newSeed := "new-seed"+ if _, err := client.AdminRegenerateKeyWithOptions(context.Background(), "acct", "alice", &AdminRegenerateKeyOptions{+ Seed: &newSeed,+ }); err != nil {+ t.Fatal(err)+ }++ if got := seen[0]["seed"]; got != "admin-seed" {+ t.Fatalf("create seed = %#v", got)+ }+ if got := seen[1]["seed"]; got != "alice-seed" {+ t.Fatalf("register seed = %#v", got)+ }+ if got := seen[2]["seed"]; got != "new-seed" {+ t.Fatalf("regenerate seed = %#v", got)+ }+}++func TestAdminEmptySeedPayloadsAreSent(t *testing.T) {+ var seen []map[string]any+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body := readJSONBody(t, r)+ seen = append(seen, body)+ writeOK(t, w, body)+ }))+ defer closeServer()++ emptySeed := ""+ if _, err := client.AdminCreateAccountWithOptions(context.Background(), "acct", "admin", &AdminCreateAccountOptions{+ Seed: &emptySeed,+ }); err != nil {+ t.Fatal(err)+ }+ if _, err := client.AdminRegisterUserWithOptions(context.Background(), "acct", "alice", "admin", &AdminRegisterUserOptions{+ Seed: &emptySeed,+ }); err != nil {+ t.Fatal(err)+ }+ if _, err := client.AdminRegenerateKeyWithOptions(context.Background(), "acct", "alice", &AdminRegenerateKeyOptions{+ Seed: &emptySeed,+ }); err != nil {+ t.Fatal(err)+ }++ for i, body := range seen {+ if got, ok := body["seed"]; !ok || got != "" {+ t.Fatalf("request %d seed = %#v, present = %v", i, got, ok)+ }+ }+}+func TestSearchSendsSessionAndSearchFilters(t *testing.T) {client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if r.URL.Path != "/api/v1/search/search" {diff --git a/sdk/go/types.go b/sdk/go/types.goindex 1be642824..2bf5cd0de 100644--- a/sdk/go/types.go+++ b/sdk/go/types.go@@ -53,11 +53,18 @@ type AddSkillOptions struct {// AdminCreateAccountOptions controls AdminCreateAccountWithOptions.type AdminCreateAccountOptions struct {UserConfig map[string]any+ Seed *string}// AdminRegisterUserOptions controls AdminRegisterUserWithOptions.type AdminRegisterUserOptions struct {UserConfig map[string]any+ Seed *string+}++// AdminRegenerateKeyOptions controls AdminRegenerateKeyWithOptions.+type AdminRegenerateKeyOptions struct {+ Seed *string}// ListSkillsOptions controls ListSkills.diff --git a/sdk/python/README.md b/sdk/python/README.mdindex e99061d1c..a80ed32dd 100644--- a/sdk/python/README.md+++ b/sdk/python/README.md@@ -206,6 +206,7 @@ root_client = SyncHTTPClient(result = root_client.admin_create_account(account_id="demo-account",admin_user_id="demo-admin",+ seed="demo-admin-seed",)print(result)@@ -213,6 +214,7 @@ root_client.admin_register_user(account_id="demo-account",user_id="alice",role="user",+ seed="alice-seed",user_config={"add_targets": {"resource_uri": "viking://user/resources/project-a",@@ -220,11 +222,19 @@ root_client.admin_register_user(}},)++root_client.admin_regenerate_key(+ account_id="demo-account",+ user_id="alice",+ seed="alice-new-seed",+)````admin_create_account` also accepts `user_config` with the same shape.These fields initialize server-side user config; ordinary add calls still justomit `to` / `parent` / `target_uri` and let the server resolve defaults.+When `seed` is set, the returned API key is derived from+`sha256(user_id + "\0" + seed)`; omit it for random key generation.## Error Handlingdiff --git a/sdk/python/README_CN.md b/sdk/python/README_CN.mdindex 22e0543f8..dd1753081 100644--- a/sdk/python/README_CN.md+++ b/sdk/python/README_CN.md@@ -206,6 +206,7 @@ root_client = SyncHTTPClient(result = root_client.admin_create_account(account_id="demo-account",admin_user_id="demo-admin",+ seed="demo-admin-seed",)print(result)@@ -213,6 +214,7 @@ root_client.admin_register_user(account_id="demo-account",user_id="alice",role="user",+ seed="alice-seed",user_config={"add_targets": {"resource_uri": "viking://user/resources/project-a",@@ -220,9 +222,16 @@ root_client.admin_register_user(}},)++root_client.admin_regenerate_key(+ account_id="demo-account",+ user_id="alice",+ seed="alice-new-seed",+)````admin_create_account` 也接受同样结构的 `user_config`。这些字段用于初始化服务端用户配置;普通添加调用仍然只需省略 `to` / `parent` / `target_uri`,由服务端解析默认值。+传入 `seed` 时,返回的 API Key 会基于 `sha256(user_id + "\0" + seed)` 生成;省略时仍使用随机生成逻辑。## 错误处理diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.pyindex 83644504c..72b2194c0 100644--- a/sdk/python/openviking_sdk/client.py+++ b/sdk/python/openviking_sdk/client.py@@ -1234,8 +1234,11 @@ class AsyncHTTPClient:account_id: str,admin_user_id: str,user_config: Optional[Dict[str, Any]] = None,+ seed: Optional[str] = None,) -> Dict[str, Any]:payload: Dict[str, Any] = {"account_id": account_id, "admin_user_id": admin_user_id}+ if seed is not None:+ payload["seed"] = seedif user_config is not None:payload["user_config"] = user_configresponse = await self._http.post(@@ -1258,8 +1261,11 @@ class AsyncHTTPClient:user_id: str,role: str = "user",user_config: Optional[Dict[str, Any]] = None,+ seed: Optional[str] = None,) -> Dict[str, Any]:payload: Dict[str, Any] = {"user_id": user_id, "role": role}+ if seed is not None:+ payload["seed"] = seedif user_config is not None:payload["user_config"] = user_configresponse = await self._http.post(@@ -1283,8 +1289,16 @@ class AsyncHTTPClient:)return self._handle_response(response)- async def admin_regenerate_key(self, account_id: str, user_id: str) -> Dict[str, Any]:- response = await self._http.post(f"/api/v1/admin/accounts/{account_id}/users/{user_id}/key")+ async def admin_regenerate_key(+ self, account_id: str, user_id: str, seed: Optional[str] = None+ ) -> Dict[str, Any]:+ payload: Dict[str, Any] = {}+ if seed is not None:+ payload["seed"] = seed+ response = await self._http.post(+ f"/api/v1/admin/accounts/{account_id}/users/{user_id}/key",+ json=payload,+ )return self._handle_response(response)async def admin_migrate(self, cleanup: bool = False) -> Dict[str, Any]:@@ -1994,11 +2008,13 @@ class SyncHTTPClient:account_id: str,admin_user_id: str,user_config: Optional[Dict[str, Any]] = None,+ seed: Optional[str] = None,) -> Dict[str, Any]:return run_async(self._async_client.admin_create_account(account_id,admin_user_id,+ seed=seed,user_config=user_config,))@@ -2015,12 +2031,14 @@ class SyncHTTPClient:user_id: str,role: str = "user",user_config: Optional[Dict[str, Any]] = None,+ seed: Optional[str] = None,) -> Dict[str, Any]:return run_async(self._async_client.admin_register_user(account_id,user_id,role,+ seed=seed,user_config=user_config,))@@ -2034,8 +2052,10 @@ class SyncHTTPClient:def admin_set_role(self, account_id: str, user_id: str, role: str) -> Dict[str, Any]:return run_async(self._async_client.admin_set_role(account_id, user_id, role))- def admin_regenerate_key(self, account_id: str, user_id: str) -> Dict[str, Any]:- return run_async(self._async_client.admin_regenerate_key(account_id, user_id))+ def admin_regenerate_key(+ self, account_id: str, user_id: str, seed: Optional[str] = None+ ) -> Dict[str, Any]:+ return run_async(self._async_client.admin_regenerate_key(account_id, user_id, seed=seed))def admin_migrate(self, cleanup: bool = False) -> Dict[str, Any]:return run_async(self._async_client.admin_migrate(cleanup=cleanup))diff --git a/sdk/python/tests/test_async_client_behaviors.py b/sdk/python/tests/test_async_client_behaviors.pyindex 2ba12d9af..9f2d40a84 100644--- a/sdk/python/tests/test_async_client_behaviors.py+++ b/sdk/python/tests/test_async_client_behaviors.py@@ -386,6 +386,30 @@ async def test_admin_create_paths_accept_initial_user_config():}+async def test_admin_seed_payloads_are_sent():+ client = AsyncHTTPClient(url="http://localhost:1933")+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))+ client._http = fake_http+ client._handle_response = lambda _response: {"status": "ok"}++ await client.admin_create_account("acct", "admin", seed="admin-seed")+ await client.admin_register_user("acct", "alice", "admin", seed="alice-seed")+ await client.admin_regenerate_key("acct", "alice", seed="new-seed")++ assert fake_http.post.await_args_list[0].kwargs["json"] == {+ "account_id": "acct",+ "admin_user_id": "admin",+ "seed": "admin-seed",+ }+ assert fake_http.post.await_args_list[1].kwargs["json"] == {+ "user_id": "alice",+ "role": "admin",+ "seed": "alice-seed",+ }+ assert fake_http.post.await_args_list[2].kwargs["json"] == {"seed": "new-seed"}++@pytest.mark.asyncioasync def test_import_ovpack_uploads_local_file_even_when_url_is_localhost(tmp_path):pack_file = tmp_path / "demo.ovpack"diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.pyindex a3457f67d..ac4699d15 100644--- a/tests/server/test_admin_api.py+++ b/tests/server/test_admin_api.py@@ -4,6 +4,7 @@"""Tests for Admin API endpoints (openviking/server/routers/admin.py)."""import asyncio+import hashlibimport jsonimport uuid@@ -35,6 +36,10 @@ def _uid() -> str:return f"acme_{uuid.uuid4().hex[:8]}"+def _seed_secret(user_id: str, seed: str) -> str:+ return hashlib.sha256(f"{user_id}\0{seed}".encode("utf-8")).hexdigest()++ROOT_KEY = "admin-api-test-root-key-abcdef1234567890ab"@@ -667,6 +672,60 @@ async def test_regenerate_key(admin_client: httpx.AsyncClient):assert resp.status_code == 200+async def test_seeded_admin_key_endpoints(admin_client: httpx.AsyncClient):+ from openviking.server.api_keys import parse_api_key++ acct = _uid()+ resp = await admin_client.post(+ "/api/v1/admin/accounts",+ json={"account_id": acct, "admin_user_id": "alice", "seed": "admin-seed"},+ headers=root_headers(),+ )+ assert resp.status_code == 200+ admin_key = resp.json()["result"]["user_key"]+ account_id, user_id, secret = parse_api_key(admin_key)+ assert account_id == acct+ assert user_id == "alice"+ assert secret == _seed_secret("alice", "admin-seed")++ resp = await admin_client.post(+ f"/api/v1/admin/accounts/{acct}/users",+ json={"user_id": "bob", "role": "user", "seed": "bob-seed"},+ headers=root_headers(),+ )+ assert resp.status_code == 200+ old_key = resp.json()["result"]["user_key"]+ _, _, old_secret = parse_api_key(old_key)+ assert old_secret == _seed_secret("bob", "bob-seed")++ resp = await admin_client.post(+ f"/api/v1/admin/accounts/{acct}/users/bob/key",+ json={"seed": "bob-new-seed"},+ headers=root_headers(),+ )+ assert resp.status_code == 200+ new_key = resp.json()["result"]["user_key"]+ _, _, new_secret = parse_api_key(new_key)+ assert new_secret == _seed_secret("bob", "bob-new-seed")+ assert new_key != old_key++ resp = await admin_client.get(+ "/api/v1/fs/ls?uri=viking://",+ headers={"X-API-Key": old_key},+ )+ assert resp.status_code == 401+++async def test_empty_seed_rejected(admin_client: httpx.AsyncClient):+ acct = _uid()+ resp = await admin_client.post(+ "/api/v1/admin/accounts",+ json={"account_id": acct, "admin_user_id": "alice", "seed": ""},+ headers=root_headers(),+ )+ assert resp.status_code == 400++# ---- Permission guard ----diff --git a/tests/server/test_api_key_manager.py b/tests/server/test_api_key_manager.pyindex 982c4fc57..8d614bfea 100644--- a/tests/server/test_api_key_manager.py+++ b/tests/server/test_api_key_manager.py@@ -3,6 +3,7 @@"""Tests for APIKeyManager (openviking/server/api_keys.py)."""+import hashlibimport uuidimport pytest@@ -12,7 +13,12 @@ from openviking.pyagfs.exceptions import AGFSNotFoundErrorfrom openviking.server.api_keys import APIKeyManagerfrom openviking.server.identity import Rolefrom openviking.service.core import OpenVikingService-from openviking_cli.exceptions import AlreadyExistsError, NotFoundError, UnauthenticatedError+from openviking_cli.exceptions import (+ AlreadyExistsError,+ InvalidArgumentError,+ NotFoundError,+ UnauthenticatedError,+)from openviking_cli.session.user_id import UserIdentifier@@ -21,6 +27,10 @@ def _uid() -> str:return f"acme_{uuid.uuid4().hex[:8]}"+def _seed_secret(user_id: str, seed: str) -> str:+ return hashlib.sha256(f"{user_id}\0{seed}".encode("utf-8")).hexdigest()++ROOT_KEY = "test-root-key-abcdef1234567890abcdef1234567890"@@ -552,6 +562,70 @@ async def test_register_user_generates_new_format(manager: APIKeyManager):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++ seed = "client-known-seed"+ acct1 = _uid()+ acct2 = _uid()++ key1 = await manager.create_account(acct1, "alice", seed=seed)+ key2 = await manager.create_account(acct2, "alice", seed=seed)++ account1, user1, secret1 = parse_api_key(key1)+ account2, user2, secret2 = parse_api_key(key2)++ assert account1 == acct1+ assert account2 == acct2+ assert user1 == user2 == "alice"+ assert secret1 == secret2 == _seed_secret("alice", seed)+ assert key1 != key2+++async def test_seeded_register_and_regenerate_key(manager: APIKeyManager):+ from openviking.server.api_keys import parse_api_key++ acct = _uid()+ await manager.create_account(acct, "alice")+ old_key = await manager.register_user(acct, "bob", "user", seed="first-seed")+ _, _, old_secret = parse_api_key(old_key)+ assert old_secret == _seed_secret("bob", "first-seed")++ new_key = await manager.regenerate_key(acct, "bob", seed="second-seed")+ _, _, new_secret = parse_api_key(new_key)+ assert new_secret == _seed_secret("bob", "second-seed")+ assert new_key != old_key++ with pytest.raises(UnauthenticatedError):+ manager.resolve(old_key)+ assert manager.resolve(new_key).user_id == "bob"+++async def test_seed_must_not_be_empty(manager: APIKeyManager):+ acct = _uid()+ with pytest.raises(InvalidArgumentError):+ 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