Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(keyring): make encrypted migration durable and available

Steven Enamakel180c6dc7a92b
diff --git a/crates/openhuman-app/permissions/README.md b/crates/openhuman-app/permissions/README.md
index 465ed84f88..9158615f25 100644
--- a/crates/openhuman-app/permissions/README.md
+++ b/crates/openhuman-app/permissions/README.md
@@ -31,7 +31,7 @@ RuntimeAuthority::resolve_access
| File | Identifier | Commands |
| --- | --- | --- |
-| [`allow-core-process.toml`](allow-core-process.toml) | `allow-core-process` | Core endpoint and lifecycle (`core_rpc_*`, `relay_http_rpc`, `start_core_process`, `restart_core_process`, `reset_local_data`), app control (`restart_app`, `app_quit`), session (`get_active_user_id`, `auth_*`), dictation and push-to-talk hotkeys, `show_ptt_overlay`, `activate_main_window`, notch window, native notifications, and log folder commands. |
+| [`allow-core-process.toml`](allow-core-process.toml) | `allow-core-process` | Core endpoint and lifecycle (`core_rpc_*`, `relay_http_rpc`, `relay_remote_socket`, `start_core_process`, `restart_core_process`, `reset_local_data`), app control (`restart_app`, `app_quit`), session (`get_active_user_id`, `auth_*`), dictation and push-to-talk hotkeys, `show_ptt_overlay`, `activate_main_window`, notch window, native notifications, and log folder commands. |
| [`allow-app-update.toml`](allow-app-update.toml) | `allow-app-update` | `check_app_update`, `apply_app_update`, `download_app_update`, `install_app_update`. |
| [`allow-workspace-files.toml`](allow-workspace-files.toml) | `allow-workspace-files` | `open_workspace_path`, `reveal_workspace_path`, `preview_workspace_text`. |
| [`allow-artifact-download.toml`](allow-artifact-download.toml) | `allow-artifact-download` | `download_artifact_to_downloads`. |
diff --git a/crates/openhuman-core/src/core/cli.rs b/crates/openhuman-core/src/core/cli.rs
index 16fab1c353..c038220833 100644
--- a/crates/openhuman-core/src/core/cli.rs
+++ b/crates/openhuman-core/src/core/cli.rs
@@ -46,6 +46,35 @@ pub fn run_from_cli_args(args: &[String]) -> Result<()> {
run_from_cli_args_with(args, None)
}
+/// Whether the parsed invocation only asks the CLI to print help.
+///
+/// Hosts use this before startup work that may access user credentials so
+/// `--help` remains available on a machine whose keyring is unavailable.
+pub(crate) fn is_help_only(args: &[String]) -> bool {
+ let Ok(launch) = parse_launch_options(args) else {
+ return false;
+ };
+ let Some(command) = launch.args.first() else {
+ return true;
+ };
+ if is_help(command) {
+ return true;
+ }
+ let tail = &launch.args[1..];
+ match command.as_str() {
+ "call" | "agent" => tail.is_empty() || tail.iter().any(|arg| is_help(arg)),
+ "mcp" | "mcp-server" | "run" | "serve" | "sentry-test" => {
+ tail.iter().any(|arg| is_help(arg))
+ }
+ _namespace => {
+ matches!(
+ tail,
+ [function, ..] if is_help(function)
+ ) || matches!(tail, [_, slot, ..] if is_help(slot))
+ }
+ }
+}
+
/// [`run_from_cli_args`] with a host-supplied boot description for `run` /
/// `serve`; see [`crate::run_core_from_args_with`].
pub fn run_from_cli_args_with(
diff --git a/crates/openhuman-core/src/core/cli_tests.rs b/crates/openhuman-core/src/core/cli_tests.rs
index e451e4f522..b8f57c7189 100644
--- a/crates/openhuman-core/src/core/cli_tests.rs
+++ b/crates/openhuman-core/src/core/cli_tests.rs
@@ -1,11 +1,36 @@
use super::{
- grouped_schemas, load_dotenv_for_cli, parse_function_params, parse_input_value,
+ grouped_schemas, is_help_only, load_dotenv_for_cli, parse_function_params, parse_input_value,
parse_launch_options,
};
use crate::config::test_env::EnvVarGuard;
use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
use tempfile::tempdir;
+#[test]
+fn help_only_cli_calls_skip_keyring_initialization() {
+ for args in [
+ vec![],
+ vec!["--help".to_string()],
+ vec![
+ "--model".to_string(),
+ "qwen3:8b".to_string(),
+ "--help".to_string(),
+ ],
+ vec!["call".to_string()],
+ vec!["agent".to_string(), "--help".to_string()],
+ vec!["auth".to_string(), "--help".to_string()],
+ ] {
+ assert!(
+ is_help_only(&args),
+ "expected help-only invocation: {args:?}"
+ );
+ }
+ assert!(!is_help_only(&[
+ "run".to_string(),
+ "--jsonrpc-only".to_string()
+ ]));
+}
+
#[test]
fn launch_options_parse_model_and_provider_before_command() {
let args = vec![
diff --git a/crates/openhuman-core/src/lib.rs b/crates/openhuman-core/src/lib.rs
index 8a5b9c76fc..3a3abf1159 100644
--- a/crates/openhuman-core/src/lib.rs
+++ b/crates/openhuman-core/src/lib.rs
@@ -135,7 +135,9 @@ pub fn run_core_from_args_with(
platform::service::apply_startup_restart_delay_from_env();
// A SaaS boot roots the keyring under its operator directory
// (`saas::build`), so it must not be latched to the home directory here.
- if !core::runtime::mode::requested_in(args, std::env::var("OPENHUMAN_MODE").ok().as_deref()) {
+ if !core::cli::is_help_only(args)
+ && !core::runtime::mode::requested_in(args, std::env::var("OPENHUMAN_MODE").ok().as_deref())
+ {
security::keyring::init_master_key().map_err(anyhow::Error::msg)?;
}
core::cli::run_from_cli_args_with(args, host_boot)
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
index c4eb7889c1..81740bc9c2 100644
--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
+++ b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
@@ -414,6 +414,10 @@ fn master_key() -> Option<&'static [u8; KEY_LEN]> {
.and_then(Option::as_ref)
}
+pub(super) fn master_key_available() -> bool {
+ master_key().is_some()
+}
+
// ── Backend ──────────────────────────────────────────────────────────────────
/// Every secret in one ChaCha20-Poly1305 file: an adapter over
@@ -470,58 +474,73 @@ impl EncryptedFileBackend {
/// Import `dev-keychain.json` into a missing `secrets.enc`, once.
fn import_legacy_dev_keychain(&self, key: &[u8; KEY_LEN]) -> Result<(), KeyringError> {
let legacy_path = self.workspace_dir.join(LEGACY_DEV_KEYCHAIN);
- if !legacy_path.exists() {
+ let migrated_path = legacy_path.with_extension("json.migrated");
+ if !legacy_path.exists() && !migrated_path.exists() {
return Ok(());
}
- // Use the same lock order as migration callers: encrypted destination
- // first, then legacy source. The plaintext backend takes only the
- // second lock, so its writers cannot race this read-and-remove window.
+ // Use one lock order everywhere: encrypted destination, current legacy
+ // source, then an older migrated source. The plaintext backend takes
+ // the source lock, so its writers cannot race this read-and-remove.
let _guard = file_store::lock_for_write(&self.path)?;
let _legacy_guard = file_store::lock_for_write(&legacy_path)?;
- if !legacy_path.exists() {
+ let _migrated_guard = file_store::lock_for_write(&migrated_path)?;
+ if !legacy_path.exists() && !migrated_path.exists() {
+ return Ok(());
+ }
+
+ // A legacy file can remain after a previous publication/cleanup error.
+ // It must not make an otherwise valid encrypted store unavailable.
+ if self.path.exists() {
+ let existing_sources = [legacy_path.exists(), migrated_path.exists()];
+ for (source, existed_before_cleanup) in [&legacy_path, &migrated_path]
+ .into_iter()
+ .zip(existing_sources)
+ {
+ if !existed_before_cleanup {
+ continue;
+ }
+ if let Err(error) =
+ self.remove_legacy_if_encrypted_copy_matches(key, source, &_guard)
+ {
+ log::warn!("[keyring:encrypted_file] could not clean up legacy copy: {error}");
+ }
+ }
return Ok(());
}
- let metadata = std::fs::symlink_metadata(&legacy_path).map_err(|source| {
+ let source_path = if legacy_path.exists() {
+ &legacy_path
+ } else {
+ &migrated_path
+ };
+ let metadata = std::fs::symlink_metadata(source_path).map_err(|source| {
KeyringError::MigrationReadFailed {
- path: legacy_path.display().to_string(),
+ path: source_path.display().to_string(),
source,
}
})?;
if !metadata.file_type().is_file() {
return Err(KeyringError::Backend(format!(
- "legacy {LEGACY_DEV_KEYCHAIN} is not a regular file; preserving it for recovery"
+ "legacy {} is not a regular file; preserving it for recovery",
+ source_path.display()
)));
}
-
log::info!(
"[keyring:encrypted_file] found legacy {} — migrating to encrypted file",
- LEGACY_DEV_KEYCHAIN
+ source_path.display()
);
-
- let bytes = std::fs::read(&legacy_path).map_err(|e| KeyringError::MigrationReadFailed {
- path: legacy_path.display().to_string(),
- source: e,
- })?;
-
- // A legacy file can remain after a previous publication/cleanup error.
- // It must not make an otherwise valid encrypted store unavailable.
- if self.path.exists() {
- if let Ok(legacy) = serde_json::from_slice::<
- std::collections::BTreeMap<String, String>,
- >(&bytes)
- {
- self.remove_legacy_if_encrypted_copy_matches(key, &legacy_path, &legacy)?;
- }
- return Ok(());
- }
-
+ let bytes =
+ std::fs::read(source_path).map_err(|source| KeyringError::MigrationReadFailed {
+ path: source_path.display().to_string(),
+ source,
+ })?;
let map: std::collections::BTreeMap<String, String> = if bytes.is_empty() {
Default::default()
} else {
serde_json::from_slice(&bytes).map_err(|e| {
KeyringError::Backend(format!(
- "legacy {LEGACY_DEV_KEYCHAIN} is invalid JSON; preserving it for recovery: {e}"
+ "legacy {} is invalid JSON; preserving it for recovery: {e}",
+ source_path.display()
))
})?
};
@@ -536,28 +555,84 @@ impl EncryptedFileBackend {
file_store::write_atomic(&self.path, &blob)?;
}
- self.remove_legacy_if_encrypted_copy_matches(key, &legacy_path, &map)?;
+ let verified = match self.remove_legacy_if_encrypted_copy_matches(key, source_path, &_guard)
+ {
+ Ok(verified) => verified,
+ Err(error @ KeyringError::MigrationDeleteFailed { .. }) => {
+ log::warn!("[keyring:encrypted_file] could not remove migrated plaintext: {error}");
+ true
+ }
+ Err(error) => return Err(error),
+ };
+ if !verified {
+ return Err(KeyringError::Backend(
+ "encrypted migration result did not verify against its plaintext source".into(),
+ ));
+ }
log::info!(
- "[keyring:encrypted_file] legacy {LEGACY_DEV_KEYCHAIN} migrated \
- ({} entries), verified, durably published, and removed",
+ "[keyring:encrypted_file] legacy {} migrated \
+ ({} entries), verified, and durably published",
+ source_path.display(),
map.len()
);
Ok(())
}
/// Remove the plaintext source only after the published encrypted copy is
- /// durable and decrypts to a map containing every legacy entry unchanged.
- /// If publication succeeded but its directory sync failed, the next call
- /// rechecks the same file and retries the durability step before cleanup.
+ /// durable and decrypts to a map containing every source entry unchanged.
+ /// The caller holds the destination and source locks through verification
+ /// and deletion, preventing a concurrent encrypted write from invalidating
+ /// the snapshot between comparison and cleanup.
fn remove_legacy_if_encrypted_copy_matches(
&self,
key: &[u8; KEY_LEN],
legacy_path: &Path,
- legacy: &std::collections::BTreeMap<String, String>,
- ) -> Result<(), KeyringError> {
+ destination_lock: &file_store::WriteLock,
+ ) -> Result<bool, KeyringError> {
+ self.remove_legacy_if_encrypted_copy_matches_with_sync(
+ key,
+ legacy_path,
+ destination_lock,
+ |path, lock| file_store::sync_parent_dir(path, lock),
+ )
+ }
+
+ fn remove_legacy_if_encrypted_copy_matches_with_sync(
+ &self,
+ key: &[u8; KEY_LEN],
+ legacy_path: &Path,
+ destination_lock: &file_store::WriteLock,
+ sync_parent: impl FnOnce(&Path, &file_store::WriteLock) -> Result<(), KeyringError>,
+ ) -> Result<bool, KeyringError> {
+ let metadata = match std::fs::symlink_metadata(legacy_path) {
+ Ok(metadata) => metadata,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
+ Err(source) => {
+ return Err(KeyringError::MigrationReadFailed {
+ path: legacy_path.display().to_string(),
+ source,
+ });
+ }
+ };
+ if !metadata.file_type().is_file() {
+ return Ok(false);
+ }
+ let bytes =
+ std::fs::read(legacy_path).map_err(|source| KeyringError::MigrationReadFailed {
+ path: legacy_path.display().to_string(),
+ source,
+ })?;
+ let legacy: std::collections::BTreeMap<String, String> = if bytes.is_empty() {
+ Default::default()
+ } else {
+ match serde_json::from_slice(&bytes) {
+ Ok(legacy) => legacy,
+ Err(_) => return Ok(false),
+ }
+ };
let blob = match std::fs::read(&self.path) {
Ok(blob) => blob,
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(source) => {
return Err(KeyringError::MigrationReadFailed {
path: self.path.display().to_string(),
@@ -567,24 +642,37 @@ impl EncryptedFileBackend {
};
let plaintext = match crypto::chacha20_decrypt(key, &blob) {
Ok(plaintext) => plaintext,
- Err(_) => return Ok(()),
+ Err(_) => return Ok(false),
};
let encrypted: std::collections::HashMap<String, String> =
match serde_json::from_slice(&plaintext) {
Ok(encrypted) => encrypted,
- Err(_) => return Ok(()),
+ Err(_) => return Ok(false),
};
if !legacy
.iter()
.all(|(name, value)| encrypted.get(name) == Some(value))
{
- return Ok(());
+ return Ok(false);
}
- file_store::sync_parent_dir(&self.path)?;
- match std::fs::remove_file(legacy_path) {
- Ok(()) => Ok(()),
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ sync_parent(&self.path, destination_lock)?;
+ let current_legacy = self.workspace_dir.join(LEGACY_DEV_KEYCHAIN);
+ let archive_path = current_legacy.with_extension("json.migrated");
+ let cleanup = if legacy_path == current_legacy && !archive_path.exists() {
+ std::fs::rename(legacy_path, &archive_path)
+ } else {
+ std::fs::remove_file(legacy_path)
+ };
+ match cleanup {
+ Ok(()) => {
+ // Persist the source rename/removal too. If this sync fails,
+ // the encrypted copy is already durable and the archive (or
+ // original source) remains available for another cleanup pass.
+ file_store::sync_parent_dir(&self.path, destination_lock)?;
+ Ok(true)
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(source) => Err(KeyringError::MigrationDeleteFailed {
path: legacy_path.display().to_string(),
source,
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend_tests.rs b/crates/openhuman-core/src/security/keyring/encrypted_file_backend_tests.rs
index 8d92f616ed..2322a598ac 100644
--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend_tests.rs
+++ b/crates/openhuman-core/src/security/keyring/encrypted_file_backend_tests.rs
@@ -1,10 +1,19 @@
use super::*;
use std::cell::{Cell, RefCell};
+use std::collections::HashMap;
fn legacy_secret_map() -> HashMap<String, String> {
HashMap::from([("user:token".to_string(), "secret-value".to_string())])
}
+fn read_secret(backend: &EncryptedFileBackend, key: &[u8; KEY_LEN]) -> Option<String> {
+ backend.get_with_key(key, "user:token").unwrap()
+}
+
+fn write_secret(backend: &EncryptedFileBackend, key: &[u8; KEY_LEN], value: &str) {
+ backend.set_with_key(key, "user:token", value).unwrap();
+}
+
#[test]
fn legacy_plaintext_is_removed_only_after_verified_encrypted_migration() {
let dir = tempfile::tempdir().unwrap();
@@ -14,10 +23,12 @@ fn legacy_plaintext_is_removed_only_after_verified_encrypted_migration() {
let backend = EncryptedFileBackend::new(dir.path());
let key = [0x42; KEY_LEN];
- assert_eq!(backend.read_map(&key).unwrap(), expected);
+ assert_eq!(read_secret(&backend, &key).as_deref(), Some("secret-value"));
assert!(!legacy_path.exists());
assert!(backend.path.exists());
- assert_eq!(backend.read_map(&key).unwrap(), expected);
+ assert!(legacy_path.with_extension("json.migrated").exists());
+ assert_eq!(read_secret(&backend, &key).as_deref(), Some("secret-value"));
+ assert_eq!(expected["user:token"], "secret-value");
}
#[test]
@@ -27,7 +38,9 @@ fn invalid_legacy_plaintext_is_preserved_for_recovery() {
std::fs::write(&legacy_path, b"invalid JSON").unwrap();
let backend = EncryptedFileBackend::new(dir.path());
- assert!(backend.read_map(&[0x42; KEY_LEN]).is_err());
+ assert!(backend
+ .get_with_key(&[0x42; KEY_LEN], "user:token")
+ .is_err());
assert_eq!(std::fs::read(&legacy_path).unwrap(), b"invalid JSON");
assert!(!backend.path.exists());
}
@@ -38,17 +51,17 @@ fn encrypted_store_removes_only_matching_legacy_plaintext() {
let backend = EncryptedFileBackend::new(dir.path());
let key = [0x42; KEY_LEN];
let encrypted = legacy_secret_map();
- backend.write_map(&key, &encrypted).unwrap();
+ write_secret(&backend, &key, "secret-value");
let legacy_path = dir.path().join(LEGACY_DEV_KEYCHAIN);
let mut different = encrypted.clone();
different.insert("user:token".to_string(), "different".to_string());
std::fs::write(&legacy_path, serde_json::to_vec(&different).unwrap()).unwrap();
- assert!(backend.read_map(&key).is_err());
+ assert_eq!(read_secret(&backend, &key).as_deref(), Some("secret-value"));
assert!(legacy_path.exists());
std::fs::write(&legacy_path, serde_json::to_vec(&encrypted).unwrap()).unwrap();
- assert_eq!(backend.read_map(&key).unwrap(), encrypted);
+ assert_eq!(read_secret(&backend, &key).as_deref(), Some("secret-value"));
assert!(!legacy_path.exists());
}
@@ -57,23 +70,14 @@ fn encrypted_store_remains_readable_when_verified_plaintext_cannot_be_deleted()
let dir = tempfile::tempdir().unwrap();
let backend = EncryptedFileBackend::new(dir.path());
let key = [0x42; KEY_LEN];
- let expected = legacy_secret_map();
- backend.write_map(&key, &expected).unwrap();
let legacy_path = dir.path().join(LEGACY_DEV_KEYCHAIN);
- std::fs::write(&legacy_path, serde_json::to_vec(&expected).unwrap()).unwrap();
+ write_secret(&backend, &key, "secret-value");
+ std::fs::write(&legacy_path, b"stale invalid plaintext").unwrap();
- let actual = backend
- .read_map_with_cleanup(&key, |_| {
- Err(KeyringError::MigrationDeleteFailed {
- path: legacy_path.display().to_string(),
- source: std::io::Error::new(std::io::ErrorKind::PermissionDenied, "test denial"),
- })
- })
- .unwrap();
- assert_eq!(actual, expected);
- assert!(
- legacy_path.exists(),
- "plaintext must be preserved for recovery"
+ assert_eq!(read_secret(&backend, &key).as_deref(), Some("secret-value"));
+ assert_eq!(
+ std::fs::read(&legacy_path).unwrap(),
+ b"stale invalid plaintext"
);
}
@@ -83,23 +87,27 @@ fn existing_encrypted_file_does_not_remove_plaintext_until_directory_sync_succee
let backend = EncryptedFileBackend::new(dir.path());
let key = [0x42; KEY_LEN];
let expected = legacy_secret_map();
- backend.write_map(&key, &expected).unwrap();
+ write_secret(&backend, &key, "secret-value");
let legacy_path = dir.path().join(LEGACY_DEV_KEYCHAIN);
std::fs::write(&legacy_path, serde_json::to_vec(&expected).unwrap()).unwrap();
- let result = backend.read_map_with_cleanup(&key, |map| {
- backend.cleanup_matching_legacy_file_with_sync(&legacy_path, map, true, |_| {
- Err(KeyringError::Backend("directory sync failed".into()))
- })
- });
+ let destination_lock = file_store::lock_for_write(&backend.path).unwrap();
+ let result = backend.remove_legacy_if_encrypted_copy_matches_with_sync(
+ &key,
+ &legacy_path,
+ &destination_lock,
+ |_, _| Err(KeyringError::Backend("directory sync failed".into())),
+ );
assert!(result.is_err());
assert!(
legacy_path.exists(),
"plaintext must remain until encrypted publication is durable"
);
- assert_eq!(backend.read_map(&key).unwrap(), expected);
+ drop(destination_lock);
+ assert_eq!(read_secret(&backend, &key).as_deref(), Some("secret-value"));
assert!(!legacy_path.exists());
+ assert!(legacy_path.with_extension("json.migrated").exists());
}
#[test]
@@ -108,18 +116,18 @@ fn older_plaintext_copy_is_removed_only_when_it_matches() {
let backend = EncryptedFileBackend::new(dir.path());
let key = [0x42; KEY_LEN];
let encrypted = legacy_secret_map();
- backend.write_map(&key, &encrypted).unwrap();
+ write_secret(&backend, &key, "secret-value");
let old_copy = dir
.path()
.join(LEGACY_DEV_KEYCHAIN)
.with_extension("json.migrated");
std::fs::write(&old_copy, serde_json::to_vec(&encrypted).unwrap()).unwrap();
- assert_eq!(backend.read_map(&key).unwrap(), encrypted);
+ assert_eq!(read_secret(&backend, &key).as_deref(), Some("secret-value"));
assert!(!old_copy.exists());
std::fs::write(&old_copy, b"invalid JSON").unwrap();
- assert_eq!(backend.read_map(&key).unwrap(), encrypted);
+ assert_eq!(read_secret(&backend, &key).as_deref(), Some("secret-value"));
assert_eq!(std::fs::read(&old_copy).unwrap(), b"invalid JSON");
}
diff --git a/crates/openhuman-core/src/security/keyring/file_store.rs b/crates/openhuman-core/src/security/keyring/file_store.rs
index c8bda36ba1..eab7cc89e0 100644
--- a/crates/openhuman-core/src/security/keyring/file_store.rs
+++ b/crates/openhuman-core/src/security/keyring/file_store.rs
@@ -104,6 +104,12 @@ pub fn lock_path_for(path: &Path) -> PathBuf {
path.with_file_name(name)
}
+fn parent_dir(path: &Path) -> &Path {
+ path.parent()
+ .filter(|parent| !parent.as_os_str().is_empty())
+ .unwrap_or_else(|| Path::new("."))
+}
+
/// Replace `path`'s contents with `bytes`, atomically, durably, and `0600`.
///
/// Staged through a temp file unique to this process and call, then renamed —
@@ -118,14 +124,13 @@ pub fn lock_path_for(path: &Path) -> PathBuf {
/// Returns [`KeyringError::Backend`] when the parent directory cannot be
/// created, or the temp file cannot be written or renamed.
pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), KeyringError> {
- if let Some(parent) = path.parent() {
- std::fs::create_dir_all(parent).map_err(|e| {
- KeyringError::Backend(format!(
- "could not create {} for a keyring write: {e}",
- parent.display()
- ))
- })?;
- }
+ let parent = parent_dir(path);
+ std::fs::create_dir_all(parent).map_err(|e| {
+ KeyringError::Backend(format!(
+ "could not create {} for a keyring write: {e}",
+ parent.display()
+ ))
+ })?;
// A stale temp file can survive a crash. PID reuse then makes the first
// sequence value collide, so keep allocating sequence values until a new
@@ -169,15 +174,18 @@ fn replace_durably(source: &Path, destination: &Path) -> std::io::Result<()> {
replace_durably_with_sync(source, destination, |parent| File::open(parent)?.sync_all())
}
-/// Ensure a previously published encrypted file is durable before removing a
-/// matching plaintext migration source. This retries an earlier publication
-/// that returned an error after the destination had already appeared.
-pub fn sync_parent_dir(path: &Path) -> Result<(), KeyringError> {
+/// Ensure a previously published encrypted file is durable before cleaning a
+/// matching plaintext migration source. The caller must hold `destination_lock`
+/// across the read, comparison, and cleanup; on Windows this also prevents a
+/// durability retry from republishing stale bytes over a newer write.
+///
+/// This retries an earlier publication that returned an error after the
+/// destination had already appeared.
+pub fn sync_parent_dir(path: &Path, destination_lock: &WriteLock) -> Result<(), KeyringError> {
#[cfg(unix)]
{
- let parent = path.parent().ok_or_else(|| {
- KeyringError::Backend(format!("keyring path {} has no parent", path.display()))
- })?;
+ let _ = destination_lock;
+ let parent = parent_dir(path);
File::open(parent)
.and_then(|directory| directory.sync_all())
.map_err(|error| {
@@ -192,13 +200,14 @@ pub fn sync_parent_dir(path: &Path) -> Result<(), KeyringError> {
// A failed MoveFileExW can leave the destination visible. Republish
// the same bytes with WRITE_THROUGH and verify the result before the
// caller deletes the last plaintext copy.
- sync_parent_dir_with_republish(path, write_atomic)
+ sync_parent_dir_with_republish(path, destination_lock, write_atomic)
}
}
#[cfg(windows)]
fn sync_parent_dir_with_republish(
path: &Path,
+ _destination_lock: &WriteLock,
republish: impl FnOnce(&Path, &[u8]) -> Result<(), KeyringError>,
) -> Result<(), KeyringError> {
let expected = std::fs::read(path).map_err(|source| KeyringError::MigrationReadFailed {
@@ -226,12 +235,7 @@ fn replace_durably_with_sync(
sync_parent: impl FnOnce(&Path) -> std::io::Result<()>,
) -> std::io::Result<()> {
std::fs::rename(source, destination)?;
- let parent = destination.parent().ok_or_else(|| {
- std::io::Error::new(
- std::io::ErrorKind::InvalidInput,
- "keyring path has no parent",
- )
- })?;
+ let parent = parent_dir(destination);
sync_parent(parent)
}
diff --git a/crates/openhuman-core/src/security/keyring/file_store_tests.rs b/crates/openhuman-core/src/security/keyring/file_store_tests.rs
index d2571baae3..02186bedbe 100644
--- a/crates/openhuman-core/src/security/keyring/file_store_tests.rs
+++ b/crates/openhuman-core/src/security/keyring/file_store_tests.rs
@@ -33,7 +33,8 @@ fn existing_ciphertext_is_republished_and_verified_before_plaintext_cleanup() {
let path = dir.path().join("secrets.enc");
std::fs::write(&path, b"ciphertext").unwrap();
- super::sync_parent_dir_with_republish(&path, |destination, bytes| {
+ let destination_lock = lock_for_write(&path).unwrap();
+ super::sync_parent_dir_with_republish(&path, &destination_lock, |destination, bytes| {
assert_eq!(destination, path);
assert_eq!(bytes, b"ciphertext");
super::write_atomic(destination, bytes)
@@ -42,6 +43,11 @@ fn existing_ciphertext_is_republished_and_verified_before_plaintext_cleanup() {
assert_eq!(std::fs::read(&path).unwrap(), b"ciphertext");
}
+#[test]
+fn relative_keyring_paths_sync_the_current_directory() {
+ assert_eq!(super::parent_dir(Path::new("keyring")), Path::new("."));
+}
+
#[test]
fn write_atomic_replaces_contents() {
let dir = tempfile::TempDir::new().unwrap();
diff --git a/crates/openhuman-core/src/security/keyring/ops.rs b/crates/openhuman-core/src/security/keyring/ops.rs
index 6eaf0b26e4..217d567ae3 100644
--- a/crates/openhuman-core/src/security/keyring/ops.rs
+++ b/crates/openhuman-core/src/security/keyring/ops.rs
@@ -246,11 +246,13 @@ fn probe_availability() -> bool {
backend().name()
);
- // File-based and mock backends are always available.
let b = backend();
- if b.name() == "file" || b.name() == "mock" || b.name() == "encrypted_file" {
- log::debug!("[keyring] is_available=true (non-os backend)");
- return true;
+ if let Some(available) = backend_availability_without_probe(
+ b.name(),
+ super::encrypted_file_backend::master_key_available(),
+ ) {
+ log::debug!("[keyring] is_available={available} (non-os backend)");
+ return available;
}
let result = (|| -> Result<bool, KeyringError> {
@@ -284,6 +286,14 @@ fn probe_availability() -> bool {
}
}
+fn backend_availability_without_probe(name: &str, encrypted_key_available: bool) -> Option<bool> {
+ match name {
+ "file" | "mock" => Some(true),
+ "encrypted_file" => Some(encrypted_key_available),
+ _ => None,
+ }
+}
+
/// Retrieve or generate-and-store a random hex secret of `len_bytes` bytes.
///
/// If an entry already exists it is returned unchanged (idempotent).
diff --git a/crates/openhuman-core/src/security/keyring/ops_adoption_tests.rs b/crates/openhuman-core/src/security/keyring/ops_adoption_tests.rs
index 388775c460..7fd1555277 100644
--- a/crates/openhuman-core/src/security/keyring/ops_adoption_tests.rs
+++ b/crates/openhuman-core/src/security/keyring/ops_adoption_tests.rs
@@ -11,6 +11,27 @@ use crate::security::keyring::adapter::tests::fake_os_backend;
use crate::security::keyring::KeyringBackend;
use crate::storage::{MemoryStorage, Scope, StorageBackend};
+#[test]
+fn encrypted_file_is_unavailable_without_an_initialized_master_key() {
+ assert_eq!(
+ backend_availability_without_probe("encrypted_file", false),
+ Some(false)
+ );
+ assert_eq!(
+ backend_availability_without_probe("encrypted_file", true),
+ Some(true)
+ );
+ assert_eq!(
+ backend_availability_without_probe("file", false),
+ Some(true)
+ );
+ assert_eq!(
+ backend_availability_without_probe("mock", false),
+ Some(true)
+ );
+ assert_eq!(backend_availability_without_probe("os", false), None);
+}
+
fn storage_secrets_in(
storage: &MemoryStorage,
scope: &str,
diff --git a/tests/cli_sigpipe.rs b/tests/cli_sigpipe.rs
index cc2d610212..e333f151c0 100644
--- a/tests/cli_sigpipe.rs
+++ b/tests/cli_sigpipe.rs
@@ -48,3 +48,65 @@ fn help_output_closed_pipe_does_not_panic() {
output.status
);
}
+
+#[test]
+fn help_does_not_require_a_keyring_master_key() {
+ use std::process::Command;
+
+ let workspace = tempfile::tempdir().unwrap();
+ for args in [Vec::<&str>::new(), vec!["--help"]] {
+ let output = Command::new(env!("CARGO_BIN_EXE_openhuman-core"))
+ .args(args)
+ .current_dir(workspace.path())
+ .env("OPENHUMAN_WORKSPACE", workspace.path())
+ .env("OPENHUMAN_KEYRING_MASTER_KEY", "invalid")
+ .env_remove("OPENHUMAN_KEYRING_MASTER_KEY_FILE")
+ .env_remove("OPENHUMAN_APP_ENV")
+ .env_remove("OPENHUMAN_KEYRING_BACKEND")
+ .env_remove("OPENHUMAN_MODE")
+ .output()
+ .expect("run help-only CLI invocation");
+ assert!(
+ output.status.success(),
+ "help should not initialize the keyring: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+}
+
+#[test]
+fn headless_default_keyring_stores_provider_secrets_encrypted() {
+ use std::process::Command;
+
+ let workspace = tempfile::tempdir().expect("temporary OpenHuman workspace");
+ let secret = "provider-secret-e2e";
+ let params = format!(r#"{{"provider":"openai","token":"{secret}"}}"#);
+ let output = Command::new(env!("CARGO_BIN_EXE_openhuman-core"))
+ .args([
+ "call",
+ "--method",
+ "openhuman.auth_store_provider_credentials",
+ "--params",
+ &params,
+ ])
+ .current_dir(workspace.path())
+ .env("OPENHUMAN_WORKSPACE", workspace.path())
+ .env("OPENHUMAN_KEYRING_MASTER_KEY", "42".repeat(32))
+ .env_remove("OPENHUMAN_KEYRING_MASTER_KEY_FILE")
+ .env_remove("OPENHUMAN_APP_ENV")
+ .env_remove("OPENHUMAN_KEYRING_BACKEND")
+ .env_remove("OPENHUMAN_MODE")
+ .output()
+ .expect("run provider credential store command");
+ assert!(
+ output.status.success(),
+ "credential store failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let encrypted = std::fs::read(workspace.path().join("secrets.enc"))
+ .expect("default backend should create the encrypted keyring file");
+ assert!(!encrypted
+ .windows(secret.len())
+ .any(|window| window == secret.as_bytes()));
+}