The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(keyring): durably publish encrypted migration before plaintext cleanup
Steven Enamakel1aed845b8d8b
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rsindex 2762299ccc..193a320f5b 100644--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs+++ b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs@@ -436,6 +436,14 @@ impl EncryptedFileBackend {}fn read_map(&self, key: &[u8; KEY_LEN]) -> Result<HashMap<String, String>, KeyringError> {+ self.read_map_with_cleanup(key, |map| self.cleanup_matching_legacy_files(map))+ }++ fn read_map_with_cleanup(+ &self,+ key: &[u8; KEY_LEN],+ cleanup: impl FnOnce(&HashMap<String, String>) -> Result<(), KeyringError>,+ ) -> Result<HashMap<String, String>, KeyringError> {if !self.path.exists() {return self.migrate_legacy_dev_keychain(key);}@@ -452,7 +460,19 @@ impl EncryptedFileBackend {match crypto::chacha20_decrypt(key, &blob) {Ok(plaintext) => match serde_json::from_slice::<HashMap<String, String>>(&plaintext) {Ok(map) => {- self.cleanup_matching_legacy_files(&map)?;+ if let Err(error) = cleanup(&map) {+ match error {+ KeyringError::MigrationDeleteFailed { .. } => {+ // The encrypted copy is valid. Keep serving it+ // while leaving the plaintext source for a+ // later cleanup attempt or manual recovery.+ log::warn!(+ "[keyring:encrypted_file] could not remove verified legacy copy: {error}"+ );+ }+ _ => return Err(error),+ }+ }Ok(map)}Err(e) => {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.rsindex 2911276dd6..4e7251c14e 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@@ -52,6 +52,31 @@ fn encrypted_store_removes_only_matching_legacy_plaintext() {assert!(!legacy_path.exists());}+#[test]+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();++ 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"+ );+}+#[test]fn older_plaintext_copy_is_removed_only_when_it_matches() {let dir = tempfile::tempdir().unwrap();diff --git a/crates/openhuman-core/src/security/keyring/file_store.rs b/crates/openhuman-core/src/security/keyring/file_store.rsindex 04b93570c1..34ff35b00f 100644--- a/crates/openhuman-core/src/security/keyring/file_store.rs+++ b/crates/openhuman-core/src/security/keyring/file_store.rs@@ -104,12 +104,14 @@ pub fn lock_path_for(path: &Path) -> PathBuf {path.with_file_name(name)}-/// Replace `path`'s contents with `bytes`, atomically and `0600`.+/// Replace `path`'s contents with `bytes`, atomically, durably, and `0600`.////// Staged through a temp file unique to this process and call, then renamed —/// so a concurrent writer can never observe, or rename into place, a partially-/// written buffer. The temp file is removed if the rename fails, leaving no-/// debris behind for the next run to trip over.+/// written buffer. The temp file is synced before publication, and the rename+/// is made durable before returning, so a verified encrypted migration can+/// then remove its plaintext source. The temp file is removed if publication+/// fails, leaving no debris behind for the next run to trip over.////// # Errors///@@ -150,7 +152,7 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), KeyringError> {))})?;- std::fs::rename(&tmp_path, path).map_err(|e| {+ replace_durably(&tmp_path, path).map_err(|e| {let _ = std::fs::remove_file(&tmp_path);KeyringError::Backend(format!("could not replace the keyring file at {}: {e}",@@ -159,6 +161,61 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), KeyringError> {})}+/// Publish the synced file and persist its directory entry before callers may+/// remove a plaintext migration source. Unix requires syncing the parent+/// directory after rename; Windows can request a write-through move.+#[cfg(unix)]+fn replace_durably(source: &Path, destination: &Path) -> std::io::Result<()> {+ replace_durably_with_sync(source, destination, |parent| File::open(parent)?.sync_all())+}++#[cfg(unix)]+fn replace_durably_with_sync(+ source: &Path,+ destination: &Path,+ 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",+ )+ })?;+ sync_parent(parent)+}++#[cfg(windows)]+fn replace_durably(source: &Path, destination: &Path) -> std::io::Result<()> {+ use std::os::windows::ffi::OsStrExt;+ use windows_sys::Win32::Storage::FileSystem::{+ MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH,+ };++ let source: Vec<u16> = source.as_os_str().encode_wide().chain(Some(0)).collect();+ let destination: Vec<u16> = destination+ .as_os_str()+ .encode_wide()+ .chain(Some(0))+ .collect();+ // A directory handle cannot be flushed portably on Windows. The+ // write-through move is the platform's durability barrier for the rename.+ let moved = unsafe {+ MoveFileExW(+ source.as_ptr(),+ destination.as_ptr(),+ MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,+ )+ };+ if moved == 0 {+ return Err(std::io::Error::last_os_error());+ }+ Ok(())+}++#[cfg(not(any(unix, windows)))]+compile_error!("keyring durable replacement requires a platform implementation");+/// Reserve a fresh temp file, advancing past leftovers from crashed writers.fn reserve_temp_file(mut next_path: impl FnMut() -> PathBuf,diff --git a/crates/openhuman-core/src/security/keyring/file_store_tests.rs b/crates/openhuman-core/src/security/keyring/file_store_tests.rsindex 342189a90e..65bdafc015 100644--- a/crates/openhuman-core/src/security/keyring/file_store_tests.rs+++ b/crates/openhuman-core/src/security/keyring/file_store_tests.rs@@ -8,6 +8,24 @@ use super::{write_atomic,};+#[cfg(unix)]+#[test]+fn durable_replace_syncs_parent_after_rename_and_propagates_failure() {+ let dir = tempfile::TempDir::new().unwrap();+ let source = dir.path().join("staged");+ let destination = dir.path().join("secrets.enc");+ std::fs::write(&source, b"encrypted").unwrap();++ let error = super::replace_durably_with_sync(&source, &destination, |parent| {+ assert_eq!(parent, dir.path());+ assert_eq!(std::fs::read(&destination).unwrap(), b"encrypted");+ Err(std::io::Error::other("directory sync failed"))+ })+ .unwrap_err();+ assert_eq!(error.to_string(), "directory sync failed");+ assert!(!source.exists());+}+#[test]fn write_atomic_replaces_contents() {let dir = tempfile::TempDir::new().unwrap();