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(credentials): put the API key back only where it was
M3gA-Mind027722b144d6
diff --git a/crates/openhuman-core/src/security/credentials/ops.rs b/crates/openhuman-core/src/security/credentials/ops.rsindex 45fdf1088e..cad9051dca 100644--- a/crates/openhuman-core/src/security/credentials/ops.rs+++ b/crates/openhuman-core/src/security/credentials/ops.rs@@ -16,6 +16,8 @@ pub use composio::{clear_composio_api_key, get_composio_api_key, rpc_store_composio_api_key,store_composio_api_key, COMPOSIO_DIRECT_PROVIDER,};+#[cfg(test)]+pub(crate) use credential::clear_credential_with;pub use credential::{clear_credential, clear_session, set_credential, store_session, SetCredentialRequest,PENDING_BACKEND_VALIDATION_FIELD,diff --git a/crates/openhuman-core/src/security/credentials/ops/credential.rs b/crates/openhuman-core/src/security/credentials/ops/credential.rsindex b4ca213f59..360e0f440f 100644--- a/crates/openhuman-core/src/security/credentials/ops/credential.rs+++ b/crates/openhuman-core/src/security/credentials/ops/credential.rs@@ -383,20 +383,23 @@ pub async fn clear_credential(config: &Config,kind: Option<CredentialKind>,) -> Result<Outcome<Value>, String> {- clear_credential_with(ctx, config, kind, || reload_config_or(ctx, config)).await+ clear_credential_with(ctx, config, kind, |to, key| {+ api_key::store_api_key(to, key).map(|_| ())+ })+ .await}-/// [`clear_credential`] with the post-teardown config reload passed in, so a-/// test can make it fail. Production passes [`reload_config_or`].-pub(crate) async fn clear_credential_with<F, Fut>(+/// [`clear_credential`] with the carry of the API key into the signed-out+/// workspace passed in, so a test can make it fail. Production passes+/// [`api_key::store_api_key`].+pub(crate) async fn clear_credential_with<F>(ctx: &DispatchCtx,config: &Config,kind: Option<CredentialKind>,- reload: F,+ carry: F,) -> Result<Outcome<Value>, String>where- F: FnOnce() -> Fut,- Fut: std::future::Future<Output = Result<Config, String>>,+ F: FnOnce(&Config, &str) -> anyhow::Result<()>,{refuse_process_credential_in_saas("clear_credential")?;let _mutation = CREDENTIAL_MUTATION_LOCK.lock().await;@@ -441,19 +444,41 @@ wherecleared_source_api_key = api_key::clear_api_key(config).map_err(|e| e.to_string())?;}- // Every step from here to the carry puts the key back if it fails,- // so a failed sign-out never loses it.- let restore = |reason| restore_api_key(config, source_api_key.as_deref(), reason);+ // A failure from here on puts the key back where it was, but only+ // while that store is still the installed one: profiles follow the+ // installed backend, so after a rebind to another database a write+ // through `config` would land in the signed-out store under this+ // user's secret namespace, where nothing reads it.+ // A teardown can fail before its rebind (the source is still+ // installed) or after it (a later rebind step); the check covers both.+ let source_url = crate::storage::installed_url();+ let fail = |reason: &str, error: String| -> String {+ let Some(key) = source_api_key.as_deref() else {+ return error;+ };+ if crate::storage::installed_url() == source_url {+ restore_api_key(config, Some(key), reason);+ return error;+ }+ tracing::error!(+ domain = "credentials",+ operation = "clear_credential",+ reason,+ "{LOG_PREFIX} api key lost: the sign-out failed after storage moved off its source"+ );+ format!("{error}; the API key could not be kept and must be entered again")+ };let outcome = clear_session_credential(ctx, config).await- .inspect_err(|_| restore("teardown failed"))?;- removed_session = outcome.value;+ .map_err(|error| fail("teardown failed", error))?;+ let (removed, signed_out_config) = outcome.value;+ removed_session = removed;logs.extend(outcome.logs);- // The teardown rebinds every process global to the signed-out+ // The teardown rebound every process global to the signed-out// workspace whether or not a session profile was found; follow it so// the api-key checks below agree with `auth.get_state`.- effective_config = reload().await.inspect_err(|_| restore("reload failed"))?;+ effective_config = signed_out_config;if let Some(key) = source_api_key.as_deref() {if matches!(kind,@@ -465,9 +490,8 @@ where// is only removing the session — an unrelated, stale key at// the pre-login workspace must never silently outrank the key// that was the effective credential a moment ago (#6318).- api_key::store_api_key(&effective_config, key)- .inspect_err(|_| restore("carry failed"))- .map_err(|e| e.to_string())?;+ carry(&effective_config, key)+ .map_err(|error| fail("carry failed", error.to_string()))?;logs.push("api key carried forward to the signed-out workspace".to_string());}}@@ -557,7 +581,7 @@ fn restore_api_key(config: &Config, key: Option<&str>, reason: &str) {async fn clear_session_credential(ctx: &DispatchCtx,config: &Config,-) -> Result<Outcome<bool>, String> {+) -> Result<Outcome<(bool, Config)>, String> {let mut logs = Vec::new();crate::platform::llm_gate::set_signed_out(true);#[cfg(feature = "web3")]@@ -603,23 +627,22 @@ async fn clear_session_credential(// Every process-global store must follow the now-active pre-login// workspace, or a signed-out caller keeps reading the previous account's// context until the process restarts.- match ctx.load_config().await {- Ok(signed_out_config) => {- logs.extend(rebind_after_credential_change(- &signed_out_config,- "credential cleared",- )?);- logs.push(format!(- "process globals rebound to signed-out workspace {}",- signed_out_config.workspace_dir.display()- ));- }- Err(error) => return Err(format!("failed to resolve signed-out workspace: {error}")),- }+ let signed_out_config = ctx+ .load_config()+ .await+ .map_err(|error| format!("failed to resolve signed-out workspace: {error}"))?;+ logs.extend(rebind_after_credential_change(+ &signed_out_config,+ "credential cleared",+ )?);+ logs.push(format!(+ "process globals rebound to signed-out workspace {}",+ signed_out_config.workspace_dir.display()+ ));sentry_scope::clear();logs.push("session cleared".to_string());- Ok(Outcome::new(removed, logs))+ Ok(Outcome::new((removed, signed_out_config), logs))}/// Historical entry point: install a session (or local) credential from adiff --git a/crates/openhuman-core/src/security/credentials/ops/credential_tests.rs b/crates/openhuman-core/src/security/credentials/ops/credential_tests.rsindex 7632228683..fa8e1498ff 100644--- a/crates/openhuman-core/src/security/credentials/ops/credential_tests.rs+++ b/crates/openhuman-core/src/security/credentials/ops/credential_tests.rs@@ -76,40 +76,9 @@ async fn signed_in_with_key() -> Config {user_scoped}-// A session sign-out whose config reload fails after the teardown returns the-// error with the API key back at its source, not removed.-#[tokio::test]-#[allow(clippy::await_holding_lock)] // Serializes the process-wide storage slot.-async fn a_failed_reload_during_sign_out_puts_the_api_key_back() {- let _module = crate::integrations::composio::module_client::module_lock_guard().await;- let _env_guard = crate::config::TEST_ENV_LOCK.lock().await;- let _slot = crate::storage::test_support::lock_storage_slot();- assert!(- crate::storage::installed().is_none(),- "file-backed profiles in this test"- );- let tmp = tempfile::TempDir::new().unwrap();- let _home = crate::config::test_env::EnvVarGuard::set("HOME", tmp.path());- let user_scoped = signed_in_with_key().await;-- let error = clear_credential_with(- &DispatchCtx::process_default(),- &user_scoped,- Some(CredentialKind::Session),- || async { Err::<Config, String>("injected reload failure".into()) },- )- .await- .unwrap_err();- assert!(error.contains("injected reload failure"), "{error}");- assert_eq!(- api_key::get_api_key(&user_scoped).unwrap().as_deref(),- Some("sk-keep"),- "a failed reload must put the API key back where it was"- );-}--// The carry into the signed-out workspace failing (its state directory cannot-// be written) also returns the error with the API key back at its source.+// The carry into the signed-out workspace failing returns the error with the+// API key back at its source. With file-backed profiles the source stays+// reachable after the teardown, so it is put back.#[tokio::test]#[allow(clippy::await_holding_lock)] // Serializes the process-wide storage slot.async fn a_failed_carry_during_sign_out_puts_the_api_key_back() {@@ -124,22 +93,16 @@ async fn a_failed_carry_during_sign_out_puts_the_api_key_back() {let _home = crate::config::test_env::EnvVarGuard::set("HOME", tmp.path());let user_scoped = signed_in_with_key().await;- // The "signed-out" state directory sits under a regular file.- let blocker = tmp.path().join("blocker");- std::fs::write(&blocker, "").unwrap();- let unwritable = Config {- workspace_dir: blocker.join("workspace"),- config_path: blocker.join("config.toml"),- ..Config::default()- };- clear_credential_with(+ let error = clear_credential_with(&DispatchCtx::process_default(),&user_scoped,Some(CredentialKind::Session),- move || async move { Ok(unwritable) },+ |_, _| Err(anyhow::anyhow!("injected carry failure")),).await.unwrap_err();+ assert!(error.contains("injected carry failure"), "{error}");+ assert!(!error.contains("must be entered again"), "{error}");assert_eq!(api_key::get_api_key(&user_scoped).unwrap().as_deref(),Some("sk-keep"),diff --git a/crates/openhuman-core/src/security/credentials/ops_credential_per_user_storage_tests.rs b/crates/openhuman-core/src/security/credentials/ops_credential_per_user_storage_tests.rsindex a5499a1e91..c645d99e5b 100644--- a/crates/openhuman-core/src/security/credentials/ops_credential_per_user_storage_tests.rs+++ b/crates/openhuman-core/src/security/credentials/ops_credential_per_user_storage_tests.rs@@ -235,3 +235,44 @@ async fn another_user_signing_in_does_not_get_the_first_users_api_key() {assert_eq!(state.credential.as_deref(), Some("session"));assert_eq!(state.user_id.as_deref(), Some("user-77"));}++// A carry that fails after the sign-out rebound storage to the signed-out+// database cannot put the key back: its source is another database, no longer+// installed. The error says so, and nothing is written through the old+// user-scoped config into the signed-out store, where the record would sit+// under this user's secret namespace and read back as nothing.+#[tokio::test(flavor = "multi_thread")]+#[allow(clippy::await_holding_lock)] // Serializes the process-wide storage slot.+async fn a_failed_carry_on_per_user_storage_says_the_key_must_be_entered_again() {+ let _module = crate::integrations::composio::module_client::module_lock_guard().await;+ let _env_guard = crate::config::TEST_ENV_LOCK.lock().await;+ let _slot = crate::storage::test_support::lock_storage_slot();+ let tmp = TempDir::new().unwrap();+ let _home = EnvVarGuard::set("HOME", tmp.path());+ let _env = EnvVarGuard::unset_many(&["OPENHUMAN_STORAGE_URL", "OPENHUMAN_WORKSPACE"]);+ let pre_login = crate::config::load_config_with_timeout().await.unwrap();+ let _storage = DefaultStorageForTest::install(&pre_login).await;+ let user_scoped = sign_in(&pre_login, "user-42").await;+ set_api_key(&user_scoped, "sk-live").await;++ let error = clear_credential_with(+ &DispatchCtx::process_default(),+ &user_scoped,+ Some(session_support::CredentialKind::Session),+ |_, _| Err(anyhow::anyhow!("injected carry failure")),+ )+ .await+ .unwrap_err();+ assert!(error.contains("injected carry failure"), "{error}");+ assert!(error.contains("must be entered again"), "{error}");++ let signed_out = crate::config::load_config_with_timeout().await.unwrap();+ assert_eq!(signed_out.config_path, pre_login.config_path);+ assert!(+ crate::security::credentials::AuthService::from_config(&signed_out)+ .get_profile(api_key::API_KEY_PROVIDER, None)+ .unwrap()+ .is_none(),+ "no api-key record may be written into the signed-out store under the old user's namespace"+ );+}