Skip to content

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

fix(session): handle stale credential responses after concurrent login or logout

Steven Enamakelbbafb9820bac
diff --git a/app/src/services/session/sessionOwner.ts b/app/src/services/session/sessionOwner.ts
index 1b4dff0ad5..25c3fa2e80 100644
--- a/app/src/services/session/sessionOwner.ts
+++ b/app/src/services/session/sessionOwner.ts
@@ -210,6 +210,12 @@ const browserCurrentUser = async (force: boolean): Promise<SessionCurrentUser> =
}
try {
const user = await browserFetchMe(token);
+ // Do not publish a response obtained with an old credential after a
+ // concurrent login or logout installed a new one.
+ const latest = await callCoreRpc<{ result: { token: string | null } }>({
+ method: 'openhuman.auth_get_session_token',
+ });
+ if (latest.result.token !== token) return browserCurrentUser(force);
browserCurrentUserCache = { token, fetchedAt: Date.now(), user };
return { user, stale: false, staleSeconds: 0 };
} catch (error) {
@@ -222,11 +228,11 @@ const browserCurrentUser = async (force: boolean): Promise<SessionCurrentUser> =
method: 'openhuman.auth_get_session_token',
}).catch(() => null);
if (latest?.result.token === token) {
- browserCurrentUserCache = null;
await callCoreRpc({
method: 'openhuman.auth_clear_credential',
params: { kind: 'session' },
- }).catch(() => undefined);
+ });
+ browserCurrentUserCache = null;
} else {
return browserCurrentUser(false);
}
diff --git a/crates/openhuman-core/src/core/dispatch.rs b/crates/openhuman-core/src/core/dispatch.rs
index b8a44071f8..234e9de31b 100644
--- a/crates/openhuman-core/src/core/dispatch.rs
+++ b/crates/openhuman-core/src/core/dispatch.rs
@@ -54,6 +54,17 @@ pub async fn dispatch(
resolved
);
}
+ let params = if method == "openhuman.auth_clear_session" {
+ // The legacy method was session-only. Keep that contract even though
+ // its canonical successor accepts an omitted kind to clear all kinds.
+ let mut params = params;
+ if let Value::Object(ref mut object) = params {
+ object.entry("kind".to_string()).or_insert_with(|| json!("session"));
+ }
+ params
+ } else {
+ params
+ };
let method = resolved;
// Tier 1: Internal core methods.
diff --git a/crates/openhuman-core/src/security/credentials/ops/credential.rs b/crates/openhuman-core/src/security/credentials/ops/credential.rs
index 0eddb6c0d4..49f363f5ae 100644
--- a/crates/openhuman-core/src/security/credentials/ops/credential.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/credential.rs
@@ -269,7 +269,8 @@ pub async fn set_credential(
effective
};
- AuthService::from_config(&effective_config)
+ let auth = AuthService::from_config(&effective_config);
+ auth
.store_provider_token(
APP_SESSION_PROVIDER,
DEFAULT_AUTH_PROFILE_NAME,
@@ -281,10 +282,14 @@ pub async fn set_credential(
logs.push(format!("{} credential stored", resolved.kind.as_str()));
if !refresh {
- logs.extend(rebind_after_credential_change(
- &effective_config,
- "credential installed",
- )?);
+ 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(&effective_config).await;
logs.push("credential-gated services started".to_string());
crate::memory::ops::maintenance::reembed_best_effort(
diff --git a/crates/openhuman-session/src/cache.rs b/crates/openhuman-session/src/cache.rs
index ea5c46e757..ef9e0330bc 100644
--- a/crates/openhuman-session/src/cache.rs
+++ b/crates/openhuman-session/src/cache.rs
@@ -274,6 +274,16 @@ impl CurrentUserCache {
}
}
+ // The first caller owns the network refresh. Concurrent cache misses
+ // (including forced refreshes) wait for it, then reuse its result.
+ // This avoids multiplying `/auth/me` requests during startup/polling.
+ let waited_for_refresh = self.inner.inflight.try_lock().is_err();
+ let refresh_guard = self.inner.inflight.lock().await;
+ if waited_for_refresh {
+ if let Some((user, _)) = self.cached(&key) {
+ return Ok(self.with_result(&key, Some(user)));
+ }
+ }
let timeout = fetch_timeout();
match tokio::time::timeout(
timeout,
@@ -391,7 +401,11 @@ impl CurrentUserCache {
"{LOG_PREFIX} discarding refresh that raced sign-out or an identity switch"
);
}
- Ok(fetched)
+ if committed {
+ Ok(fetched)
+ } else {
+ Err(FetchMeError::Superseded)
+ }
}
}
diff --git a/crates/openhuman-session/src/client.rs b/crates/openhuman-session/src/client.rs
index d12da9a7d0..075587d396 100644
--- a/crates/openhuman-session/src/client.rs
+++ b/crates/openhuman-session/src/client.rs
@@ -126,6 +126,10 @@ pub enum FetchMeError {
Transient(String),
/// The request never got an answer (connect/timeout/TLS/read failure).
Transport(String),
+ /// A refresh completed after its credential was replaced or cleared.
+ /// Callers must read the current core credential and retry instead of
+ /// applying this response to the prior session.
+ Superseded,
/// Replayed from the current-user cache's backoff window instead of going
/// to the network. Carries the failure that opened the window.
Suppressed {
@@ -139,6 +143,7 @@ impl FetchMeError {
pub fn message(&self) -> &str {
match self {
Self::Rejected(m) | Self::Transient(m) | Self::Transport(m) => m,
+ Self::Superseded => "refresh superseded by a credential change",
Self::Suppressed { message, .. } => message,
}
}
diff --git a/crates/openhuman-session/src/manager.rs b/crates/openhuman-session/src/manager.rs
index a49aef0e40..730604b253 100644
--- a/crates/openhuman-session/src/manager.rs
+++ b/crates/openhuman-session/src/manager.rs
@@ -256,6 +256,13 @@ impl<L: CoreLink> SessionManager<L> {
);
Err(SessionError::Rejected(reason))
}
+ Err(FetchMeError::Superseded) => {
+ log::debug!(
+ "{LOG_PREFIX} current-user refresh was superseded; retrying with the current core credential"
+ );
+ let current = self.core_state().await?;
+ self.current_user_for(&current, force).await
+ }
Err(error) => {
let reason = error.message().to_string();
if jwt_is_live(&credential.secret, now).is_none() {