Skip to content

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

Merge upstream/main into cve-keyring-encryption

Steven Enamakel22776dfca73c
diff --cc crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
index f733c9e579,ed63996501..c4eb7889c1
--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
+++ b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
@@@ -495,47 -467,21 +467,33 @@@ impl EncryptedFileBackend
}
}
- fn write_map(
- &self,
- key: &[u8; KEY_LEN],
- map: &HashMap<String, String>,
- ) -> Result<(), KeyringError> {
- let json = serde_json::to_vec(map)
- .map_err(|e| KeyringError::Backend(format!("failed to serialize secrets: {e}")))?;
-
- let blob = crypto::chacha20_encrypt(key, &json)
- .map_err(|e| KeyringError::Backend(format!("encryption failed: {e}")))?;
-
- file_store::write_atomic(&self.path, &blob)
- }
-
- fn migrate_legacy_dev_keychain(
- &self,
- key: &[u8; KEY_LEN],
- ) -> Result<HashMap<String, String>, KeyringError> {
+ /// 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 self.path.exists() || !legacy_path.exists() {
+ if !legacy_path.exists() {
- return Ok(HashMap::new());
+ return Ok(());
}
- // The plaintext backend uses this same sidecar lock. Keep it across
- // the read, encrypted write, verification, and source removal so a
- // concurrent plaintext writer cannot lose an update during migration.
- // The driver's own writes take this same lock, so it is released
- // before they run: this import stages the file itself.
++ // 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.
+ let _guard = file_store::lock_for_write(&self.path)?;
- // Rechecked under the lock: another process may have imported (and
- // renamed) the legacy file between the unlocked check and here.
- if self.path.exists() || !legacy_path.exists() {
+ let _legacy_guard = file_store::lock_for_write(&legacy_path)?;
+ if !legacy_path.exists() {
- return Ok(HashMap::new());
+ return Ok(());
}
+
+ let metadata = std::fs::symlink_metadata(&legacy_path).map_err(|source| {
+ KeyringError::MigrationReadFailed {
+ path: legacy_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"
+ )));
+ }
+
log::info!(
"[keyring:encrypted_file] found legacy {} — migrating to encrypted file",
LEGACY_DEV_KEYCHAIN
@@@ -546,178 -492,46 +504,96 @@@
source: e,
})?;
- let map: HashMap<String, String> = if bytes.is_empty() {
- HashMap::new()
++ // 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 map: std::collections::BTreeMap<String, String> = if bytes.is_empty() {
+ Default::default()
} else {
- serde_json::from_slice(&bytes).unwrap_or_else(|e| {
- log::warn!(
- "[keyring:encrypted_file] legacy {LEGACY_DEV_KEYCHAIN} is corrupt ({e}); \
- starting fresh"
- );
- Default::default()
- })
+ serde_json::from_slice(&bytes).map_err(|e| {
+ KeyringError::Backend(format!(
+ "legacy {LEGACY_DEV_KEYCHAIN} is invalid JSON; preserving it for recovery: {e}"
+ ))
+ })?
};
- self.write_map(key, &map)?;
- self.verify_migrated_map(key, &map)?;
- if !map.is_empty() {
- let json =
- zeroize::Zeroizing::new(serde_json::to_vec(&map).map_err(|e| {
- KeyringError::Backend(format!("failed to serialize secrets: {e}"))
- })?);
++ let json = Zeroizing::new(
++ serde_json::to_vec(&map)
++ .map_err(|e| KeyringError::Backend(format!("failed to serialize secrets: {e}")))?,
++ );
++ {
+ let blob = crypto::chacha20_encrypt(key, &json)
+ .map_err(|e| KeyringError::Backend(format!("encryption failed: {e}")))?;
+ file_store::write_atomic(&self.path, &blob)?;
+ }
- std::fs::remove_file(&legacy_path).map_err(|source| {
- KeyringError::MigrationDeleteFailed {
- path: legacy_path.display().to_string(),
- source,
- }
- })?;
- let migrated_path = legacy_path.with_extension("json.migrated");
- if let Err(e) = std::fs::rename(&legacy_path, &migrated_path) {
- log::warn!(
- "[keyring:encrypted_file] could not rename legacy file: {e}; \
- migration still succeeded"
- );
- } else {
- log::info!(
- "[keyring:encrypted_file] legacy {LEGACY_DEV_KEYCHAIN} migrated \
- ({} entries) and renamed to .migrated",
- map.len()
- );
- }
++ self.remove_legacy_if_encrypted_copy_matches(key, &legacy_path, &map)?;
+ log::info!(
+ "[keyring:encrypted_file] legacy {LEGACY_DEV_KEYCHAIN} migrated \
- ({} entries), verified, and removed",
++ ({} entries), verified, durably published, and removed",
+ map.len()
+ );
- if let Err(e) = self.cleanup_matching_legacy_file(
- &legacy_path.with_extension("json.migrated"),
- &map,
- false,
- ) {
- log::warn!("[keyring:encrypted_file] could not clean up older legacy copy: {e}");
- }
-
- Ok(map)
- }
-
- /// Read the encrypted file back without the normal corruption quarantine.
- /// A failed verification must leave the plaintext source available to retry.
- fn verify_migrated_map(
- &self,
- key: &[u8; KEY_LEN],
- expected: &HashMap<String, String>,
- ) -> Result<(), KeyringError> {
- let blob = std::fs::read(&self.path).map_err(|e| {
- KeyringError::Backend(format!("cannot read encrypted migration result: {e}"))
- })?;
- let plaintext = crypto::chacha20_decrypt(key, &blob)
- .map_err(|e| KeyringError::Backend(format!("cannot decrypt migration result: {e}")))?;
- let actual: HashMap<String, String> = serde_json::from_slice(&plaintext).map_err(|e| {
- KeyringError::Backend(format!("cannot parse decrypted migration result: {e}"))
- })?;
- if &actual != expected {
- return Err(KeyringError::Backend(
- "encrypted migration result differs from plaintext source".into(),
- ));
- }
Ok(())
}
- /// Remove an old plaintext copy only when every entry is present with the
- /// same value in the decrypted store. A changed or invalid copy may hold
- /// data needed for recovery and is left in place for manual inspection.
- fn cleanup_matching_legacy_file(
- &self,
- path: &Path,
- encrypted: &HashMap<String, String>,
- strict: bool,
- ) -> Result<(), KeyringError> {
- self.cleanup_matching_legacy_file_with_sync(
- path,
- encrypted,
- strict,
- file_store::sync_parent_dir,
- )
- }
-
- fn cleanup_matching_legacy_file_with_sync(
++ /// 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.
++ fn remove_legacy_if_encrypted_copy_matches(
+ &self,
- path: &Path,
- encrypted: &HashMap<String, String>,
- strict: bool,
- sync_encrypted_parent: impl FnOnce(&Path) -> Result<(), KeyringError>,
++ key: &[u8; KEY_LEN],
++ legacy_path: &Path,
++ legacy: &std::collections::BTreeMap<String, String>,
+ ) -> Result<(), KeyringError> {
- if !path.exists() {
- return Ok(());
- }
- let _guard = file_store::lock_for_write(path)?;
- let metadata = match std::fs::symlink_metadata(path) {
- Ok(metadata) => metadata,
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
++ let blob = match std::fs::read(&self.path) {
++ Ok(blob) => blob,
++ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
+ Err(source) => {
+ return Err(KeyringError::MigrationReadFailed {
- path: path.display().to_string(),
++ path: self.path.display().to_string(),
+ source,
+ });
+ }
+ };
- if !metadata.file_type().is_file() {
- if strict {
- return Err(KeyringError::Backend(format!(
- "legacy {LEGACY_DEV_KEYCHAIN} is not a regular file; preserving it for recovery"
- )));
- }
- log::warn!("[keyring:encrypted_file] legacy path {} is not a regular file; leaving it untouched", path.display());
- return Ok(());
- }
- let bytes = std::fs::read(path).map_err(|source| KeyringError::MigrationReadFailed {
- path: path.display().to_string(),
- source,
- })?;
- let legacy: HashMap<String, String> = match serde_json::from_slice(&bytes) {
- Ok(map) => map,
- Err(e) => {
- if strict {
- return Err(KeyringError::Backend(format!(
- "legacy {LEGACY_DEV_KEYCHAIN} is invalid JSON; preserving it for recovery: {e}"
- )));
- }
- log::warn!("[keyring:encrypted_file] legacy copy {} is invalid JSON ({e}); leaving it for recovery", path.display());
- return Ok(());
- }
++ let plaintext = match crypto::chacha20_decrypt(key, &blob) {
++ Ok(plaintext) => plaintext,
++ Err(_) => return Ok(()),
+ };
++ let encrypted: std::collections::HashMap<String, String> =
++ match serde_json::from_slice(&plaintext) {
++ Ok(encrypted) => encrypted,
++ Err(_) => return Ok(()),
++ };
+ if !legacy
+ .iter()
- .all(|(key, value)| encrypted.get(key) == Some(value))
++ .all(|(name, value)| encrypted.get(name) == Some(value))
+ {
- if strict {
- return Err(KeyringError::Backend(format!(
- "legacy {LEGACY_DEV_KEYCHAIN} differs from encrypted secrets; preserving it for recovery"
- )));
- }
- log::warn!("[keyring:encrypted_file] legacy copy {} differs from encrypted secrets; leaving it for recovery", path.display());
+ return Ok(());
+ }
- // A previous write may have renamed secrets.enc successfully and then
- // failed its directory sync. Recheck durability before deleting any
- // surviving plaintext copy on a later read.
- sync_encrypted_parent(&self.path)?;
- std::fs::remove_file(path).map_err(|source| KeyringError::MigrationDeleteFailed {
- path: path.display().to_string(),
- source,
- })?;
- log::info!(
- "[keyring:encrypted_file] removed verified legacy plaintext copy {}",
- path.display()
- );
- Ok(())
- }
+
- fn cleanup_matching_legacy_files(
- &self,
- encrypted: &HashMap<String, String>,
- ) -> Result<(), KeyringError> {
- let legacy_path = self.workspace_dir.join(LEGACY_DEV_KEYCHAIN);
- self.cleanup_matching_legacy_file(&legacy_path, encrypted, true)?;
- if let Err(e) = self.cleanup_matching_legacy_file(
- &legacy_path.with_extension("json.migrated"),
- encrypted,
- false,
- ) {
- log::warn!("[keyring:encrypted_file] could not clean up older legacy copy: {e}");
++ 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(()),
++ Err(source) => Err(KeyringError::MigrationDeleteFailed {
++ path: legacy_path.display().to_string(),
++ source,
++ }),
+ }
- Ok(())
- }
-
- /// Move an undecryptable / unparseable secrets file aside so the next call
- /// starts fresh without destroying the bytes.
- fn handle_corruption(&self) {
- file_store::quarantine_corrupt(&self.path, "enc");
+ }
+
/// [`KeyringBackend::get`] under an explicit master key.
- fn get_with_key(
+ pub(super) fn get_with_key(
&self,
key: &[u8; KEY_LEN],
namespaced_key: &str,