Skip to content

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

fix(credentials): keep sessions and the API key on per-user storage

M3gA-Mind73204a255f9b
diff --git a/crates/openhuman-core/src/security/credentials/ops/credential.rs b/crates/openhuman-core/src/security/credentials/ops/credential.rs
index 85a147bddd..b5b6a6ea29 100644
--- a/crates/openhuman-core/src/security/credentials/ops/credential.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/credential.rs
@@ -313,6 +313,19 @@ pub async fn set_credential(
effective
};
+ if !refresh {
+ crate::integrations::composio::invalidate_connected_integrations_cache();
+ // Rebind before the session is stored. With a storage backend the auth
+ // profiles live in the installed backend, and the default backend
+ // belongs to the profile (`users/<id>/storage.db`): a session stored
+ // first would land in the previous profile's database and read back
+ // as absent once the rebind installs this user's. A failed rebind
+ // stores nothing, so a retry takes this install path again rather
+ // than the refresh fast-path that skips the bind.
+ rebind_after_credential_change(&effective_config, "credential installed")?;
+ logs.push("process globals rebound after credential install".to_string());
+ }
+
let auth = AuthService::from_config(&effective_config);
auth.store_provider_token(
APP_SESSION_PROVIDER,
@@ -325,19 +338,6 @@ pub async fn set_credential(
logs.push(format!("{} credential stored", resolved.kind.as_str()));
if !refresh {
- crate::integrations::composio::invalidate_connected_integrations_cache();
- if let Err(error) =
- rebind_after_credential_change(&effective_config, "credential installed")
- {
- // A retry of the same credential takes the refresh fast-path, so
- // leaving its profile behind would let it skip this required bind.
- auth.remove_profile(APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME)
- .map_err(|rollback| {
- format!("credential rebind failed: {error}; rollback failed: {rollback}")
- })?;
- return Err(error);
- }
- logs.push("process globals rebound after credential install".to_string());
start_credential_gated_services(ctx, &effective_config).await;
logs.push("credential-gated services started".to_string());
}
@@ -410,56 +410,52 @@ pub async fn clear_credential(
let mut effective_config = config.clone();
let mut cleared_source_api_key = false;
- let mut carried_api_key = false;
if matches!(
kind,
None | Some(CredentialKind::Session) | Some(CredentialKind::Local)
) {
- let outcome = clear_session_credential(ctx, config).await?;
+ // Remove the key at its source while the source's store is still the
+ // installed one. The teardown below rebinds storage, and with the
+ // default backend (one database per profile) the signed-out
+ // workspace is another database: after it the source copy can no
+ // longer be reached, and left behind it would resurrect on the next
+ // login to this account (#6318). With a shared store or the
+ // per-directory files this is the same record or file the carry below
+ // writes again.
+ if source_api_key.is_some() {
+ 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);
+ }
+ };
removed_session = outcome.value;
logs.extend(outcome.logs);
- if removed_session {
- // Follow the same process globals the teardown just rebound to,
- // so the api-key checks below agree with `auth.get_state`.
- effective_config = reload_config_or(ctx, config).await?;
- if let Some(key) = source_api_key.as_deref() {
- if matches!(
- kind,
- Some(CredentialKind::Session) | Some(CredentialKind::Local)
- ) {
- // A session/local-only clear preserves the key that was
- // actually active (the source): carry it forward to the
- // post-teardown workspace before the source copy is
- // removed below, overwriting whatever the destination
- // already held. This RPC is only removing the session —
- // an unrelated, stale key sitting 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).map_err(|e| e.to_string())?;
- logs.push("api key carried forward to the signed-out workspace".to_string());
- carried_api_key = true;
- }
- // With a storage backend the auth profiles are one secret in
- // the acting scope (`profiles::persistence::STORAGE_SECRET_NAME`),
- // not a file per state directory, so the source and the
- // destination above are the same record: clearing the
- // "source" would delete the key just carried forward.
- let shares_store =
- carried_api_key && matches!(crate::storage::secrets::current(), Ok(Some(_)));
- if shares_store {
- log::debug!("[credentials] api key kept: the storage profile store is shared");
- } else {
- // Either the key was just moved to the post-teardown config
- // above, or `kind` is `None` and it must be removed outright.
- // `config` here is still the pre-teardown, user-scoped
- // reference, so this clears the *source* location — never
- // leave that copy behind, or a later login to the same
- // account (or an api-key clear against the wrong location)
- // would silently resurrect it (#6318).
- cleared_source_api_key =
- api_key::clear_api_key(config).map_err(|e| e.to_string())?;
+ // 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?;
+ if let Some(key) = source_api_key.as_deref() {
+ if matches!(
+ kind,
+ Some(CredentialKind::Session) | Some(CredentialKind::Local)
+ ) {
+ // A session/local-only clear preserves the key that was
+ // actually active: carry it to the signed-out workspace,
+ // overwriting whatever the destination already held. This RPC
+ // 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());
}
+ logs.push("api key carried forward to the signed-out workspace".to_string());
}
}
}
@@ -516,6 +512,30 @@ pub async fn clear_credential(
))
}
+/// Puts back an API key `clear_credential` took out of its source for a move
+/// that then failed, where the process can read it now. Logged rather than
+/// returned: the caller reports the error that stopped the move.
+fn restore_api_key(config: &Config, key: Option<&str>, reason: &str) {
+ let Some(key) = key else {
+ return;
+ };
+ match api_key::store_api_key(config, key) {
+ Ok(_) => tracing::warn!(
+ domain = "credentials",
+ operation = "clear_credential",
+ reason,
+ "{LOG_PREFIX} api key restored after a failed sign-out"
+ ),
+ Err(error) => tracing::error!(
+ domain = "credentials",
+ operation = "clear_credential",
+ reason,
+ %error,
+ "{LOG_PREFIX} api key could not be restored after a failed sign-out; it must be entered again"
+ ),
+ }
+}
+
/// The session teardown: gate closed first so no worker fires at a backend
/// about to be invalidated, then profile removal, socket / workflow-bridge
/// teardown, user-dir deactivation, service stop, rebind to the signed-out
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.rs
new file mode 100644
index 0000000000..a5499a1e91
--- /dev/null
+++ b/crates/openhuman-core/src/security/credentials/ops_credential_per_user_storage_tests.rs
@@ -0,0 +1,237 @@
+use super::*;
+use crate::core::runtime::DispatchCtx;
+use crate::security::credentials::api_key;
+
+// Credentials on the desktop's DEFAULT storage: the backend belongs to the
+// profile (`users/<id>/storage.db` under layout v2), the host installs it from
+// its URL, and every credential change rebinds the process to the next
+// profile's own database. The other storage tests install one backend with no
+// URL, which is never rebound, so they cannot see a record written to the
+// wrong database.
+
+/// Installs the default backend of `config`'s workspace from its URL, as the
+/// desktop host does (`install_for_url`), and empties the slot on drop. Hold
+/// `lock_storage_slot()` for as long as it lives.
+struct DefaultStorageForTest;
+
+impl DefaultStorageForTest {
+ async fn install(config: &crate::config::Config) -> Self {
+ let url = crate::storage::configured_url(config).expect("a default storage URL");
+ assert!(url.starts_with("sqlite:"), "the default is SQLite: {url}");
+ let backend = crate::storage::open(&url).await.unwrap();
+ assert!(
+ crate::storage::install_for_url(&url, backend).is_none(),
+ "no storage backend may be left installed by another test"
+ );
+ assert!(
+ matches!(crate::storage::secrets::current(), Ok(Some(_))),
+ "the auth profiles must be served from storage secrets in this test"
+ );
+ Self
+ }
+}
+
+impl Drop for DefaultStorageForTest {
+ fn drop(&mut self) {
+ crate::storage::clear();
+ }
+}
+
+fn session_token(user: &str) -> String {
+ let exp = chrono::Utc::now() + chrono::Duration::hours(1);
+ jwt_with_payload(json!({ "sub": user, "exp": exp.timestamp() }))
+}
+
+async fn sign_in(config: &crate::config::Config, user: &str) -> crate::config::Config {
+ store_session(
+ &DispatchCtx::process_default(),
+ config,
+ &session_token(user),
+ None,
+ Some(json!({ "id": user })),
+ )
+ .await
+ .unwrap();
+ crate::config::load_config_with_timeout().await.unwrap()
+}
+
+async fn set_api_key(config: &crate::config::Config, key: &str) {
+ set_credential(
+ &DispatchCtx::process_default(),
+ config,
+ SetCredentialRequest {
+ token: key.into(),
+ kind: Some("api-key".into()),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+}
+
+/// The default storage database every profile under `home` holds, by user id.
+fn profile_databases(home: &std::path::Path) -> Vec<String> {
+ let users = home.join(".openhuman").join("users");
+ let mut ids: Vec<String> = std::fs::read_dir(&users)
+ .map(|entries| {
+ entries
+ .flatten()
+ .filter(|e| e.path().join("storage.db").is_file())
+ .map(|e| e.file_name().to_string_lossy().into_owned())
+ .collect()
+ })
+ .unwrap_or_default();
+ ids.sort();
+ ids
+}
+
+// A session installed on the default storage is stored in the signed-in
+// user's own database, so it reads back after the rebind.
+#[tokio::test(flavor = "multi_thread")]
+#[allow(clippy::await_holding_lock)] // Serializes the process-wide storage slot.
+async fn a_session_is_stored_in_the_users_own_database() {
+ 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 token = session_token("user-42");
+ store_session(
+ &DispatchCtx::process_default(),
+ &pre_login,
+ &token,
+ None,
+ Some(json!({ "id": "user-42" })),
+ )
+ .await
+ .unwrap();
+ let user_scoped = crate::config::load_config_with_timeout().await.unwrap();
+ assert_ne!(user_scoped.config_path, pre_login.config_path);
+ assert!(
+ profile_databases(tmp.path()).contains(&"user-42".to_string()),
+ "signing in rebinds to the user's own storage.db: {:?}",
+ profile_databases(tmp.path())
+ );
+
+ assert_eq!(
+ session_support::get_session_token(&user_scoped)
+ .unwrap()
+ .as_deref(),
+ Some(token.as_str()),
+ "the session must read back from the user's own database"
+ );
+ let state = auth_get_state(&user_scoped).await.unwrap().value;
+ assert!(state.is_authenticated);
+ assert_eq!(state.credential.as_deref(), Some("session"));
+ assert_eq!(state.user_id.as_deref(), Some("user-42"));
+}
+
+// #6318 / #8366 on the default storage: a session-only sign-out moves the
+// API key to the signed-out profile, where it stays in effect (also after the
+// process reopens the store), and takes it out of the user's database so a
+// later login to this account does not resurrect it.
+#[tokio::test(flavor = "multi_thread")]
+#[allow(clippy::await_holding_lock)] // Serializes the process-wide storage slot.
+async fn a_session_sign_out_keeps_the_api_key_on_per_user_storage() {
+ 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 before = auth_get_state(&user_scoped).await.unwrap().value;
+ assert_eq!(before.credential.as_deref(), Some("api-key"), "control");
+
+ let cleared = clear_credential(
+ &DispatchCtx::process_default(),
+ &user_scoped,
+ Some(session_support::CredentialKind::Session),
+ )
+ .await
+ .unwrap()
+ .value;
+ assert_eq!(cleared["removedSession"], true);
+ assert_eq!(cleared["removedApiKey"], false);
+
+ let signed_out = crate::config::load_config_with_timeout().await.unwrap();
+ assert_eq!(signed_out.config_path, pre_login.config_path);
+ assert_eq!(
+ api_key::get_api_key(&signed_out).unwrap().as_deref(),
+ Some("sk-live"),
+ "the API key must survive a session sign-out on per-user storage"
+ );
+ let state = auth_get_state(&signed_out).await.unwrap().value;
+ assert!(state.is_authenticated);
+ assert_eq!(state.credential.as_deref(), Some("api-key"));
+
+ // Reopened from its URL, as a restarted host would.
+ crate::storage::clear();
+ let reopened = DefaultStorageForTest::install(&signed_out).await;
+ let state = auth_get_state(&signed_out).await.unwrap().value;
+ assert_eq!(
+ state.credential.as_deref(),
+ Some("api-key"),
+ "the key must still be in effect after the store is reopened"
+ );
+ drop(reopened);
+ let _storage = DefaultStorageForTest::install(&signed_out).await;
+
+ // Moved, not copied: signing back in finds no stale key in the user's
+ // database (only the session authenticates there).
+ let again = sign_in(&signed_out, "user-42").await;
+ assert_eq!(api_key::get_api_key(&again).unwrap(), None);
+ let state = auth_get_state(&again).await.unwrap().value;
+ assert_eq!(state.credential.as_deref(), Some("session"));
+}
+
+// The multi-user side: the key carried into the signed-out profile belongs to
+// this device's signed-out state, never to another account. A different user
+// signing in afterwards does not get it.
+#[tokio::test(flavor = "multi_thread")]
+#[allow(clippy::await_holding_lock)] // Serializes the process-wide storage slot.
+async fn another_user_signing_in_does_not_get_the_first_users_api_key() {
+ 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 first = sign_in(&pre_login, "user-42").await;
+ set_api_key(&first, "sk-first-user").await;
+ clear_credential(
+ &DispatchCtx::process_default(),
+ &first,
+ Some(session_support::CredentialKind::Session),
+ )
+ .await
+ .unwrap();
+ let signed_out = crate::config::load_config_with_timeout().await.unwrap();
+ assert_eq!(
+ api_key::get_api_key(&signed_out).unwrap().as_deref(),
+ Some("sk-first-user"),
+ "control: the key is in effect while signed out"
+ );
+
+ let second = sign_in(&signed_out, "user-77").await;
+ assert_eq!(
+ api_key::get_api_key(&second).unwrap(),
+ None,
+ "another account must not get the first user's API key"
+ );
+ let state = auth_get_state(&second).await.unwrap().value;
+ assert!(state.is_authenticated);
+ assert_eq!(state.credential.as_deref(), Some("session"));
+ assert_eq!(state.user_id.as_deref(), Some("user-77"));
+}
diff --git a/crates/openhuman-core/src/security/credentials/ops_tests.rs b/crates/openhuman-core/src/security/credentials/ops_tests.rs
index fbeba9eac1..2e57422324 100644
--- a/crates/openhuman-core/src/security/credentials/ops_tests.rs
+++ b/crates/openhuman-core/src/security/credentials/ops_tests.rs
@@ -83,5 +83,8 @@ fn store_live_session(user_id: &str) -> Config {
mod credential_local_session_tests;
#[path = "ops_credential_tests.rs"]
mod credential_tests;
+#[cfg(feature = "storage-sqlite")]
+#[path = "ops_credential_per_user_storage_tests.rs"]
+mod credential_per_user_storage_tests;
#[path = "ops_provider_oauth_tests.rs"]
mod provider_oauth_tests;