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 self-service user API key rotation (#6649)
MaojiaShenge2145009cc27
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex ac5c0e10f..b6712c518 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -212,6 +212,22 @@ impl HttpClient {self.base.api_key()}+ /// Match the server's credential selection after custom headers are applied.+ pub(crate) fn request_api_key(&self) -> Option<String> {+ let headers = self.base.build_headers();+ headers+ .get("X-API-Key")+ .and_then(|value| value.to_str().ok())+ .filter(|value| !value.is_empty())+ .or_else(|| {+ headers+ .get(reqwest::header::AUTHORIZATION)+ .and_then(|value| value.to_str().ok())+ .and_then(|value| value.strip_prefix("Bearer "))+ })+ .map(str::to_owned)+ }+fn upload_mode(&self) -> Option<String> {match env::var("OPENVIKING_UPLOAD_MODE") {Ok(value) => {diff --git a/crates/ov_cli/src/commands/admin.rs b/crates/ov_cli/src/commands/admin.rsindex fa8eb282e..811dd0adf 100644--- a/crates/ov_cli/src/commands/admin.rs+++ b/crates/ov_cli/src/commands/admin.rs@@ -1,7 +1,10 @@use crate::client::HttpClient;+use crate::config::Config;+use crate::config_wizard::ConfigStore;use crate::error::{Error, Result};use crate::output::{OutputFormat, output_success};use crate::theme;+use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};use colored::Colorize;use serde_json::{Value, json};@@ -254,17 +257,72 @@ pub async fn regenerate_key(account_id: &str,user_id: &str,seed: Option<&str>,+ active_config: Option<&Config>,output_format: OutputFormat,compact: bool,) -> Result<()> {+ let request_key = client.request_api_key();+ let update = if let Some(config) = active_config.filter(|config| {+ config.api_key.as_deref() == client.api_key()+ && request_key+ .as_deref()+ .is_some_and(|key| key_belongs_to(key, account_id, user_id))+ }) {+ let update = ConfigStore::new()?.prepare_api_key_update(config, request_key.as_deref().unwrap())?;+ eprintln!(+ "Rotating your API key will update api_key in {} and any matching authentication headers.",+ update.path().display()+ );+ Some(update)+ } else {+ None+ };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);+ if let Some(update) = update {+ let path = update.path().display().to_string();+ let Some(new_key) = response+ .get("user_key")+ .and_then(Value::as_str)+ .filter(|key| key_belongs_to(key, account_id, user_id))+ else {+ output_success(&response, output_format, compact);+ return Err(Error::Config(format!(+ "Server reported key rotation without a valid user_key for {account_id}/{user_id}; {path} was not updated. Check the command output and recover the credential before retrying."+ )));+ };+ let saved = update.commit(new_key).map_err(|error| Error::Config(format!(+ "API key was rotated, but could not update {path}: {error}. Save the new user_key from the command output to api_key manually."+ )));+ // Persist before writing stdout (which can fail on a closed pipe), but+ // retain the returned credential in the output even if saving failed.+ output_success(&response, output_format, compact);+ saved?;+ if request_key.as_deref() == Some(new_key) {+ eprintln!(+ "Updated api_key in {path} and any matching authentication headers. The generated key is unchanged; use a new seed or omit --seed to rotate it."+ );+ } else {+ eprintln!(+ "Updated api_key in {path} and any matching authentication headers. The old key is invalid; update other clients using it."+ );+ }+ } else {+ output_success(&response, output_format, compact);+ print_admin_user_key_notice(&response, output_format, true);+ }Ok(())}+fn key_belongs_to(key: &str, account_id: &str, user_id: &str) -> bool {+ let parts: Vec<_> = key.split('.').collect();+ parts.len() == 3+ && !parts[2].is_empty()+ && URL_SAFE_NO_PAD.decode(parts[0]).ok().as_deref() == Some(account_id.as_bytes())+ && URL_SAFE_NO_PAD.decode(parts[1]).ok().as_deref() == Some(user_id.as_bytes())+}+pub async fn set_account_settings(client: &HttpClient,account_id: &str,diff --git a/crates/ov_cli/src/config_wizard/store.rs b/crates/ov_cli/src/config_wizard/store.rsindex be030ef40..172ba1460 100644--- a/crates/ov_cli/src/config_wizard/store.rs+++ b/crates/ov_cli/src/config_wizard/store.rs@@ -94,6 +94,56 @@ pub struct ConfigStore {active_path: PathBuf,}+pub(crate) struct PreparedApiKeyUpdate {+ path: PathBuf,+ target: PathBuf,+ old_key: String,+ original: Vec<u8>,+ value: Value,+ temp_file: tempfile::NamedTempFile,+}++impl PreparedApiKeyUpdate {+ pub(crate) fn path(&self) -> &Path {+ &self.path+ }++ pub(crate) fn commit(mut self, new_key: &str) -> Result<()> {+ if fs::canonicalize(&self.path)? != self.target+ || fs::read(&self.target)? != self.original+ {+ return Err(Error::Config(+ "Config changed during key rotation; refusing to overwrite it".into(),+ ));+ }+ self.value["api_key"] = Value::String(new_key.to_string());+ for field in ["extra_headers", "extra_header"] {+ if let Some(headers) = self.value.get_mut(field).and_then(Value::as_object_mut) {+ for (name, value) in headers {+ if name.eq_ignore_ascii_case("x-api-key")+ && value.as_str() == Some(self.old_key.as_str())+ {+ *value = Value::String(new_key.to_string());+ } else if name.eq_ignore_ascii_case("authorization")+ && value.as_str().and_then(|v| v.strip_prefix("Bearer "))+ == Some(self.old_key.as_str())+ {+ *value = Value::String(format!("Bearer {new_key}"));+ }+ }+ }+ }+ self.temp_file+ .write_all(serde_json::to_string_pretty(&self.value)?.as_bytes())?;+ self.temp_file.flush()?;+ self.temp_file.as_file().sync_all()?;+ self.temp_file.persist(&self.target).map_err(|error| {+ Error::Config(format!("Failed to replace config file: {}", error.error))+ })?;+ Ok(())+ }+}+impl ConfigStore {pub fn new() -> Result<Self> {Self::for_active_path(effective_config_path()?)@@ -265,6 +315,39 @@ impl ConfigStore {write_config_file(&self.active_path, config)}+ pub(crate) fn prepare_api_key_update(&self, expected: &Config, old_key: &str) -> Result<PreparedApiKeyUpdate> {+ let target = fs::canonicalize(&self.active_path)?;+ let original = fs::read(&target)?;+ let current: Config = serde_json::from_slice(&original)?;+ if current.url != expected.url || current.api_key != expected.api_key+ || current.extra_headers != expected.extra_headers+ {+ return Err(Error::Config(+ "Active connection changed; retry key rotation with the current config".into(),+ ));+ }+ // Case variants can coexist in the JSON map but become the same HTTP+ // header. Refuse ambiguous credentials before invalidating any key.+ if current.extra_headers.as_ref().is_some_and(|headers| {+ headers.iter().any(|(name, value)| {+ name.eq_ignore_ascii_case("x-api-key") && value != old_key+ })+ }) {+ return Err(Error::Config(+ "Conflicting X-API-Key headers; remove the overrides before rotating your key".into(),+ ));+ }+ Ok(PreparedApiKeyUpdate {+ path: self.active_path.clone(),+ old_key: old_key.to_string(),+ value: serde_json::from_slice(&original)?,+ original,+ // Check that a replacement can be created before invalidating the old key.+ temp_file: create_config_temp_file(&target)?,+ target,+ })+ }+pub fn save_edited_config(&self,old_name: &str,@@ -802,18 +885,27 @@ fn carry_over_unmodeled_keys(path: &Path, value: &mut Value) {}fn write_file_atomically(path: &Path, content: &[u8]) -> Result<()> {+ let mut temp_file = create_config_temp_file(path)?;+ temp_file.write_all(content)?;+ temp_file.flush()?;+ temp_file.as_file().sync_all()?;+ temp_file.persist(path).map_err(|error| {+ Error::Config(format!("Failed to replace config file: {}", error.error))+ })?;+ Ok(())+}++fn create_config_temp_file(path: &Path) -> Result<tempfile::NamedTempFile> {let parent = path.parent()- .ok_or_else(|| Error::Config("Could not determine config file directory".to_string()))?;+ .filter(|parent| !parent.as_os_str().is_empty())+ .unwrap_or_else(|| Path::new("."));fs::create_dir_all(parent)?;- let mut temp_file = tempfile::Builder::new()+ let temp_file = tempfile::Builder::new().prefix(".ovcli.conf.").suffix(".tmp").tempfile_in(parent)?;- temp_file.write_all(content)?;- temp_file.flush()?;-#[cfg(unix)]{use std::os::unix::fs::PermissionsExt;@@ -822,12 +914,7 @@ fn write_file_atomically(path: &Path, content: &[u8]) -> Result<()> {temp_file.as_file().set_permissions(permissions)?;}- temp_file.as_file().sync_all()?;- temp_file.persist(path).map_err(|error| {- Error::Config(format!("Failed to replace config file: {}", error.error))- })?;-- Ok(())+ Ok(temp_file)}pub(crate) fn configs_equivalent(left: &Config, right: &Config) -> Result<bool> {diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rsindex 5c2632176..bc6d8a95f 100644--- a/crates/ov_cli/src/handlers.rs+++ b/crates/ov_cli/src/handlers.rs@@ -773,6 +773,7 @@ pub async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {&account_id,&user_id,seed.as_deref(),+ if ctx.sudo { None } else { Some(&ctx.config) },ctx.output_format,ctx.compact,)diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex 75b22baa4..33158f8fb 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -2254,7 +2254,7 @@ enum AdminCommands {#[arg(value_name = "role")]role: String,},- /// Regenerate a user's API key (old key immediately invalidated)+ /// Regenerate a user's API key; self-rotation updates the active ovcli.confRegenerateKey {/// Account ID#[arg(value_name = "account-id")]diff --git a/crates/ov_cli/tests/api_key_rotation.rs b/crates/ov_cli/tests/api_key_rotation.rsnew file mode 100644index 000000000..e6341a784--- /dev/null+++ b/crates/ov_cli/tests/api_key_rotation.rs@@ -0,0 +1,403 @@+//! Exercise the real command and an isolated selected config, never the user's config.+use serde_json::{Value, json};+use std::{+ fs,+ io::{Read, Write},+ net::TcpListener,+ path::Path,+ process::{Command, Output, Stdio},+ thread,+ time::{Duration, Instant},+};++const OLD_KEY: &str = "YWNtZQ.YWxpY2U.b2xkLXNlY3JldA";+const NEW_KEY: &str = "YWNtZQ.YWxpY2U.bmV3LXNlY3JldA";++fn run(dir: &Path, args: &[&str]) -> Output {+ Command::new(env!("CARGO_BIN_EXE_ov"))+ .current_dir(dir)+ .env("OPENVIKING_CLI_CONFIG_FILE", "selected.json")+ .env("OPENVIKING_LANG", "en")+ .env("NO_COLOR", "1")+ .stdin(Stdio::null())+ .args(args)+ .output()+ .unwrap()+}++fn serve(+ status: u16,+ body: Value,+ before_response: impl FnOnce() + Send + 'static,+) -> (String, thread::JoinHandle<String>) {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let url = format!("http://{}", listener.local_addr().unwrap());+ listener.set_nonblocking(true).unwrap();+ let server = thread::spawn(move || {+ let started = Instant::now();+ let mut stream = loop {+ match listener.accept() {+ Ok((stream, _)) => break stream,+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {+ assert!(+ started.elapsed() < Duration::from_secs(10),+ "CLI sent no request"+ );+ thread::sleep(Duration::from_millis(10));+ }+ Err(error) => panic!("{error}"),+ }+ };+ stream+ .set_read_timeout(Some(Duration::from_secs(5)))+ .unwrap();+ let mut request = Vec::new();+ let mut buf = [0; 4096];+ loop {+ let n = stream.read(&mut buf).unwrap();+ assert!(n > 0);+ request.extend_from_slice(&buf[..n]);+ if let Some(header_end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") {+ let headers = String::from_utf8_lossy(&request[..header_end]);+ let content_length: usize = headers+ .lines()+ .filter_map(|line| line.split_once(':'))+ .find(|(name, _)| name.eq_ignore_ascii_case("content-length"))+ .map(|(_, value)| value.trim().parse().unwrap())+ .unwrap_or(0);+ if request.len() >= header_end + 4 + content_length {+ break;+ }+ }+ }+ before_response();+ let body = body.to_string();+ write!(stream, "HTTP/1.1 {status} Test\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap();+ String::from_utf8(request).unwrap()+ });+ (url, server)+}++fn seed(dir: &Path, url: &str) -> Value {+ let config = json!({+ "url": url, "api_key": OLD_KEY, "root_api_key": "root-secret",+ "echo_command": false, "timeout": 5,+ "plugin": {"capture": {"enabled": true}}, "unknown": [1, 2],+ // Identity headers are not authoritative in API-key mode.+ "account": "stale-account", "user": "stale-user"+ });+ fs::write(dir.join("selected.json"), config.to_string()).unwrap();+ fs::write(dir.join("ovcli.conf"), "unrelated config").unwrap();+ config+}++#[test]+fn self_rotation_updates_only_selected_api_key_and_announces_it() {+ let (url, server) = serve(+ 200,+ json!({"status":"ok", "result":{"user_key":NEW_KEY}}),+ || {},+ );+ let dir = tempfile::tempdir().unwrap();+ let mut expected = seed(dir.path(), &url);+ let result = run(+ dir.path(),+ &["admin", "regenerate-key", "acme", "alice", "-o", "json"],+ );+ let request = server.join().unwrap();+ assert!(request.contains("POST /api/v1/admin/accounts/acme/users/alice/key"));+ assert!(request.contains(OLD_KEY));+ assert!(result.status.success(), "{result:?}");+ assert_eq!(+ serde_json::from_slice::<Value>(&result.stdout).unwrap()["result"]["user_key"],+ NEW_KEY+ );+ let notice = String::from_utf8_lossy(&result.stderr);+ assert!(+ notice.contains("will update api_key in selected.json"),+ "{notice}"+ );+ assert!(+ notice.contains("Updated api_key in selected.json"),+ "{notice}"+ );+ assert!(!notice.contains(NEW_KEY));+ expected["api_key"] = json!(NEW_KEY);+ let saved: Value =+ serde_json::from_slice(&fs::read(dir.path().join("selected.json")).unwrap()).unwrap();+ assert_eq!(saved, expected);+ assert_eq!(+ fs::read_to_string(dir.path().join("ovcli.conf")).unwrap(),+ "unrelated config"+ );+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ assert_eq!(+ fs::metadata(dir.path().join("selected.json"))+ .unwrap()+ .permissions()+ .mode()+ & 0o777,+ 0o600+ );+ }+}++#[test]+fn failed_rotation_keeps_config_unchanged() {+ let (url, server) = serve(+ 403,+ json!({"status":"error", "error":{"code":"PERMISSION_DENIED","message":"denied"}}),+ || {},+ );+ let dir = tempfile::tempdir().unwrap();+ seed(dir.path(), &url);+ let original = fs::read(dir.path().join("selected.json")).unwrap();+ let result = run(+ dir.path(),+ &["admin", "regenerate-key", "acme", "alice", "-o", "json"],+ );+ server.join().unwrap();+ assert!(!result.status.success());+ assert_eq!(+ fs::read(dir.path().join("selected.json")).unwrap(),+ original+ );+ assert!(!String::from_utf8_lossy(&result.stderr).contains("Updated api_key"));+ assert!(!fs::read_dir(dir.path()).unwrap().any(|entry| {+ entry+ .unwrap()+ .file_name()+ .to_string_lossy()+ .ends_with(".tmp")+ }));+}++#[test]+fn concurrent_config_edit_is_preserved_and_rotated_key_is_recoverable() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("selected.json");+ let (url, server) = serve(+ 200,+ json!({"status":"ok", "result":{"user_key":NEW_KEY}}),+ move || {+ let mut config: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();+ config["plugin"] = json!({"changed": true});+ fs::write(path, config.to_string()).unwrap();+ },+ );+ let mut expected = seed(dir.path(), &url);+ expected["plugin"] = json!({"changed": true});+ let result = run(+ dir.path(),+ &["admin", "regenerate-key", "acme", "alice", "-o", "json"],+ );+ server.join().unwrap();+ assert!(!result.status.success());+ assert_eq!(+ serde_json::from_slice::<Value>(&result.stdout).unwrap()["result"]["user_key"],+ NEW_KEY+ );+ let notice = String::from_utf8_lossy(&result.stderr);+ assert!(+ notice.contains("API key was rotated, but could not update"),+ "{notice}"+ );+ assert!(notice.contains("manually"), "{notice}");+ assert_eq!(+ serde_json::from_slice::<Value>(&fs::read(dir.path().join("selected.json")).unwrap())+ .unwrap(),+ expected+ );+}++#[test]+fn rotating_another_user_or_using_sudo_does_not_replace_personal_config() {+ for args in [+ vec!["admin", "regenerate-key", "acme", "bob", "-o", "json"],+ vec![+ "--sudo",+ "admin",+ "regenerate-key",+ "acme",+ "alice",+ "-o",+ "json",+ ],+ ] {+ let (url, server) = serve(+ 200,+ json!({"status":"ok", "result":{"user_key":NEW_KEY}}),+ || {},+ );+ let dir = tempfile::tempdir().unwrap();+ seed(dir.path(), &url);+ let original = fs::read(dir.path().join("selected.json")).unwrap();+ let result = run(dir.path(), &args);+ server.join().unwrap();+ assert!(result.status.success(), "{result:?}");+ assert_eq!(+ fs::read(dir.path().join("selected.json")).unwrap(),+ original+ );+ assert!(!String::from_utf8_lossy(&result.stderr).contains("update api_key"));+ }+}++#[test]+fn rotation_updates_the_effective_credential_and_matching_custom_headers() {+ for (field, api_key, headers) in [+ (+ "extra_headers",+ json!(OLD_KEY),+ json!({"x-aPi-kEy": OLD_KEY, "Authorization": format!("Bearer {OLD_KEY}")}),+ ),+ (+ "extra_header",+ json!(OLD_KEY),+ json!({"X-API-Key": OLD_KEY}),+ ),+ (+ "extra_headers",+ json!("unused-key"),+ json!({"X-API-Key": OLD_KEY}),+ ),+ (+ "extra_headers",+ Value::Null,+ json!({"authorization": format!("Bearer {OLD_KEY}")}),+ ),+ ] {+ let dir = tempfile::tempdir().unwrap();+ let (url, server) = serve(+ 200,+ json!({"status":"ok", "result":{"user_key":NEW_KEY}}),+ || {},+ );+ let mut config = seed(dir.path(), &url);+ config["api_key"] = api_key;+ if config["api_key"].is_null() {+ // The Bearer-only row has no personal api_key: without dropping the+ // root fallback, admin commands would send X-API-Key: root-secret+ // and the Bearer header would never be the effective credential.+ config.as_object_mut().unwrap().remove("root_api_key");+ }+ config[field] = headers;+ config[field]["X-Custom"] = json!("preserved");+ let path = dir.path().join("selected.json");+ fs::write(&path, config.to_string()).unwrap();+ let result = run(+ dir.path(),+ &["admin", "regenerate-key", "acme", "alice", "-o", "json"],+ );+ server.join().unwrap();+ assert!(result.status.success(), "{result:?}");+ let mut saved: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();+ assert_eq!(saved["api_key"], NEW_KEY);+ assert_eq!(saved[field]["X-Custom"], "preserved");+ assert!(!saved.to_string().contains(OLD_KEY));+ assert!(+ String::from_utf8_lossy(&result.stderr).contains("matching authentication headers")+ );++ // A fresh CLI invocation must authenticate with the rotated key.+ let (url, server) = serve(200, json!({"status":"ok", "result":[]}), || {});+ saved["url"] = json!(url);+ fs::write(&path, saved.to_string()).unwrap();+ let result = run(dir.path(), &["admin", "list-users", "acme", "-o", "json"]);+ let request = server.join().unwrap();+ assert!(result.status.success(), "{result:?}");+ assert!(request.contains(NEW_KEY));+ assert!(!request.contains(OLD_KEY));+ }+}++#[test]+fn conflicting_header_credentials_fail_before_rotation() {+ let dir = tempfile::tempdir().unwrap();+ let mut config = seed(dir.path(), "http://127.0.0.1:1");+ config["extra_headers"] = json!({"X-API-Key": OLD_KEY, "x-api-key": NEW_KEY});+ let path = dir.path().join("selected.json");+ fs::write(&path, config.to_string()).unwrap();+ let result = run(+ dir.path(),+ &["admin", "regenerate-key", "acme", "alice", "-o", "json"],+ );+ assert!(!result.status.success());+ assert!(String::from_utf8_lossy(&result.stderr).contains("Conflicting X-API-Key headers"));+ assert_eq!(fs::read_to_string(path).unwrap(), config.to_string());+}++#[cfg(unix)]+#[test]+fn rotation_preserves_config_symlinks_and_updates_the_target() {+ let dir = tempfile::tempdir().unwrap();+ let (url, server) = serve(+ 200,+ json!({"status":"ok", "result":{"user_key":NEW_KEY}}),+ || {},+ );+ let mut expected = seed(dir.path(), &url);+ let selected = dir.path().join("selected.json");+ fs::create_dir(dir.path().join("shared")).unwrap();+ let target = dir.path().join("shared/ovcli.conf");+ fs::rename(&selected, &target).unwrap();+ std::os::unix::fs::symlink("shared/ovcli.conf", &selected).unwrap();+ let result = run(+ dir.path(),+ &["admin", "regenerate-key", "acme", "alice", "-o", "json"],+ );+ server.join().unwrap();+ assert!(result.status.success(), "{result:?}");+ assert_eq!(+ fs::read_link(&selected).unwrap(),+ Path::new("shared/ovcli.conf")+ );+ expected["api_key"] = json!(NEW_KEY);+ assert_eq!(+ serde_json::from_slice::<Value>(&fs::read(target).unwrap()).unwrap(),+ expected+ );+ assert_eq!(+ fs::read(selected).unwrap(),+ serde_json::to_vec_pretty(&expected).unwrap()+ );+}++#[cfg(unix)]+#[test]+fn retargeting_config_symlink_during_rotation_preserves_both_files() {+ let dir = tempfile::tempdir().unwrap();+ let selected = dir.path().join("selected.json");+ let changed_link = selected.clone();+ let (url, server) = serve(+ 200,+ json!({"status":"ok", "result":{"user_key":NEW_KEY}}),+ move || {+ fs::remove_file(&changed_link).unwrap();+ std::os::unix::fs::symlink("other.json", changed_link).unwrap();+ },+ );+ let config = seed(dir.path(), &url);+ let target = dir.path().join("target.json");+ let other = dir.path().join("other.json");+ fs::rename(&selected, &target).unwrap();+ fs::copy(&target, &other).unwrap();+ std::os::unix::fs::symlink("target.json", &selected).unwrap();+ let result = run(+ dir.path(),+ &["admin", "regenerate-key", "acme", "alice", "-o", "json"],+ );+ server.join().unwrap();+ assert!(!result.status.success());+ assert_eq!(fs::read_link(&selected).unwrap(), Path::new("other.json"));+ for file in [target, other] {+ assert_eq!(fs::read_to_string(file).unwrap(), config.to_string());+ }+ assert_eq!(+ serde_json::from_slice::<Value>(&result.stdout).unwrap()["result"]["user_key"],+ NEW_KEY+ );+ assert!(String::from_utf8_lossy(&result.stderr).contains("Config changed during key rotation"));+}diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.mdindex 387262c7a..354fc1c0e 100644--- a/docs/en/api/08-admin.md+++ b/docs/en/api/08-admin.md@@ -20,10 +20,11 @@ For `/api/v1/admin/*`, `trusted` mode permits requests with no explicit identity|-----------|------|-------|------|| Create/delete workspace | Y | N | N || List workspaces | Y | N | N |+| List users | Y | Y (own account) | Y (own account) || Register/remove users | Y | Y (own account) | N || Manage groups and membership | Y | Y (own account) | N || List agents (deprecated, returns empty list) | Y | Y (own account) | N |-| Regenerate user key (API Key mode only) | Y | Y (own account) | N |+| Regenerate user key (API Key mode only) | Y | Y (own account) | Y (own key) || Promote user to ADMIN | Y | Y (own account) | N |## CLI `--sudo` Option@@ -1589,7 +1590,7 @@ ov admin register-user acme bob-private --role user \List active users in a workspace. Users with deletion in progress are omitted.**Processing Flow:**-1. Verify requester has ROOT privileges or is an ADMIN of the account+1. Verify requester has ROOT privileges or is an ADMIN/USER of the account2. Call API Key Manager to get active users list (in creation order)3. Apply optional filters (name, role)4. Apply optional `limit`/`page` pagination@@ -1611,21 +1612,22 @@ 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. 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. |+| 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; USER receives only its own key. Set false to return `user_id`, `role`, and `api_key_available` without credentials or key prefixes. USER receives availability only for its own row. Availability 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-- 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.+- ADMIN and USER can only list users in their own account.+- ROOT receives every stored key as plaintext in `api_key`. ADMIN receives its own plaintext key and a masked `key_prefix` for every other user. USER authenticated with a personal API key receives only its own stored key; other rows omit both `api_key` and `key_prefix`. OAuth and other authentication methods do not grant USER access to stored credentials. 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. A mismatched key is masked for ADMIN and omitted for USER.+- ADMIN masking retains the first two key segments and only the last four characters of the secret; every preceding secret character is replaced by `*`. Secrets of four characters or fewer and malformed keys are completely hidden. Hash-only credentials cannot be recovered as plaintext; their existing prefix is visible to ROOT/ADMIN and to the owning USER only.- 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.+- `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 ADMIN/USER still sees only its own key. Other rows remain masked for ADMIN and contain no key or prefix for USER. 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.+- Registration and key regeneration still return the newly issued key to ROOT or ADMIN. USER may regenerate only its own key using personal API key authentication.- 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.+**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). USER responses omit `key_count`. 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.`query` performs a trimmed, case-insensitive literal substring match on user IDs. It combines with the existing `name` wildcard and `role` filters. For example:@@ -1687,12 +1689,13 @@ fmt.Println(users)**CLI**```bash-# Either ROOT or account ADMIN can execute-# If using regular user's api_key who is an ADMIN of acme:+# ROOT or an ADMIN/USER in acme can executeov admin list-users acme+# Reveal your own key (other users' credentials remain hidden for USER)+ov admin list-users acme --reveal-api-keys# 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)+# ROOT can reveal all available plaintext keysov --sudo admin list-users acme --reveal-api-keys# Filter by wildcard nameov admin list-users acme --name '*ali*'@@ -1916,7 +1919,7 @@ ov --sudo admin set-role acme bob adminGenerate and store a user API key. With the default random generation, the old key stops working after a successful update. Reusing the same account, user, and seed reproduces the same key; choose a new seed or omit it when rotating credentials.**Processing Flow:**-1. Verify requester has ROOT privileges or is an ADMIN of the account+1. Verify requester has ROOT privileges, is an ADMIN of the account, or is the target USER authenticated with a personal API key2. Call API Key Manager to regenerate user key3. With random generation or a new seed, the old key stops working immediately4. Return new user key@@ -1937,8 +1940,9 @@ Generate and store a user API key. With the default random generation, the old k| 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:**-- `trusted` mode rejects this operation with HTTP 412 (`FAILED_PRECONDITION`) without generating or modifying credentials.+- In `trusted` mode, ROOT/ADMIN requests receive HTTP 412 (`FAILED_PRECONDITION`); USER self-service requests receive HTTP 403. No credentials are generated or modified.- ADMIN can only regenerate keys for users in their own account+- USER can only regenerate its own key in its own account, authenticated with a personal API key. OAuth, trusted, OIDC, and LDAP identities cannot use USER self-service rotation.- With random generation or a new seed, the old key stops working immediately; update clients that use it- Omit `seed` for the default random regenerated key. Deterministic examples use `OV_KEY_SEED` or `OV_NEW_KEY_SEED`; set these to a securely generated secret before use. In Go, import `os`. Do not use the example variable names as seed values.@@ -2004,6 +2008,25 @@ ov admin regenerate-key acme bob --seed "$OV_NEW_KEY_SEED"ov --sudo admin regenerate-key acme bob```+For a USER authenticated as `acme/alice`:++```bash+ov admin list-users acme --reveal-api-keys+ov admin regenerate-key acme alice+```++When the target matches the personal `api_key` in the active configuration, the CLI+automatically updates that file's `api_key`, preserving other settings. It uses+`OPENVIKING_CLI_CONFIG_FILE` when set, otherwise `~/.openviking/ovcli.conf`.+Before requesting rotation it prints the destination path to stderr; after saving,+it confirms the update and reminds you to update other clients. JSON stdout remains+machine-readable. `--sudo` and rotation of another user's key do not update the local key.++The CLI checks that a replacement file can be prepared before requesting rotation.+If saving fails after the server rotates the key, or the configuration changes while+the request is in progress, the command exits with an error and keeps the returned+`user_key` in stdout for manual recovery. Save that key to the indicated configuration.+**Response Example**```jsondiff --git a/docs/en/guides/04-authentication.md b/docs/en/guides/04-authentication.mdindex 2dae1a4cb..6c90d3c04 100644--- a/docs/en/guides/04-authentication.md+++ b/docs/en/guides/04-authentication.md@@ -645,10 +645,10 @@ curl http://localhost:1933/health| GET | `/api/v1/admin/accounts` | ROOT | List all accounts || DELETE | `/api/v1/admin/accounts/{id}` | ROOT | Delete account || POST | `/api/v1/admin/accounts/{id}/users` | ROOT, ADMIN | Register user |-| GET | `/api/v1/admin/accounts/{id}/users` | ROOT, ADMIN | List users |+| GET | `/api/v1/admin/accounts/{id}/users` | ROOT, ADMIN, USER | List users; ADMIN/USER are limited to their own account || DELETE | `/api/v1/admin/accounts/{id}/users/{uid}` | ROOT, ADMIN | Remove user || PUT | `/api/v1/admin/accounts/{id}/users/{uid}/role` | ROOT, ADMIN | Promote a user to ADMIN; ADMIN is limited to its own account |-| POST | `/api/v1/admin/accounts/{id}/users/{uid}/key` | ROOT, ADMIN | Regenerate user key |+| POST | `/api/v1/admin/accounts/{id}/users/{uid}/key` | ROOT, ADMIN, USER | Regenerate user key; USER may rotate only its own key using personal API key authentication |## Custom Authentication Pluginsdiff --git a/docs/en/guides/06-mcp-integration.md b/docs/en/guides/06-mcp-integration.mdindex 434ee366a..95a37f1f5 100644--- a/docs/en/guides/06-mcp-integration.md+++ b/docs/en/guides/06-mcp-integration.md@@ -148,7 +148,7 @@ The built-in MCP tools are listed below. Use the connected server's `tools/list`| `privacy_tree` | Check which credentials are saved; return active field metadata and references without values | `category` (optional) || `privacy_resolve` | Turn a complete <code v-pre>{{ov_privacy:...}}</code> placeholder into one current field's actual value for immediate use | `reference` || `privacy_upsert` | Save user-supplied credential fields with an atomic merge; return metadata and references without values | `category`, `target_key`, `values` |-| `list_users` | Find user IDs in the caller's account; credentials are excluded by default, including for administrators | `query` (ID substring), `limit` (100), `page` (1), `include_credentials` (false; true requires ADMIN/ROOT) |+| `list_users` | Find user IDs in the caller's account; credentials are excluded by default, including for administrators | `query` (ID substring), `limit` (100), `page` (1), `include_credentials` (false; true applies role-based visibility) || `list_groups` | List group IDs in the caller's account without membership | None || `get_acl` | Read direct, inherited and effective ACL; requires resource manage or account ADMIN | `uri` || `set_acl` | Update a shared resource ACL; authorize against the permissions before the change | `uri`, `acl` |@@ -217,9 +217,10 @@ All account users may call `list_users` and `list_groups`; neither tool acceptsThe default output contains only user IDs and a matching total, or group IDs. Even administratorsmust explicitly set `include_credentials=true` to include credential fields: ROOT receivesevery 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.+`key_prefix` values for every other user. USER authenticated with a personal API key receives+only its own stored key (or prefix for hash-only storage); every other row omits both credential+fields. USER authenticated through OAuth or other methods receives no credentials. Trusted auth+mode forbids credential disclosure. Group membership remains available through the admin API.`get_acl` and `set_acl` require resource `manage` permission. A resource manager does not gainaccount administrator privileges. `write` and `add_resource` accept an optional `acl` object;diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.mdindex 3b0bd6b18..a51491bd1 100644--- a/docs/zh/api/08-admin.md+++ b/docs/zh/api/08-admin.md@@ -20,10 +20,11 @@ Admin API 用于多租户环境下的账户、用户和用户组管理。包括|------|------|-------|------|| 创建/删除工作区 | Y | N | N || 列出工作区 | Y | N | N |+| 列出用户 | Y | Y(本 account) | Y(本 account) || 注册/移除用户 | Y | Y(本 account) | N || 管理用户组和成员 | Y | Y(本 account) | N || 列出 agents(已废弃,返回空列表) | Y | Y(本 account) | N |-| 重新生成 User Key(仅 API Key 模式) | Y | Y(本 account) | N |+| 重新生成 User Key(仅 API Key 模式) | Y | Y(本 account) | Y(自身密钥) || 将用户提升为 ADMIN | Y | Y(本 account) | N |## CLI `--sudo` 选项@@ -1445,7 +1446,7 @@ ov admin register-user acme bob-private --role user \列出工作区中的活跃用户。正在删除中的用户不会返回。**处理流程:**-1. 验证请求者具有 ROOT 权限,或为本账户的 ADMIN+1. 验证请求者具有 ROOT 权限,或为本账户的 ADMIN/USER2. 调用 API Key Manager 获取活跃用户列表(按创建顺序排列)3. 应用可选的过滤条件(name、role)4. 应用可选的 `limit`/`page` 分页@@ -1467,21 +1468,22 @@ 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。ROOT 可获取可用的明文密钥,ADMIN 仅获取打码后的前缀。设为 false 时仅返回 `user_id`、`role` 和 `api_key_available`,不返回密钥或前缀;仅当服务端能读取完整 key 并用于服务端绑定时 `api_key_available` 才为 true,仅存哈希的凭据返回 false。 |+| include_credentials | bool | 否 | true | 仅 HTTP。ROOT 获取所有可用明文密钥;ADMIN 获取自身明文及他人的打码前缀;USER 仅获取自身密钥。设为 false 时返回 `user_id`、`role` 和 `api_key_available`,不返回密钥或前缀;USER 仅自身行包含可用状态。仅当服务端能读取完整 key 并用于服务端绑定时可用状态才为 true,仅存哈希的凭据返回 false。 || limit | int | 否 | null | 每页数量(≥1)。省略则返回所有匹配项 || page | int | 否 | 1 | 从 1 开始的页码;仅在设置了 `limit` 时生效 |**说明:**- 结果按创建顺序返回-- ADMIN 只能列出自己所属的 account 中的用户-- ROOT 可通过 `api_key` 获取全部已存储的明文密钥。非 ROOT 调用方只有自身那一行返回 `api_key` 明文,其他用户(包括其他 ADMIN)均返回打码后的 `key_prefix`。自身匹配是严格匹配:列表 account、行内 user ID 以及三段式 key 内嵌的 account/user 段必须全部等于调用方认证身份,否则该行仍打码。三段式密钥保留前两段和 secret 的最后 4 个字符,secret 中其余每个字符均替换为 `*`;secret 不超过 4 个字符时完全隐藏。非三段式密钥完全隐藏;仅存哈希的凭据沿用已有前缀。+- ADMIN 和 USER 只能列出自己所属 account 中的用户。+- ROOT 可通过 `api_key` 获取全部已存储的明文密钥。ADMIN 获取自身明文及他人的打码 `key_prefix`。使用个人 API Key 认证的 USER 仅获取自身已存储密钥,其他行不包含 `api_key` 或 `key_prefix`。OAuth 等其他认证方式不授予 USER 查看已存储凭据的权限。自身匹配是严格匹配:列表 account、行内 user ID 以及三段式 key 内嵌的 account/user 段必须全部等于调用方认证身份;不匹配的 key 对 ADMIN 打码,对 USER 隐藏。+- ADMIN 打码保留密钥前两段和 secret 的最后 4 个字符,secret 中其余每个字符均替换为 `*`;secret 不超过 4 个字符或密钥格式无效时完全隐藏。仅存哈希的凭据无法恢复明文,其已有前缀仅 ROOT/ADMIN 及凭据所属 USER 可见。- 打码在服务端执行,同时覆盖 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 尚无自助轮换接口。+- `ov admin list-users` 默认还会在 CLI 侧对明文 `api_key` 行使用相同格式打码,table 和 JSON 输出保持一致,并在 stderr 打印提示。传入 `--reveal-api-keys` 可输出明文:ROOT 会显示全部密钥,ADMIN/USER 仍只能看到自身密钥;其他行对 ADMIN 打码,对 USER 完全隐藏密钥和前缀。该 flag 只影响 CLI 渲染,不改变服务端响应。table 输出会把服务端的 `api_key`(明文或 CLI 打码值)与 `key_prefix` 合并为同一个 `api_key` 列;JSON 输出保留服务端的字段名。+- 创建用户与重置密钥仍会向 ROOT 或 ADMIN 返回新密钥;USER 使用个人 API Key 认证时可以重新生成自身密钥。- 在 `trusted` 模式下,响应中不会包含 `api_key` 或 `key_prefix` 字段- 用户删除开始后,不再出现在该列表中-**带统计的响应(HTTP):** 设置 `include_summary=true` 后,`result` 返回对象:`users` 为当前页,`total` 为匹配人数,`account_total` 为账号总人数,`manager_count` 为 admin/root 人数,`key_count` 为具有可见密钥或前缀的用户数。账号统计不受搜索和角色过滤影响,并排除正在删除的用户;禁用密钥展示时 `key_count` 为零。默认仍返回用户数组,兼容现有调用。+**带统计的响应(HTTP):** 设置 `include_summary=true` 后,`result` 返回对象:`users` 为当前页,`total` 为匹配人数,`account_total` 为账号总人数,`manager_count` 为 admin/root 人数,`key_count` 为具有可见密钥或前缀的用户数。USER 响应不包含 `key_count`。账号统计不受搜索和角色过滤影响,并排除正在删除的用户;禁用密钥展示时 `key_count` 为零。默认仍返回用户数组,兼容现有调用。`query` 对用户 ID 做去除首尾空格、不区分大小写的字面包含匹配,可与已有的 `name` 通配符、`role` 过滤组合。例如:@@ -1543,12 +1545,13 @@ fmt.Println(users)**CLI**```bash-# ROOT 或本账户的 ADMIN 都可以执行-# 如果使用普通用户的 api_key 但该用户是 acme 的 ADMIN:+# ROOT 或 acme 中的 ADMIN/USER 都可以执行ov admin list-users acme+# 显示自己的明文密钥(USER 仍看不到其他用户的密钥或前缀)+ov admin list-users acme --reveal-api-keys# 如果使用 root_api_key(--sudo):ov --sudo admin list-users acme-# 输出明文密钥而不是打码值(仅 ROOT)+# ROOT 可显示全部可用的明文密钥ov --sudo admin list-users acme --reveal-api-keys# 按通配符 name 过滤ov admin list-users acme --name '*ali*'@@ -1771,7 +1774,7 @@ ov --sudo admin set-role acme bob admin生成并保存用户的 API Key。默认随机生成时,更新成功后旧 Key 失效。同一 account、user 和 seed 会生成相同的 Key;轮换密钥时应使用新 seed,或省略 seed。**处理流程:**-1. 验证请求者具有 ROOT 权限,或为本账户的 ADMIN+1. 验证请求者具有 ROOT 权限、为本账户的 ADMIN,或为使用个人 API Key 认证的目标 USER2. 调用 API Key Manager 重新生成用户密钥3. 随机生成或使用新 seed 时,旧密钥立即失效4. 返回新的用户密钥@@ -1792,8 +1795,9 @@ ov --sudo admin set-role acme bob admin| seed | str | 否 | `null` | JSON request body 中可选的确定性 API Key seed。传入后,key secret 为 `sha256(user_id + "\0" + seed)` |**说明:**-- `trusted` 模式拒绝此操作,返回 HTTP 412(`FAILED_PRECONDITION`),不生成或修改密钥。+- `trusted` 模式下,ROOT/ADMIN 请求返回 HTTP 412(`FAILED_PRECONDITION`),USER 自助轮换返回 HTTP 403,均不生成或修改密钥。- ADMIN 只能为自己所属的 account 中的用户重新生成密钥+- USER 仅能使用个人 API Key 认证,轮换本 account 下的自身密钥。OAuth、trusted、OIDC 和 LDAP 身份不能使用 USER 自助轮换。- 随机生成或使用新 seed 时,旧密钥立即失效,需要更新使用该密钥的客户端- 省略 `seed` 时随机生成新密钥。确定性示例使用 `OV_KEY_SEED` 或 `OV_NEW_KEY_SEED`,运行前需将其设为安全生成的秘密值;Go 示例需导入 `os`。不要把示例变量名直接当作 seed。@@ -1859,6 +1863,22 @@ ov admin regenerate-key acme bob --seed "$OV_NEW_KEY_SEED"ov --sudo admin regenerate-key acme bob```+以普通 USER `acme/alice` 的身份调用:++```bash+ov admin list-users acme --reveal-api-keys+ov admin regenerate-key acme alice+```++当目标与当前配置中的个人 `api_key` 身份匹配时,CLI 自动更新该配置文件的 `api_key`,+保留其他设置。配置路径优先使用 `OPENVIKING_CLI_CONFIG_FILE`,否则为+`~/.openviking/ovcli.conf`。CLI 在请求轮换前向 stderr 提示将写入的文件路径,+保存成功后确认更新,并提醒同步其他客户端;JSON stdout 保持可解析。+使用 `--sudo` 或轮换其他用户的密钥时,不自动修改本地密钥。++CLI 在请求轮换前检查能否准备替换文件。如果服务端已换钥但保存失败,或请求期间配置被修改,+命令返回非零退出码并明确报错,stdout 仍保留返回的 `user_key`,供手动恢复到提示的配置文件中。+**响应示例**```jsondiff --git a/docs/zh/guides/04-authentication.md b/docs/zh/guides/04-authentication.mdindex e46592130..07eb8e8c8 100644--- a/docs/zh/guides/04-authentication.md+++ b/docs/zh/guides/04-authentication.md@@ -732,7 +732,7 @@ ov config validate| GET | `/api/v1/admin/accounts` | ROOT | 列出所有工作区 || DELETE | `/api/v1/admin/accounts/{id}` | ROOT | 删除工作区 || POST | `/api/v1/admin/accounts/{id}/users` | ROOT, ADMIN | 注册用户 |-| GET | `/api/v1/admin/accounts/{id}/users` | ROOT, ADMIN | 列出用户 |+| GET | `/api/v1/admin/accounts/{id}/users` | ROOT, ADMIN, USER | 列出用户;ADMIN/USER 仅限本账户 || DELETE | `/api/v1/admin/accounts/{id}/users/{uid}` | ROOT, ADMIN | 移除用户 || PUT | `/api/v1/admin/accounts/{id}/users/{uid}/role` | ROOT, ADMIN | 将用户提升为 ADMIN;ADMIN 仅限本账户 |-| POST | `/api/v1/admin/accounts/{id}/users/{uid}/key` | ROOT, ADMIN | 重新生成 user key |+| POST | `/api/v1/admin/accounts/{id}/users/{uid}/key` | ROOT, ADMIN, USER | 重新生成 user key;USER 仅能使用个人 API Key 认证轮换自身密钥 |diff --git a/docs/zh/guides/06-mcp-integration.md b/docs/zh/guides/06-mcp-integration.mdindex cc8db58e2..b356094eb 100644--- a/docs/zh/guides/06-mcp-integration.md+++ b/docs/zh/guides/06-mcp-integration.md@@ -144,7 +144,7 @@ claude mcp add --transport http openviking \| `privacy_tree` | 盘点已保存的凭据;返回当前字段元数据及引用,不含值 | `category`(可选) || `privacy_resolve` | 将完整的 <code v-pre>{{ov_privacy:...}}</code> 占位符解析为一个当前字段的实际值,供立即使用 | `reference` || `privacy_upsert` | 原子合并用户提供的凭据字段;返回元数据和引用,不回显值 | `category`, `target_key`, `values` |-| `list_users` | 查询当前 account 的用户 ID;默认不返回凭证,管理员也一样 | `query`(可选,ID 子串), `limit`(默认 100), `page`(默认 1), `include_credentials`(默认 false,仅 ADMIN/ROOT 可设为 true) |+| `list_users` | 查询当前 account 的用户 ID;默认不返回凭证,管理员也一样 | `query`(可选,ID 子串), `limit`(默认 100), `page`(默认 1), `include_credentials`(默认 false,true 时按角色限制可见范围) || `list_groups` | 查询当前 account 的组 ID,不返回成员名单 | 无 || `get_acl` | 查看共享资源的直接、继承和有效 ACL;要求该节点的 manage 或账号 ADMIN | `uri` || `set_acl` | 设置共享资源 ACL;按修改前的权限校验 manage | `uri`, `acl` |@@ -204,8 +204,9 @@ tree 和 resolve 标记为只读,upsert 标记为可能覆盖数据的写入`list_users`、`list_groups` 对当前 account 的普通用户开放,不接受跨 account 查询参数。`list_users` 默认仅返回 `user_id` 和匹配总数,`list_groups` 仅返回 `group_id`。管理员也必须显式传 `include_credentials=true` 才会返回凭证字段:ROOT 可获得全部 `api_key` 明文,-ADMIN 仅自身记录为 `api_key` 明文,其他用户一律为打码后的 `key_prefix`;普通用户传该参数会得到-`PERMISSION_DENIED`,即使查询结果为空也一样。trusted 鉴权模式禁止返回凭证。+ADMIN 仅自身记录为 `api_key` 明文,其他用户一律为打码后的 `key_prefix`;使用个人 API Key+认证的 USER 仅获取自身已存储密钥(仅存哈希时为前缀),其他行不包含密钥或前缀。+通过 OAuth 等其他方式认证的 USER 不返回凭据。trusted 鉴权模式禁止返回凭证。组成员管理和成员名单查询仍使用管理员接口。完整 ACL 的查询和修改都要求资源的 `manage` 权限;普通用户即使是资源 manager,也不会因此获得diff --git a/openviking/server/account_stores/base.py b/openviking/server/account_stores/base.pyindex 0af056b73..8ad08afc1 100644--- a/openviking/server/account_stores/base.py+++ b/openviking/server/account_stores/base.py@@ -190,7 +190,14 @@ class AccountStore(ABC):account_id: str,user_id: str,api_key: str,- ) -> None: ...+ *,+ expected_api_key: str | None = None,+ ) -> None:+ """Replace the key, atomically checking the active key when supplied.++ A revoked or superseded expected key must raise UnauthenticatedError.+ """+ ...@abstractmethodasync def revoke_active_api_keys(self, account_id: str, user_id: str | None = None) -> None: ...diff --git a/openviking/server/account_stores/file.py b/openviking/server/account_stores/file.pyindex ca2aaca6e..01b5c6788 100644--- a/openviking/server/account_stores/file.py+++ b/openviking/server/account_stores/file.py@@ -39,6 +39,7 @@ from openviking_cli.exceptions import (FailedPreconditionError,InvalidArgumentError,NotFoundError,+ UnauthenticatedError,)from openviking_cli.session.user_id import (validate_account_id,@@ -553,6 +554,7 @@ class FileStore(AccountStore):api_key: str,*,rotate: bool,+ expected_api_key: str | None = None,) -> None:"""Persist one credential in the legacy user record."""self._ensure_account_active(account_id)@@ -580,7 +582,13 @@ class FileStore(AccountStore):else:user_info.pop("key_prefix", None)try:- await self._save_users_json(account_id, {user_id: user_info})+ await self._save_users_json(+ account_id,+ {user_id: user_info},+ expected_api_keys={user_id: expected_api_key}+ if expected_api_key is not None+ else None,+ )except Exception:account.users[user_id] = old_user_infoself._rebuild_prefix_index()@@ -1364,6 +1372,7 @@ class FileStore(AccountStore):deleted_user_ids: set[str] | None = None,reject_existing_user_ids: set[str] | None = None,replace_existing: bool = False,+ expected_api_keys: dict[str, str] | None = None,) -> None:"""Merge targeted user mutations, or initialize a newly created account."""path = USERS_PATH_TEMPLATE.format(account_id=account_id)@@ -1382,6 +1391,14 @@ class FileStore(AccountStore):else:data = await self._read_json(path) or {"users": {}}users = data.setdefault("users", {})+ # Check persisted credentials while holding the cross-instance lease.+ # Request-time authentication and the local cache may already be stale.+ for user_id, expected_key in (expected_api_keys or {}).items():+ current_user = users.get(user_id, {})+ if current_user.get("deletion") or not await self._key_matches(+ current_user.get("key", ""), expected_key+ ):+ raise UnauthenticatedError("API key is no longer active")if updated_users is None:account = self._accounts.get(account_id)if account is None:@@ -1684,7 +1701,8 @@ class FileStore(AccountStore):await self._delete_group(account_id, group_id)async def replace_active_user_api_key(- self, account_id: str, user_id: str, api_key: str+ self, account_id: str, user_id: str, api_key: str,+ *, expected_api_key: str | None = None,) -> None:async with self._mutation_lock:await self._set_user_key(@@ -1692,8 +1710,20 @@ class FileStore(AccountStore):user_id,api_key,rotate=True,+ expected_api_key=expected_api_key,)+ @staticmethod+ async def _key_matches(material: str, api_key: str) -> bool:+ if not material:+ return False+ if not material.startswith("$argon2"):+ return hmac.compare_digest(material, api_key)+ try:+ return await asyncio.to_thread(PasswordHasher().verify, material, api_key)+ except VerificationError:+ return False+async def verify_api_key(self,api_key: str,@@ -1712,23 +1742,7 @@ class FileStore(AccountStore):user = account.users.get(entry.user_id)if user is None or user.get("deletion"):continue- if entry.is_hashed:- try:- matched = await asyncio.to_thread(- PasswordHasher(- time_cost=ARGON2_TIME_COST,- memory_cost=ARGON2_MEMORY_COST,- parallelism=ARGON2_PARALLELISM,- hash_len=ARGON2_HASH_LENGTH,- ).verify,- entry.key_or_hash,- api_key,- )- except VerificationError:- matched = False- else:- matched = hmac.compare_digest(entry.key_or_hash, api_key)- if matched:+ if await self._key_matches(entry.key_or_hash, api_key):return entry.account_id, entry.user_idreturn Nonediff --git a/openviking/server/account_stores/mysql.py b/openviking/server/account_stores/mysql.pyindex 098c7b8fc..33d86586e 100644--- a/openviking/server/account_stores/mysql.py+++ b/openviking/server/account_stores/mysql.py@@ -57,6 +57,7 @@ from openviking_cli.exceptions import (InvalidArgumentError,NotFoundError,PermissionDeniedError,+ UnauthenticatedError,)from openviking_cli.session.user_id import (validate_account_id,@@ -1170,13 +1171,29 @@ class MySQLAccountStore(AccountStore):await session.delete(group)async def replace_active_user_api_key(- self, account_id: str, user_id: str, api_key: str+ self, account_id: str, user_id: str, api_key: str,+ *, expected_api_key: str | None = None,) -> None:async with self._transaction() as session:account = await self._lock_account(session, account_id)self._require_active(account)user = await self._lock_user(session, account, user_id)self._require_active(user)+ if expected_api_key is not None:+ # A locking read observes the current credential, even when a+ # concurrent reset committed after request authentication.+ current = await session.scalar(+ select(Credential.credential_id)+ .where(+ Credential.service_name == self._service_name,+ Credential.user_pk == user.user_pk,+ Credential.revoked.is_(False),+ Credential.lookup_digest == _credential_digest(expected_api_key),+ )+ .with_for_update()+ )+ if current is None:+ raise UnauthenticatedError("API key is no longer active")sequence = await session.scalar(select(func.coalesce(func.max(Credential.sequence), 0)).where(Credential.service_name == self._service_name,diff --git a/openviking/server/account_stores/redis_mysql.py b/openviking/server/account_stores/redis_mysql.pyindex c21f9c920..9df3fcef9 100644--- a/openviking/server/account_stores/redis_mysql.py+++ b/openviking/server/account_stores/redis_mysql.py@@ -961,11 +961,14 @@ class RedisMySQLAccountStore(AccountStore):)async def replace_active_user_api_key(- self, account_id: str, user_id: str, api_key: str+ self, account_id: str, user_id: str, api_key: str,+ *, expected_api_key: str | None = None,) -> None:await self._mutate_account(account_id,- lambda: self._mysql.replace_active_user_api_key(account_id, user_id, api_key),+ lambda: self._mysql.replace_active_user_api_key(+ account_id, user_id, api_key, expected_api_key=expected_api_key+ ),lambda: ((self._user_credential_fence_key(account_id, user_id),)+ self._binding_cache_keys(account_id, api_key, user_id)diff --git a/openviking/server/api_keys/new.py b/openviking/server/api_keys/new.pyindex 112f4b0f9..f1a10c08d 100644--- a/openviking/server/api_keys/new.py+++ b/openviking/server/api_keys/new.py@@ -180,12 +180,14 @@ class APIKeyManager:await self._store.create_user_with_api_key(account_id, user_id, role, key)return key- async def regenerate_key(self, account_id, user_id, seed=None):+ async def regenerate_key(self, account_id, user_id, seed=None, *, expected_api_key=None):if not self._issue_user_keys:raise FailedPreconditionError("Personal API keys are disabled in trusted mode")await self._require_manageable_user(account_id, user_id)key = generate_api_key(account_id, user_id, seed)- await self._store.replace_active_user_api_key(account_id, user_id, key)+ await self._store.replace_active_user_api_key(+ account_id, user_id, key, expected_api_key=expected_api_key+ )return keyasync def get_registered_user_role(self, account_id: str, user_id: str) -> Role | None:@@ -248,6 +250,7 @@ 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)+ hide_other_keys = filters.pop("hide_other_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)@@ -272,8 +275,14 @@ class APIKeyManager:for user in page["users"]:user.pop("api_key", None)user.pop("key_prefix", None)- elif mask_keys:+ elif mask_keys or hide_other_keys:for user in page["users"]:+ if hide_other_keys and (+ account_id != viewer_account_id or user.get("user_id") != viewer_user_id+ ):+ user.pop("api_key", None)+ user.pop("key_prefix", None)+ continueif api_key := user.pop("api_key", None):if self._is_viewer_own_key(api_key,@@ -283,8 +292,10 @@ class APIKeyManager:viewer_user_id,):user["api_key"] = api_key- else:+ elif not hide_other_keys:user["key_prefix"] = mask_api_key(api_key)+ else:+ user.pop("key_prefix", None)return page@staticmethoddiff --git a/openviking/server/auth/__init__.py b/openviking/server/auth/__init__.pyindex 9ecf4f49c..ace1ff18c 100644--- a/openviking/server/auth/__init__.py+++ b/openviking/server/auth/__init__.py@@ -357,7 +357,7 @@ _DEV_MODE_ADMIN_API_MESSAGE = ()-def require_auth_role(*allowed_roles: Role):+def require_auth_role(*allowed_roles: str):"""Decorator for Admin API routes with mode-aware errors.Usage:@@ -442,3 +442,13 @@ def should_expose_user_key(request: Request) -> bool:if not isinstance(config, ServerConfig):return Truereturn config.get_effective_auth_mode() != "trusted"+++def is_personal_api_key_auth(request: Request | None, ctx: RequestContext) -> bool:+ """Self-service credentials require a personal key, not a delegated token."""+ return (+ request is not None+ and _auth_mode(request) == "api_key"+ and not ctx.from_oauth+ and bool(ctx.api_key)+ )diff --git a/openviking/server/auth/plugins/trusted.py b/openviking/server/auth/plugins/trusted.pyindex 7176ef015..806c12cf2 100644--- a/openviking/server/auth/plugins/trusted.py+++ b/openviking/server/auth/plugins/trusted.py@@ -18,8 +18,8 @@ from openviking.core.identifiers import (validate_identifier_part,validate_user_id,)-from openviking.server.api_keys import APIKeyManagerfrom openviking.server.account_stores.file import validate_file_account_id+from openviking.server.api_keys import APIKeyManagerfrom openviking.server.auth.plugin import AuthPluginfrom openviking.server.identity import ResolvedIdentity, Rolefrom openviking.server.store_assembly import build_api_key_manager@@ -170,7 +170,15 @@ class TrustedAuthPlugin(AuthPlugin):# parameters such as ``account_id`` identify the managed resource, so# they must not be mistaken for a partial caller identity.is_admin_path = _is_trusted_admin_path(request.url.path)- if is_admin_path:+ # A key-only health probe reports control-plane identity. Probes with+ # tenant identity keep reporting the asserted/resolved data-plane role.+ is_control_probe = (+ request.url.path == "/health"+ and not effective_account_id+ and not effective_user_id+ and asserted_role is None+ )+ if is_admin_path or is_control_probe:return ResolvedIdentity(role=Role.ROOT,account_id=effective_account_id or "trusted",diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.pyindex 7c0e51a7b..bc8cf82ad 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -69,6 +69,7 @@ from openviking.server.auth import (_build_request_context,_extract_api_key,get_api_key_manager_or_raise,+ is_personal_api_key_auth,normalize_actor_peer_header,resolve_identity,should_expose_user_key,@@ -371,15 +372,15 @@ async def list_users() -> dict[str, Any]:"""Find users to grant access to in the caller's account. Returns user_id andmatching total by default, including for administrators. query matches a- substring of user_id. include_credentials=true requires ADMIN or ROOT and- 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.+ substring of user_id. include_credentials=true returns all keys to ROOT,+ the caller's own key and masked prefixes to ADMIN, and only the caller's own+ key to USER authenticated with a personal API key. Other users' keys and+ prefixes are omitted for USER. Credential disclosure is forbidden in trusted mode.Resource manage permission does not grant account administrator privileges."""ctx = _get_ctx()- if include_credentials and ctx.role not in (Role.ADMIN, Role.ROOT):- raise PermissionDeniedError("include_credentials requires ADMIN or ROOT role")+ if include_credentials and ctx.role not in (Role.USER, Role.ADMIN, Role.ROOT):+ raise PermissionDeniedError("include_credentials requires USER, ADMIN or ROOT role")request = context.request_context.requestif include_credentials and not should_expose_user_key(request):raise PermissionDeniedError("Credential disclosure is disabled in trusted auth mode")@@ -389,8 +390,10 @@ async def list_users(limit=limit,page=page,query_filter=query,- expose_key=include_credentials,+ expose_key=include_credentials+ and (ctx.role != Role.USER or is_personal_api_key_auth(request, ctx)),mask_keys=ctx.role != Role.ROOT,+ hide_other_keys=ctx.role == Role.USER,viewer_account_id=ctx.account_id,viewer_user_id=ctx.user.user_id,)diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.pyindex 1b0a32c02..412072692 100644--- a/openviking/server/routers/admin.py+++ b/openviking/server/routers/admin.py@@ -16,6 +16,8 @@ from openviking.server.api_keys.models import validate_account_user_rolefrom openviking.server.auth import (get_api_key_manager_or_raise,get_request_context,+ is_personal_api_key_auth,+ require_auth_role,require_auth_root,require_auth_root_or_admin,should_expose_user_key,@@ -240,9 +242,9 @@ def _get_runtime_config_manager():def _check_account_access(ctx: RequestContext, account_id: str) -> None:- """ADMIN can only operate on their own account."""- if ctx.role == Role.ADMIN and ctx.account_id != account_id:- raise PermissionDeniedError(f"ADMIN can only manage account: {ctx.account_id}")+ """Non-ROOT callers can only operate on their own account."""+ if ctx.role != Role.ROOT and ctx.account_id != account_id:+ raise PermissionDeniedError(f"{ctx.role} can only access account: {ctx.account_id}")async def _check_account_exists(request: Request, account_id: str):@@ -1006,7 +1008,7 @@ async def register_user(@router.get("/accounts/{account_id}/users")-@require_auth_root_or_admin+@require_auth_role(Role.ROOT, Role.ADMIN, Role.USER)async def list_users(request: Request,account_id: str = Path(..., description="Account ID"),@@ -1014,8 +1016,8 @@ async def list_users(include_credentials: bool = Query(True,description=(- "Include credentials: ROOT receives all plaintext keys; ADMIN/USER receive the "- "caller's own plaintext key and masked key_prefix for other users; "+ "Include credentials: ROOT receives all plaintext keys; ADMIN receives its own "+ "key and masked prefixes for others; USER receives only its own key; ""false returns only availability"),),@@ -1031,13 +1033,17 @@ async def list_users("""List users in an account, in creation order. `name` supports wildcard (* and ?) matching."""_check_account_access(ctx, account_id)manager = _get_api_key_manager(request)+ expose_key = should_expose_user_key(request) or not include_credentials+ if ctx.role == Role.USER:+ expose_key = expose_key and is_personal_api_key_auth(request, ctx)users = await manager.list_users_page(account_id,limit=limit,name_filter=name,role_filter=role,- expose_key=should_expose_user_key(request) or not include_credentials,+ expose_key=expose_key,mask_keys=include_credentials and ctx.role != Role.ROOT,+ hide_other_keys=ctx.role == Role.USER,viewer_account_id=ctx.account_id,viewer_user_id=ctx.user.user_id,page=page,@@ -1050,10 +1056,16 @@ async def list_users("role": user["role"],# A key prefix identifies a hash-only credential, which cannot# be supplied to server-side Gateway or Bot Studio bindings.- "api_key_available": bool(user.get("api_key")),+ **(+ {"api_key_available": bool(user.get("api_key"))}+ if ctx.role != Role.USER or user["user_id"] == ctx.user.user_id+ else {}+ ),}for user in users["users"]]+ if ctx.role == Role.USER:+ users.pop("key_count", None)return Response(status="ok", result=users if include_summary else users["users"])@@ -1183,7 +1195,7 @@ async def set_user_role(@router.post("/accounts/{account_id}/users/{user_id}/key")-@require_auth_root_or_admin+@require_auth_role(Role.ROOT, Role.ADMIN, Role.USER)async def regenerate_key(request: Request,body: RegenerateKeyRequest | None = Body(default=None),@@ -1193,11 +1205,17 @@ async def regenerate_key():"""Regenerate a user's API key. Old key is immediately invalidated."""_check_account_access(ctx, account_id)+ if ctx.role == Role.USER:+ if user_id != ctx.user.user_id:+ raise PermissionDeniedError("USER can only regenerate their own API key")+ if not is_personal_api_key_auth(request, ctx):+ raise PermissionDeniedError("Self-service key rotation requires a personal API key")manager = _get_api_key_manager(request)new_key = await manager.regenerate_key(account_id,user_id,seed=body.seed if body is not None else None,+ expected_api_key=ctx.api_key if ctx.role == Role.USER else None,)return Response(status="ok", result={"user_key": new_key})diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.pyindex fb71c3234..7ff59e17f 100644--- a/tests/server/test_admin_api.py+++ b/tests/server/test_admin_api.py@@ -2885,7 +2885,7 @@ async def test_list_users(admin_client: httpx.AsyncClient):@pytest.mark.parametrize("include_summary", [False, True])@pytest.mark.parametrize("include_credentials", [None, True, False])-async def test_user_list_masks_credentials_for_admin_only(+async def test_user_list_credentials_follow_caller_role(lightweight_admin_client, lightweight_admin_app, include_summary, include_credentials):manager = lightweight_admin_app.state.api_key_manager@@ -2904,6 +2904,7 @@ async def test_user_list_masks_credentials_for_admin_only(callers = [(admin_key, "owner", False),(keys["manager"], "manager", False),+ (keys["alice"], "alice", False),(ROOT_KEY, None, True),]for caller_key, caller_id, is_root in callers:@@ -2915,13 +2916,19 @@ async def test_user_list_masks_credentials_for_admin_only(assert response.status_code == 200result = response.json()["result"]if include_summary:- assert result["total"] == result["account_total"] == result["key_count"] == 3+ assert result["total"] == result["account_total"] == 3+ if caller_id == "alice":+ assert "key_count" not in result+ else:+ assert result["key_count"] == 3result = result["users"]users.extend(result)assert len(users) == 3for user in users:key = keys[user["user_id"]]- if include_credentials is False:+ if caller_id == "alice" and user["user_id"] != caller_id:+ assert set(user) == {"user_id", "role"}+ elif include_credentials is False:assert user["api_key_available"] is Trueassert "api_key" not in user and "key_prefix" not in userelif is_root or user["user_id"] == caller_id:@@ -2944,7 +2951,109 @@ async def test_user_list_masks_credentials_for_admin_only(assert other_key.split(".")[2] not in payloadassert (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 == 200++[email protected]("seed", [None, "new-self-service-seed"])+async def test_user_can_rotate_only_their_own_key(+ lightweight_admin_client, lightweight_admin_app, seed+):+ manager = lightweight_admin_app.state.api_key_manager+ account = _uid()+ admin_key = await manager.create_account(account, "owner")+ old_key = await manager.register_user(account, "alice")+ await manager.create_account("other", "alice")+ headers = {"X-API-Key": old_key, "X-OpenViking-User": "owner", "X-OpenViking-Account": "other"}+ for target_account, target_user in [(account, "owner"), ("other", "alice")]:+ denied = await lightweight_admin_client.post(+ f"/api/v1/admin/accounts/{target_account}/users/{target_user}/key", headers=headers+ )+ assert denied.status_code == 403+ denied = await lightweight_admin_client.get(+ "/api/v1/admin/accounts/other/users", headers=headers+ )+ assert denied.status_code == 403+ response = await lightweight_admin_client.post(+ f"/api/v1/admin/accounts/{account}/users/alice/key",+ headers=headers,+ json={"seed": seed} if seed else {},+ )+ assert response.status_code == 200+ new_key = response.json()["result"]["user_key"]+ assert new_key != old_key+ url = f"/api/v1/admin/accounts/{account}/users"+ assert (+ await lightweight_admin_client.get(url, headers={"X-API-Key": old_key})+ ).status_code == 401+ current = await lightweight_admin_client.get(url, headers={"X-API-Key": new_key})+ assert current.status_code == 200+ assert current.json()["result"][1]["api_key"] == new_key+ assert (await manager.resolve_identity(admin_key)).role == Role.ADMIN+++ "auth_mode,from_oauth",+ [("api_key", True), ("oidc", False), ("ldap", False), ("trusted", False)],+)+async def test_user_other_auth_cannot_disclose_or_rotate_personal_key(+ lightweight_admin_client, lightweight_admin_app, auth_mode, from_oauth+):+ from openviking.server.auth import get_request_context++ manager = lightweight_admin_app.state.api_key_manager+ account = _uid()+ await manager.create_account(account, "owner")+ key = await manager.register_user(account, "alice")+ lightweight_admin_app.state.config = lightweight_admin_app.state.config.model_copy(+ update={"auth_mode": auth_mode}+ )+ lightweight_admin_app.dependency_overrides[get_request_context] = lambda: RequestContext(+ UserIdentifier(account, "alice"), Role(Role.USER), from_oauth=from_oauth, api_key="identity-token"+ )+ response = await lightweight_admin_client.get(f"/api/v1/admin/accounts/{account}/users")+ assert response.status_code == 200+ assert all(set(row) == {"user_id", "role"} for row in response.json()["result"])+ response = await lightweight_admin_client.post(+ f"/api/v1/admin/accounts/{account}/users/alice/key"+ )assert response.status_code == 403+ assert (await manager.resolve_identity(key)).user_id == "alice"+++async def test_in_flight_user_rotation_cannot_overwrite_admin_reset(+ lightweight_admin_client, lightweight_admin_app, monkeypatch+):+ manager = lightweight_admin_app.state.api_key_manager+ account = _uid()+ await manager.create_account(account, "owner")+ old_key = await manager.register_user(account, "alice")+ authenticated = asyncio.Event()+ resume = asyncio.Event()+ regenerate = manager.regenerate_key++ async def pause_user_rotation(*args, **kwargs):+ if kwargs.get("expected_api_key") == old_key:+ authenticated.set()+ await resume.wait()+ return await regenerate(*args, **kwargs)++ monkeypatch.setattr(manager, "regenerate_key", pause_user_rotation)+ path = f"/api/v1/admin/accounts/{account}/users/alice/key"+ pending = asyncio.create_task(+ lightweight_admin_client.post(path, headers={"X-API-Key": old_key})+ )+ try:+ await asyncio.wait_for(authenticated.wait(), timeout=5)+ reset = await lightweight_admin_client.post(path, headers={"X-API-Key": ROOT_KEY})+ assert reset.status_code == 200+ reset_key = reset.json()["result"]["user_key"]+ finally:+ resume.set()+ response = await asyncio.wait_for(pending, timeout=5)+ assert response.status_code == 401+ url = f"/api/v1/admin/accounts/{account}/users"+ assert (await lightweight_admin_client.get(url, headers={"X-API-Key": reset_key})).status_code == 200+ assert (await lightweight_admin_client.get(url, headers={"X-API-Key": old_key})).status_code == 401@pytest.mark.parametrize(@@ -3035,12 +3144,33 @@ async def test_user_key_mask_reveals_only_the_viewers_own_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- )+ 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_user_list_hides_other_prefixes_and_mismatched_keys():+ from openviking.server.api_keys import APIKeyManager, generate_api_key++ store = Mock()+ store.list_users_page = AsyncMock(+ return_value={+ "users": [+ {+ "user_id": "alice",+ "api_key": generate_api_key("other", "alice"),+ "key_prefix": "other-prefix",+ },+ {"user_id": "hashed", "key_prefix": "sensitive-prefix"},+ ],+ "key_count": 2,+ }+ )+ page = await APIKeyManager("root", store).list_users_page(+ "acme", hide_other_keys=True, viewer_account_id="acme", viewer_user_id="alice"+ )+ assert page["users"] == [{"user_id": "alice"}, {"user_id": "hashed"}]++async def test_remove_user(admin_client: httpx.AsyncClient,admin_service: OpenVikingService,@@ -3259,8 +3389,8 @@ async def test_empty_seed_rejected(admin_client: httpx.AsyncClient):# ---- Permission guard -----async def test_user_role_cannot_access_admin_api(admin_client: httpx.AsyncClient):- """USER role should not access admin endpoints."""+async def test_user_role_cannot_register_users(admin_client: httpx.AsyncClient):+ """USER self-service does not grant user-management privileges."""acct = _uid()await admin_client.post("/api/v1/admin/accounts",@@ -3788,7 +3918,7 @@ async def test_user_page_summary_and_search_preserve_legacy_response(request = FastAPIRequest({"type": "http", "app": lightweight_admin_app})context = SimpleNamespace(request_context=SimpleNamespace(request=request))for role in (Role.USER, Role.ADMIN, Role.ROOT):- identity = RequestContext(UserIdentifier(acct, "user-1"), role)+ identity = RequestContext(UserIdentifier(acct, "user-1"), role, api_key="personal-key")token = mcp_endpoint._mcp_ctx.set(identity)try:directory = await mcp_endpoint.list_users(context, query="user-112")@@ -3796,35 +3926,43 @@ async def test_user_page_summary_and_search_preserve_legacy_response(assert await mcp_endpoint.list_groups(context) == {"groups": [{"group_id": "engineering"}]}- if role == Role.USER:- # Explicit opt-in is rejected even for an empty search result.- with pytest.raises(PermissionDeniedError, match="ADMIN or ROOT"):- await mcp_endpoint.list_users(- context, query="missing", include_credentials=True- )- else:- credentials = await mcp_endpoint.list_users(- context, query="user-112", include_credentials=True+ credentials = await mcp_endpoint.list_users(+ context, query="user-112", include_credentials=True+ )+ if role == Role.ROOT:+ assert credentials["users"][0]["api_key"] == last_key+ elif role == Role.ADMIN:+ account_part, user_part, secret = last_key.split(".")+ assert credentials["users"][0]["key_prefix"] == (+ f"{account_part}.{user_part}.{'*' * (len(secret) - 4)}{secret[-4:]}")- 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+ assert "api_key" not in credentials["users"][0]+ else:+ assert credentials == {+ "users": [{"user_id": "user-112", "role": "admin"}],+ "total": 1,+ }+ own = await mcp_endpoint.list_users(+ context, query="user-1", include_credentials=True)- try:- with pytest.raises(PermissionDeniedError, match="trusted"):- await mcp_endpoint.list_users(context, include_credentials=True)- assert await mcp_endpoint.list_users(context, query="user-112") == directory- finally:- lightweight_admin_app.state.config = original_config+ assert "api_key" in own["users"][0]+ assert all(set(row) == {"user_id", "role"} for row in own["users"][1:])+ assert await mcp_endpoint.list_users(+ context, query="missing", include_credentials=True+ ) == {"users": [], "total": 0}+ if role != Role.ROOT:+ 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+ )+ try:+ with pytest.raises(PermissionDeniedError, match="trusted"):+ await mcp_endpoint.list_users(context, include_credentials=True)+ assert await mcp_endpoint.list_users(context, query="user-112") == directory+ finally:+ lightweight_admin_app.state.config = original_config+finally:mcp_endpoint._mcp_ctx.reset(token)diff --git a/tests/server/test_api_key_manager.py b/tests/server/test_api_key_manager.pyindex 01b170b2f..90b7606eb 100644--- a/tests/server/test_api_key_manager.py+++ b/tests/server/test_api_key_manager.py@@ -454,6 +454,49 @@ async def test_regenerate_key(manager: APIKeyManager):assert identity.account_id == acct[email protected]("hashing", [False, True])[email protected]("mutation", ["reset", "revoke"])+async def test_conditional_rotation_checks_persisted_key(manager_service, hashing, mutation):+ from openviking.server.api_keys import generate_api_key++ managers = [+ build_api_key_manager(+ root_key=ROOT_KEY,+ viking_fs=manager_service.viking_fs,+ api_key_hashing_enabled=hashing,+ )+ for _ in range(2)+ ]+ writer, stale = managers+ try:+ await writer.load()+ account = _uid()+ await writer.create_account(account, "owner")+ initial_key = await writer.register_user(account, "alice")+ old_key = await writer.regenerate_key(account, "alice", expected_api_key=initial_key)+ await stale.load()+ if mutation == "reset":+ reset_key = await writer.regenerate_key(account, "alice")+ else:+ await writer._store.revoke_active_api_keys(account, "alice")+ rejected_key = generate_api_key(account, "alice")+ # This store still has the old credential in memory. Its conditional+ # write must validate the persisted registry under the shared lease.+ with pytest.raises(UnauthenticatedError):+ await stale._store.replace_active_user_api_key(+ account, "alice", rejected_key, expected_api_key=old_key+ )+ await stale.load()+ for key in (old_key, rejected_key):+ with pytest.raises(UnauthenticatedError):+ await stale.resolve_identity(key)+ if mutation == "reset":+ assert (await stale.resolve_identity(reset_key)).user_id == "alice"+ finally:+ for manager in managers:+ await manager.close()++async def test_get_user_key_fingerprint_changes_on_rotation(manager: APIKeyManager):"""fp must change when the key is regenerated and disappear when user is removed."""acct = _uid()diff --git a/tests/server/test_server_health.py b/tests/server/test_server_health.pyindex 90390c2f8..34728d963 100644--- a/tests/server/test_server_health.py+++ b/tests/server/test_server_health.py@@ -104,7 +104,7 @@ async def test_health_endpoint_without_api_key():@pytest.mark.parametrize(- "credentials", ["anonymous", "partial", "trusted", "keyed", "malformed", "asserted-root"]+ "credentials", ["anonymous", "partial", "trusted", "keyed", "malformed", "asserted-root", "root-only", "invalid-root-only"])async def test_health_trusted_identity_contract(credentials, caplog, service):app = create_app(@@ -113,12 +113,14 @@ async def test_health_trusted_identity_contract(credentials, caplog, service):)await _initialize_auth_plugin(app, service, app.state.config)headers = {}- if credentials != "anonymous":+ if credentials not in ("anonymous", "root-only", "invalid-root-only"):headers["X-OpenViking-Account"] = "account-a"if credentials in ("trusted", "keyed", "malformed", "asserted-root"):headers["X-OpenViking-User"] = "alice"- if credentials in ("keyed", "asserted-root"):+ if credentials in ("keyed", "asserted-root", "root-only"):headers["X-API-Key"] = "test-root-key"+ if credentials == "invalid-root-only":+ headers["X-API-Key"] = "invalid-key"if credentials == "malformed":headers["X-OpenViking-User"] = "alice/../root"if credentials == "asserted-root":@@ -128,13 +130,15 @@ async def test_health_trusted_identity_contract(credentials, caplog, service):) as client:response = await client.get("/health", headers=headers)body = response.json()- expected_status = 401 if credentials in ("trusted", "malformed") else 200+ expected_status = 401 if credentials in ("trusted", "malformed", "invalid-root-only") else 200assert response.status_code == expected_statusif expected_status == 401:assert body["error"]["code"] == "UNAUTHENTICATED"returnif credentials == "keyed":assert (body["account_id"], body["user_id"], body["role"]) == ("account-a", "alice", "user")+ elif credentials == "root-only":+ assert body["role"] == "root"else:assert "role" not in bodyassert body["root_api_key_required"] is Truediff --git a/web-studio/src/lib/admin-probe.test.ts b/web-studio/src/lib/admin-probe.test.tsindex 8e154db0e..a2536a9cf 100644--- a/web-studio/src/lib/admin-probe.test.ts+++ b/web-studio/src/lib/admin-probe.test.ts@@ -3,6 +3,76 @@ import { createServer } from 'node:http'import { once } from 'node:events'import { probeStudioConnection } from './admin'+describe('management role probes', () => {+ it.each([+ ['root', { role: 'root' }, 'ok', 'rootAvailable'],+ [+ 'account admin',+ { role: 'admin', account_id: 'acme' },+ 'ok',+ 'accountAdminAvailable',+ ],+ [+ 'other account admin',+ { role: 'admin', account_id: 'other' },+ 'error',+ undefined,+ ],+ ['ordinary user', { role: 'user', account_id: 'acme' }, 'error', undefined],+ ['missing identity', { healthy: true }, 'error', undefined],+ ['missing admin account', { role: 'admin' }, 'error', undefined],+ [+ 'invalid credential',+ { error: { code: 'UNAUTHENTICATED' } },+ 'error',+ undefined,+ ],+ ] as const)(+ 'uses authenticated health identity: %s',+ async (name, health, state, detailCode) => {+ const requests: Array<[string, string | undefined]> = []+ const server = createServer((req, res) => {+ requests.push([+ req.url || '',+ req.headers['x-api-key'] as string | undefined,+ ])+ res.setHeader('Content-Type', 'application/json')+ res.statusCode = name === 'invalid credential' ? 401 : 200+ res.end(JSON.stringify(req.url === '/health' ? health : { result: [] }))+ })+ server.listen(0, '127.0.0.1')+ await once(server, 'listening')+ const { port } = server.address() as { port: number }+ try {+ const result = await probeStudioConnection({+ baseUrl: `http://127.0.0.1:${port}`,+ serverMode: 'api_key',+ accountId: 'acme',+ userId: 'alice',+ apiKey: '',+ adminApiKey: 'control-key',+ })+ // detailCode only exists on the 'ok' results per CapabilityProbeResult;+ // an explicit undefined key would make toMatchObject require it.+ expect(result.admin).toMatchObject(+ detailCode === undefined ? { state } : { state, detailCode },+ )+ if (state === 'error') {+ expect(result.admin).not.toHaveProperty('detailCode')+ expect(result.admin).toMatchObject(+ name === 'invalid credential'+ ? { statusCode: 401, errorCode: 'UNAUTHENTICATED' }+ : { statusCode: 403, errorCode: 'PERMISSION_DENIED' },+ )+ }+ expect(requests).toEqual([['/health', 'control-key']])+ } finally {+ await new Promise<void>((resolve) => server.close(() => resolve()))+ }+ },+ )+})+describe('trusted connection probes', () => {it.each(['', 'root-key'])('requires a key for trusted data access and preserves server errors: %s',diff --git a/web-studio/src/lib/admin.ts b/web-studio/src/lib/admin.tsindex 144684d64..2bdab4f9b 100644--- a/web-studio/src/lib/admin.ts+++ b/web-studio/src/lib/admin.ts@@ -204,9 +204,8 @@ async function probeAdminAccess(}}- // The Root API key is the only control-plane credential. The User API key is- // never promoted to admin access, so management stays gated behind the root- // or account-admin key alone.+ // Check the control-plane credential's authenticated role. Listing users is+ // also available to ordinary users and cannot prove management permission.const controlKey = input.adminApiKey.trim()if (!controlKey) {return {@@ -223,35 +222,25 @@ async function probeAdminAccess(setApiKeyHeader(headers, controlKey)try {- await client.get('/api/v1/admin/accounts', { headers })- return {- detailCode: 'rootAvailable',- state: 'ok',+ const { data } = await client.get<unknown>('/health', { headers })+ if (isRecord(data) && data.role === 'root') {+ return { detailCode: 'rootAvailable', state: 'ok' }}- } catch (accountsError) {if (- !axios.isAxiosError(accountsError) ||- accountsError.response?.status !== 403 ||- !input.accountId+ isRecord(data) &&+ data.role === 'admin' &&+ input.accountId.trim() &&+ data.account_id === input.accountId.trim()) {- return probeError(accountsError)+ return { detailCode: 'accountAdminAvailable', state: 'ok' }}-- try {- const accountId = encodeURIComponent(input.accountId)- await client.get(`/api/v1/admin/accounts/${accountId}/users`, {- headers,- params: {- limit: 1,- },- })- return {- detailCode: 'accountAdminAvailable',- state: 'ok',- }- } catch (usersError) {- return probeError(usersError)+ return {+ errorCode: 'PERMISSION_DENIED',+ statusCode: 403,+ state: 'error',}+ } catch (error) {+ return probeError(error)}}