Skip to content

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

fix(credentials): restore the API key when a sign-out fails after reload

M3gA-Mind36f5e9a0a157
diff --git a/crates/openhuman-core/src/security/credentials/ops/credential.rs b/crates/openhuman-core/src/security/credentials/ops/credential.rs
index b5b6a6ea29..b4ca213f59 100644
--- a/crates/openhuman-core/src/security/credentials/ops/credential.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/credential.rs
@@ -383,6 +383,21 @@ 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 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>(
+ ctx: &DispatchCtx,
+ config: &Config,
+ kind: Option<CredentialKind>,
+ reload: F,
+) -> Result<Outcome<Value>, String>
+where
+ F: FnOnce() -> Fut,
+ Fut: std::future::Future<Output = Result<Config, String>>,
+{
refuse_process_credential_in_saas("clear_credential")?;
let _mutation = CREDENTIAL_MUTATION_LOCK.lock().await;
let mut logs = Vec::new();
@@ -426,20 +441,19 @@ pub async fn clear_credential(
cleared_source_api_key = api_key::clear_api_key(config).map_err(|e| e.to_string())?;
}
- let outcome = match clear_session_credential(ctx, config).await {
- Ok(outcome) => outcome,
- Err(error) => {
- restore_api_key(config, source_api_key.as_deref(), "teardown failed");
- return Err(error);
- }
- };
+ // 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);
+ let outcome = clear_session_credential(ctx, config)
+ .await
+ .inspect_err(|_| restore("teardown failed"))?;
removed_session = outcome.value;
logs.extend(outcome.logs);
// The teardown rebinds 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_config_or(ctx, config).await?;
+ effective_config = reload().await.inspect_err(|_| restore("reload failed"))?;
if let Some(key) = source_api_key.as_deref() {
if matches!(
kind,
@@ -451,10 +465,9 @@ pub async fn clear_credential(
// 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).
- if let Err(error) = api_key::store_api_key(&effective_config, key) {
- restore_api_key(config, Some(key), "carry failed");
- return Err(error.to_string());
- }
+ api_key::store_api_key(&effective_config, key)
+ .inspect_err(|_| restore("carry failed"))
+ .map_err(|e| e.to_string())?;
logs.push("api key carried forward to the signed-out workspace".to_string());
}
}
diff --git a/crates/openhuman-core/src/security/credentials/ops/credential_tests.rs b/crates/openhuman-core/src/security/credentials/ops/credential_tests.rs
index 23c823b2c3..c01aaf31b0 100644
--- a/crates/openhuman-core/src/security/credentials/ops/credential_tests.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/credential_tests.rs
@@ -6,3 +6,134 @@ fn process_wide_credentials_are_single_user_only() {
let err = process_credential_refusal(true, "set_credential").unwrap_err();
assert!(err.contains("profiles.set_credential"), "{err}");
}
+
+// A failed sign-out puts the API key it took out of its source back; a key
+// that cannot be stored again is logged, never a panic or an error of its own.
+#[tokio::test]
+#[allow(clippy::await_holding_lock)] // Serializes the process-wide storage slot.
+async fn restore_api_key_puts_the_key_back_and_tolerates_a_failed_store() {
+ 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 config = Config {
+ workspace_dir: tmp.path().join("workspace"),
+ config_path: tmp.path().join("config.toml"),
+ ..Config::default()
+ };
+
+ restore_api_key(&config, None, "test");
+ assert!(!api_key::has_api_key(&config), "nothing to put back");
+
+ restore_api_key(&config, Some("sk-restored"), "test");
+ assert_eq!(
+ api_key::get_api_key(&config).unwrap().as_deref(),
+ Some("sk-restored")
+ );
+
+ // A blank key cannot be stored: the failure is logged and the stored key stays.
+ restore_api_key(&config, Some(" "), "test");
+ assert_eq!(
+ api_key::get_api_key(&config).unwrap().as_deref(),
+ Some("sk-restored")
+ );
+}
+
+/// Signs `user-42` in on file-backed profiles under a temp HOME and stores
+/// `sk-keep` beside the user-scoped config it activates; returns that config.
+async fn signed_in_with_key() -> Config {
+ let pre_login = crate::config::load_config_with_timeout().await.unwrap();
+ store_session(
+ &DispatchCtx::process_default(),
+ &pre_login,
+ "synthetic-session-token",
+ Some("user-42".into()),
+ Some(json!({ "id": "user-42" })),
+ )
+ .await
+ .unwrap();
+ let user_scoped = crate::config::load_config_with_timeout().await.unwrap();
+ set_credential(
+ &DispatchCtx::process_default(),
+ &user_scoped,
+ SetCredentialRequest {
+ token: "sk-keep".into(),
+ kind: Some("api-key".into()),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ api_key::get_api_key(&user_scoped).unwrap().as_deref(),
+ Some("sk-keep"),
+ "control"
+ );
+ 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.
+#[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() {
+ 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;
+
+ // 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(
+ &DispatchCtx::process_default(),
+ &user_scoped,
+ Some(CredentialKind::Session),
+ move || async move { Ok(unwritable) },
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(
+ api_key::get_api_key(&user_scoped).unwrap().as_deref(),
+ Some("sk-keep"),
+ "a failed carry must put the API key back where it was"
+ );
+}