Skip to content

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

fix(auth): a keychain read error fails the load instead of purging profiles

M3gA-Mind9a40fed8c0f5
diff --git a/crates/openhuman-core/src/security/credentials/profiles/keychain.rs b/crates/openhuman-core/src/security/credentials/profiles/keychain.rs
index 271a01af16..fc66c847e7 100644
--- a/crates/openhuman-core/src/security/credentials/profiles/keychain.rs
+++ b/crates/openhuman-core/src/security/credentials/profiles/keychain.rs
@@ -41,7 +41,8 @@ impl AuthProfilesStore {
/// Load auth secrets for a profile from the OS keychain.
///
- /// Returns `None` if no keychain entry exists for the profile.
+ /// Returns `None` if no keychain entry exists for the profile, and an error
+ /// when the keychain could not be read (locked, denied, unavailable).
pub(super) fn keychain_load_secrets(
&self,
profile_id: &str,
@@ -62,7 +63,9 @@ impl AuthProfilesStore {
self.user_id,
e.diagnostic()
);
- return Ok(None);
+ // A read error is not a missing entry: the caller must not
+ // treat the profile as having no secrets.
+ anyhow::bail!("keychain read failed: {}", e.diagnostic());
}
};
let secrets: KeychainSecrets = serde_json::from_str(&payload).map_err(|e| {
diff --git a/crates/openhuman-core/src/security/credentials/profiles/migration.rs b/crates/openhuman-core/src/security/credentials/profiles/migration.rs
index 49ea0a2745..e6fcc08ffb 100644
--- a/crates/openhuman-core/src/security/credentials/profiles/migration.rs
+++ b/crates/openhuman-core/src/security/credentials/profiles/migration.rs
@@ -169,8 +169,22 @@ impl AuthProfilesStore {
}
(at, rt, it, tok)
}
- Err(_e) => {
- // Keychain I/O error — fall through to JSON decrypt path.
+ Err(e) => {
+ // Keychain read error. JSON still holding this profile's
+ // secrets can serve it; a keychain-only profile cannot,
+ // and resolving it without secrets would drop it and
+ // let the next write erase it (and its keychain entry).
+ let has_json_secrets = p.access_token.is_some()
+ || p.refresh_token.is_some()
+ || p.id_token.is_some()
+ || p.token.is_some();
+ if !has_json_secrets {
+ log::warn!(
+ "[auth] keychain read failed for keychain-only profile_id={id}; \
+ refusing to load a partial view"
+ );
+ return Err(e);
+ }
log::warn!(
"[auth] keychain error for profile_id={id}; falling back to JSON"
);
diff --git a/crates/openhuman-core/src/security/credentials/profiles_keychain_error_tests.rs b/crates/openhuman-core/src/security/credentials/profiles_keychain_error_tests.rs
new file mode 100644
index 0000000000..49b0ed5233
--- /dev/null
+++ b/crates/openhuman-core/src/security/credentials/profiles_keychain_error_tests.rs
@@ -0,0 +1,139 @@
+//! A keychain read error is not a missing secret. Treating it as one dropped
+//! keychain-only OAuth profiles and persisted the drop, and every write
+//! rebuilds the whole store (keychain entries included) from that partial view.
+
+use super::*;
+use crate::security::secret_storage::{SecretBackend, SecretStorageError};
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex};
+use tempfile::TempDir;
+
+/// In-memory keychain whose reads can be made to fail (a locked or denied keychain).
+#[derive(Default)]
+struct FlakyKeychain {
+ map: Mutex<HashMap<String, String>>,
+ fail_reads: AtomicBool,
+}
+
+impl SecretBackend for FlakyKeychain {
+ fn get(&self, key: &str) -> Result<Option<String>, SecretStorageError> {
+ if self.fail_reads.load(Ordering::SeqCst) {
+ return Err(SecretStorageError::Backend("keychain locked".into()));
+ }
+ Ok(self.map.lock().unwrap().get(key).cloned())
+ }
+ fn set(&self, key: &str, value: &str) -> Result<(), SecretStorageError> {
+ self.map.lock().unwrap().insert(key.into(), value.into());
+ Ok(())
+ }
+ fn delete(&self, key: &str) -> Result<(), SecretStorageError> {
+ self.map.lock().unwrap().remove(key);
+ Ok(())
+ }
+ fn name(&self) -> &'static str {
+ "flaky-keychain"
+ }
+}
+
+struct Fixture {
+ keychain: Arc<FlakyKeychain>,
+ store: AuthProfilesStore,
+ oauth_id: String,
+ _tmp: TempDir,
+}
+
+impl Drop for Fixture {
+ fn drop(&mut self) {
+ crate::security::secret_storage::clear_secret_backend();
+ }
+}
+
+/// A store holding one keychain-only OAuth profile and one Token profile,
+/// with keychain reads failing from here on.
+fn locked_keychain_store() -> Fixture {
+ let keychain = Arc::new(FlakyKeychain::default());
+ crate::security::secret_storage::install_secret_backend(keychain.clone());
+ let tmp = TempDir::new().unwrap();
+ let store = AuthProfilesStore::new(tmp.path(), true);
+ let oauth = AuthProfile::new_oauth(
+ "openai-codex",
+ "default",
+ TokenSet {
+ access_token: "kc-access".into(),
+ refresh_token: Some("kc-refresh".into()),
+ id_token: None,
+ expires_at: Some(Utc::now() + chrono::Duration::hours(1)),
+ token_type: Some("Bearer".into()),
+ scope: None,
+ },
+ );
+ let oauth_id = oauth.id.clone();
+ store.upsert_profile(oauth, true).unwrap();
+ store
+ .upsert_profile(
+ AuthProfile::new_token("anthropic", "default", "kc-token".into()),
+ true,
+ )
+ .unwrap();
+ let json = std::fs::read_to_string(store.path()).unwrap();
+ assert!(
+ json.contains(&oauth_id) && !json.contains("kc-access") && !json.contains("kc-token"),
+ "precondition: secrets live only in the keychain"
+ );
+ keychain.fail_reads.store(true, Ordering::SeqCst);
+ Fixture {
+ keychain,
+ store,
+ oauth_id,
+ _tmp: tmp,
+ }
+}
+
+#[test]
+fn keychain_read_error_fails_the_load_and_keeps_the_profile() {
+ let f = locked_keychain_store();
+ let json_before = std::fs::read_to_string(f.store.path()).unwrap();
+
+ assert!(
+ f.store.load().is_err(),
+ "a keychain read error must fail the load"
+ );
+
+ assert_eq!(
+ std::fs::read_to_string(f.store.path()).unwrap(),
+ json_before
+ );
+ f.keychain.fail_reads.store(false, Ordering::SeqCst);
+ let data = f.store.load().expect("load after the keychain unlocks");
+ assert!(
+ data.profiles.contains_key(&f.oauth_id),
+ "profile was purged"
+ );
+}
+
+#[test]
+fn keychain_read_error_refuses_writes_and_keeps_every_secret() {
+ let f = locked_keychain_store();
+ let json_before = std::fs::read_to_string(f.store.path()).unwrap();
+ let keychain_before = f.keychain.map.lock().unwrap().clone();
+
+ let upsert = f.store.upsert_profile(
+ AuthProfile::new_token("openrouter", "default", "new-token".into()),
+ false,
+ );
+
+ assert!(
+ upsert.is_err(),
+ "a write from a partial view must be refused"
+ );
+ assert_eq!(
+ std::fs::read_to_string(f.store.path()).unwrap(),
+ json_before
+ );
+ assert_eq!(
+ *f.keychain.map.lock().unwrap(),
+ keychain_before,
+ "keychain entries were rewritten from a partial view"
+ );
+}
diff --git a/crates/openhuman-core/src/security/credentials/profiles_tests.rs b/crates/openhuman-core/src/security/credentials/profiles_tests.rs
index 52f59fa4f0..4b4c9d4b9d 100644
--- a/crates/openhuman-core/src/security/credentials/profiles_tests.rs
+++ b/crates/openhuman-core/src/security/credentials/profiles_tests.rs
@@ -8,6 +8,8 @@ use tempfile::TempDir;
/// that has since exited.
const SYNTHETIC_DEAD_PID: u32 = i32::MAX as u32;
+#[path = "profiles_keychain_error_tests.rs"]
+mod keychain_error_tests;
#[path = "profiles_persistence_migration_tests.rs"]
mod persistence_migration_tests;
#[path = "profiles_store_lock_tests.rs"]