Skip to content

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

fix(auth): drop every current-user cache on sign-out (#5758)

Nguyen Thanh Dat2c9012b69152
diff --git a/src/openhuman/desktop/app_state/ops.rs b/src/openhuman/desktop/app_state/ops.rs
index 07a5fa0863..4ee31f6b30 100644
--- a/src/openhuman/desktop/app_state/ops.rs
+++ b/src/openhuman/desktop/app_state/ops.rs
@@ -7,5 +7,6 @@ mod tests;
include!("ops_auth_timeout.rs");
include!("ops_part_01.rs");
include!("ops_staleness.rs");
+include!("ops_current_user_generation.rs");
include!("ops_part_02.rs");
include!("ops_part_03.rs");
diff --git a/src/openhuman/desktop/app_state/ops_current_user_backoff_tests.rs b/src/openhuman/desktop/app_state/ops_current_user_backoff_tests.rs
index 3e03efbf7b..d439628b31 100644
--- a/src/openhuman/desktop/app_state/ops_current_user_backoff_tests.rs
+++ b/src/openhuman/desktop/app_state/ops_current_user_backoff_tests.rs
@@ -26,11 +26,11 @@ use serde_json::json;
/// whole point of that test is that `fetch_current_user_cached` consults the
/// record. Kept distinct from `APP_STATE_CACHE_TEST_LOCK` because the two guard
/// different globals and nothing here writes the positive cache.
-static CURRENT_USER_FAILURE_TEST_LOCK: TestLazy<tokio::sync::Mutex<()>> =
+pub(super) static CURRENT_USER_FAILURE_TEST_LOCK: TestLazy<tokio::sync::Mutex<()>> =
TestLazy::new(|| tokio::sync::Mutex::new(()));
/// Drops the seeded outage on the way out, so one test cannot leak into the next.
-struct CurrentUserFailureResetGuard;
+pub(super) struct CurrentUserFailureResetGuard;
impl Drop for CurrentUserFailureResetGuard {
fn drop(&mut self) {
@@ -40,7 +40,7 @@ impl Drop for CurrentUserFailureResetGuard {
/// Overwrite the failure record with one that failed `age` ago, so a test can
/// sit either side of a backoff window without sleeping.
-fn seed_current_user_failure(
+pub(super) fn seed_current_user_failure(
api_base: &str,
token: &str,
consecutive: u32,
@@ -270,7 +270,7 @@ async fn fetch_current_user_cached_replays_a_recorded_failure_without_calling_th
CurrentUserFetchError::FetchFailed("seeded outage marker".to_string()),
);
- let error = fetch_current_user_cached(&config, token, true)
+ let error = fetch_current_user_cached(&config, token, true, current_user_generation())
.await
.expect_err("a recorded failure inside its window must be replayed");
@@ -308,7 +308,7 @@ async fn a_replayed_failure_is_tagged_suppressed_and_keeps_the_original_message(
CurrentUserFetchError::FetchFailed("request timed out after 5s".to_string()),
);
- let error = fetch_current_user_cached(&config, token, true)
+ let error = fetch_current_user_cached(&config, token, true, current_user_generation())
.await
.expect_err("a recorded failure inside its window must be replayed");
@@ -364,7 +364,7 @@ fn a_suppressed_replay_is_never_recorded_as_a_fresh_failure() {
// ── Stale-snapshot age (#5930) ──────────────────────────────────────────────
/// Drops both the outage and the success stamp on the way out.
-struct CurrentUserStalenessResetGuard;
+pub(super) struct CurrentUserStalenessResetGuard;
impl Drop for CurrentUserStalenessResetGuard {
fn drop(&mut self) {
diff --git a/src/openhuman/desktop/app_state/ops_current_user_generation.rs b/src/openhuman/desktop/app_state/ops_current_user_generation.rs
new file mode 100644
index 0000000000..831e4f1478
--- /dev/null
+++ b/src/openhuman/desktop/app_state/ops_current_user_generation.rs
@@ -0,0 +1,167 @@
+// Sign-out invalidation for the current-user caches.
+//
+// `CURRENT_USER_CACHE`, `CURRENT_USER_FAILURE` and `LAST_CURRENT_USER_SUCCESS`
+// are all keyed on `(api_base, token)`, so clearing them is not enough on its
+// own:
+// `fetch_current_user_cached` awaits the network between reading them and
+// writing them, and a refresh already in flight when sign-out lands would
+// re-publish exactly the state the sign-out removed. A generation counter,
+// read when the token is read and re-checked under each cache's own lock,
+// is what closes that window (#5758).
+
+/// Bumped by [`forget_current_user_caches`]; read by `snapshot` before it
+/// loads the session token, threaded into `fetch_current_user_cached`, and
+/// checked again under the lock before either cache is written.
+///
+/// Counting rather than flagging keeps two overlapping sign-outs from
+/// cancelling each other out.
+static CURRENT_USER_GENERATION: AtomicU64 = AtomicU64::new(0);
+
+/// The failure write itself, taking the guard rather than the lock, so a caller
+/// that must decide *under* the lock can do so without re-entering it.
+fn record_current_user_failure_locked(
+ failure: &mut Option<CurrentUserFailure>,
+ api_base: &str,
+ token: &str,
+ error: CurrentUserFetchError,
+) {
+ let consecutive = match failure.as_ref() {
+ Some(entry) if entry.api_base == api_base && entry.token == token => {
+ entry.consecutive.saturating_add(1)
+ }
+ _ => 1,
+ };
+ *failure = Some(CurrentUserFailure {
+ api_base: api_base.to_string(),
+ token: token.to_string(),
+ failed_at: Instant::now(),
+ consecutive,
+ error,
+ });
+}
+
+/// Drop every current-user cache.
+///
+/// Sign-out must forget the positive snapshot *and* the negative failure record
+/// together: signing back in with the same JWT inside their windows would
+/// otherwise replay pre-logout state — the old `/auth/me` snapshot for the rest
+/// of [`CURRENT_USER_REFRESH_TTL`], and the old error for up to
+/// [`CURRENT_USER_BACKOFF_MAX`].
+///
+/// The freshness stamp goes with them. `clear_current_user_success` already
+/// says why — "so the next account does not inherit this one's freshness"
+/// — and sign-out is exactly the case it names; until now it ran only on
+/// the deferred-rejection path (#5930).
+///
+/// Public because the canonical sign-out path lives in
+/// `security::credentials::ops::clear_session`, outside this module, and these
+/// statics are private to it.
+pub fn forget_current_user_caches() {
+ // Bump BEFORE taking either lock. That order is what makes the checks in
+ // `publish_current_user_unless_stale` and
+ // `record_current_user_failure_unless_stale` sufficient: a writer holding
+ // one of these locks either observes the bump and stands down, or read the
+ // generation before it — in which case its write necessarily completed and
+ // released the lock before the clear below could acquire it, so the clear
+ // lands second and wins. There is no interleaving that leaves pre-logout
+ // state behind.
+ CURRENT_USER_GENERATION.fetch_add(1, Ordering::SeqCst);
+ *CURRENT_USER_CACHE.lock() = None;
+ clear_current_user_failure();
+ clear_current_user_success();
+}
+
+/// The sign-out generation a refresh must still be running under to publish.
+fn current_user_generation() -> u64 {
+ CURRENT_USER_GENERATION.load(Ordering::SeqCst)
+}
+
+/// Record an availability failure only if `generation` is still current,
+/// **checked while holding the failure lock**.
+///
+/// Checking before the lock would be a check-then-act: sign-out could land in
+/// the gap and this write would then restore the negative cache it had just
+/// cleared.
+fn record_current_user_failure_unless_stale(
+ generation: u64,
+ api_base: &str,
+ token: &str,
+ error: CurrentUserFetchError,
+) -> bool {
+ if !error.is_availability_failure() {
+ return true;
+ }
+ let mut failure = CURRENT_USER_FAILURE.lock();
+ if current_user_generation() != generation {
+ return false;
+ }
+ record_current_user_failure_locked(&mut failure, api_base, token, error);
+ true
+}
+
+/// Stamp a refreshed user's freshness only if `generation` is still current,
+/// **checked while holding the success lock** — the same check-then-act the
+/// failure recorder avoids, for the same reason.
+fn note_current_user_success_unless_stale(generation: u64, api_base: &str, token: &str) -> bool {
+ let mut success = LAST_CURRENT_USER_SUCCESS.lock();
+ if current_user_generation() != generation {
+ return false;
+ }
+ note_current_user_success_locked(&mut success, api_base, token);
+ true
+}
+
+/// Publish a fresh `/auth/me` answer to the positive cache, and drop any
+/// recorded outage, only if `generation` is still current — each check taken
+/// under the lock that guards the record it gates.
+///
+/// Returns `false` when sign-out won, in which case nothing was written.
+fn publish_current_user_unless_stale(
+ generation: u64,
+ api_base: &str,
+ token: &str,
+ fetched: Option<Value>,
+) -> bool {
+ // Only a refreshed *user* makes the displayed data fresh: the backend can
+ // answer 200 with no user, and the caller then falls back to `stored_user`,
+ // so stamping here would report an age of ~0s for data that never changed.
+ //
+ // Taken before the cache lock and never inside it, because `ops_staleness`
+ // requires that `LAST_CURRENT_USER_SUCCESS` never nest inside
+ // `CURRENT_USER_CACHE`. Standing down here ends the publish: if sign-out has
+ // landed, none of the three records may be written.
+ if fetched.is_some() && !note_current_user_success_unless_stale(generation, api_base, token) {
+ return false;
+ }
+
+ {
+ let mut cache = CURRENT_USER_CACHE.lock();
+ if current_user_generation() != generation {
+ return false;
+ }
+ match fetched {
+ Some(user) => {
+ debug!("{LOG_PREFIX} refreshed current user from backend");
+ *cache = Some(CachedCurrentUser {
+ api_base: api_base.to_string(),
+ token: token.to_string(),
+ fetched_at: Instant::now(),
+ user,
+ });
+ }
+ None => {
+ debug!("{LOG_PREFIX} backend returned empty current user; clearing cache");
+ *cache = None;
+ }
+ }
+ }
+
+ // Clearing only ever removes state, so it cannot replay a pre-logout answer
+ // — but it could erase an outage a *new* session recorded after signing back
+ // in, so it takes the same guard.
+ let mut failure = CURRENT_USER_FAILURE.lock();
+ if current_user_generation() == generation {
+ *failure = None;
+ }
+ true
+}
diff --git a/src/openhuman/desktop/app_state/ops_part_01.rs b/src/openhuman/desktop/app_state/ops_part_01.rs
index c3e38e5bff..33d8f0203d 100644
--- a/src/openhuman/desktop/app_state/ops_part_01.rs
+++ b/src/openhuman/desktop/app_state/ops_part_01.rs
@@ -228,19 +228,7 @@ fn record_current_user_failure(api_base: &str, token: &str, error: CurrentUserFe
return;
}
let mut failure = CURRENT_USER_FAILURE.lock();
- let consecutive = match failure.as_ref() {
- Some(entry) if entry.api_base == api_base && entry.token == token => {
- entry.consecutive.saturating_add(1)
- }
- _ => 1,
- };
- *failure = Some(CurrentUserFailure {
- api_base: api_base.to_string(),
- token: token.to_string(),
- failed_at: Instant::now(),
- consecutive,
- error,
- });
+ record_current_user_failure_locked(&mut failure, api_base, token, error);
}
/// Forget any recorded failure, so the next poll goes straight to the network.
@@ -259,8 +247,14 @@ fn clear_current_user_failure() {
/// mid-flight** and nothing inside it runs — including the failure recording on
/// its error path. Without this call the backoff would never engage for the one
/// case #5624 is actually about, which is timeouts rather than returned errors.
-fn note_current_user_timeout(config: &Config, token: &str) {
- record_current_user_failure(
+///
+/// Takes the generation read before the timeout started, for the same reason the
+/// refresh does: a sign-out during those `auth_fetch_timeout()` seconds means this
+/// outage belongs to an identity that no longer exists, and recording it would
+/// suppress the first poll of the next session.
+fn note_current_user_timeout(generation: u64, config: &Config, token: &str) {
+ record_current_user_failure_unless_stale(
+ generation,
&current_user_api_base(config),
token,
CurrentUserFetchError::FetchFailed(format!(
diff --git a/src/openhuman/desktop/app_state/ops_part_02.rs b/src/openhuman/desktop/app_state/ops_part_02.rs
index ad48396c3e..02c934c1f7 100644
--- a/src/openhuman/desktop/app_state/ops_part_02.rs
+++ b/src/openhuman/desktop/app_state/ops_part_02.rs
@@ -138,9 +138,7 @@ async fn clear_deferred_session_after_backend_rejection(
))
});
- *CURRENT_USER_CACHE.lock() = None;
- clear_current_user_failure();
- clear_current_user_success();
+ forget_current_user_caches();
crate::openhuman::cron::scheduler_gate::set_signed_out(true);
match crate::openhuman::config::default_root_openhuman_dir() {
@@ -180,6 +178,7 @@ async fn fetch_current_user_cached(
config: &Config,
token: &str,
allow_cache: bool,
+ generation: u64,
) -> Result<Option<Value>, CurrentUserFetchError> {
let api_base = current_user_api_base(config);
@@ -228,42 +227,28 @@ async fn fetch_current_user_cached(
}
}
+ // `generation` belongs to the caller and was read when the TOKEN was read.
+ // Everything after this point is publishing an answer about an identity that
+ // sign-out may have dropped in the meantime; if it has, the answer is stale by
+ // definition and goes nowhere near the caches. The caller still gets it — it
+ // asked before the sign-out, and suppressing the reply is a different change
+ // from suppressing the cache.
let fetched = match fetch_current_user(config, token).await {
Ok(user) => sanitize_snapshot_user(user),
Err(error) => {
- record_current_user_failure(&api_base, token, error.clone());
+ if !record_current_user_failure_unless_stale(
+ generation,
+ &api_base,
+ token,
+ error.clone(),
+ ) {
+ debug!("{LOG_PREFIX} discarding current user failure that raced sign-out");
+ }
return Err(error);
}
};
- clear_current_user_failure();
- // Only a *refreshed user* makes the displayed data fresh. The backend can
- // answer 200 with no user at all, and the snapshot caller then falls back
- // to `stored_user` — so stamping success here would report an age of ~0s
- // for data that was never replaced. `clear_current_user_failure` still runs
- // either way: an empty answer is the backend being healthy, just not
- // useful, and it should not keep the backoff window open.
- //
- // Read before the cache lock rather than inside the `Some` arm below, so
- // this never nests `LAST_CURRENT_USER_SUCCESS` inside `CURRENT_USER_CACHE`.
- if fetched.is_some() {
- note_current_user_success(&api_base, token);
- }
-
- let mut cache = CURRENT_USER_CACHE.lock();
- match fetched.clone() {
- Some(user) => {
- debug!("{LOG_PREFIX} refreshed current user from backend");
- *cache = Some(CachedCurrentUser {
- api_base,
- token: token.to_string(),
- fetched_at: Instant::now(),
- user,
- });
- }
- None => {
- debug!("{LOG_PREFIX} backend returned empty current user; clearing cache");
- *cache = None;
- }
+ if !publish_current_user_unless_stale(generation, &api_base, token, fetched.clone()) {
+ debug!("{LOG_PREFIX} discarding current user refresh that raced sign-out");
}
Ok(fetched)
diff --git a/src/openhuman/desktop/app_state/ops_part_03.rs b/src/openhuman/desktop/app_state/ops_part_03.rs
index 0de1ebc307..a9fd6d121e 100644
--- a/src/openhuman/desktop/app_state/ops_part_03.rs
+++ b/src/openhuman/desktop/app_state/ops_part_03.rs
@@ -28,6 +28,15 @@ pub async fn snapshot() -> Result<RpcOutcome<AppStateSnapshot>, String> {
// it directly on a tokio worker thread blocks that thread for the entire
// wait, exhausting the thread pool under concurrent snapshot calls and
// triggering `ERR_CONNECTION_TIMED_OUT` on all RPC connections.
+ // Read the sign-out generation BEFORE the profile load, not before the
+ // refresh. The token this snapshot is about is the one that load returns, so
+ // the generation has to be the one in force when that token was read.
+ // Capturing it later leaves a window — sign-out lands between the load and the
+ // refresh, the refresh reads the *new* generation, and then publishes an answer
+ // fetched with the *old* token, passing its own staleness check.
+ // `load_app_session_profile` busy-waits up to ~35s on a contended lock, so that
+ // window is not a narrow one.
+ let generation = current_user_generation();
let config_for_profile = config.clone();
let session_profile =
tokio::task::spawn_blocking(move || load_app_session_profile(&config_for_profile))
@@ -64,7 +73,7 @@ pub async fn snapshot() -> Result<RpcOutcome<AppStateSnapshot>, String> {
}
match tokio::time::timeout(
auth_fetch_timeout(),
- fetch_current_user_cached(&config, &token, !pending_backend_validation),
+ fetch_current_user_cached(&config, &token, !pending_backend_validation, generation),
)
.await
{
@@ -179,7 +188,7 @@ pub async fn snapshot() -> Result<RpcOutcome<AppStateSnapshot>, String> {
"{LOG_PREFIX} pending current user fetch timed out after {}s; keeping stored pending session for retry",
auth_fetch_timeout().as_secs()
);
- note_current_user_timeout(&config, &token);
+ note_current_user_timeout(generation, &config, &token);
snapshot_current_user_result(stored_user.clone())
}
Err(_) => {
@@ -187,7 +196,7 @@ pub async fn snapshot() -> Result<RpcOutcome<AppStateSnapshot>, String> {
"{LOG_PREFIX} current user fetch timed out after {}s; using stored snapshot fallback",
auth_fetch_timeout().as_secs()
);
- note_current_user_timeout(&config, &token);
+ note_current_user_timeout(generation, &config, &token);
snapshot_current_user_result(stored_user.clone())
}
}
diff --git a/src/openhuman/desktop/app_state/ops_signout_cache_tests.rs b/src/openhuman/desktop/app_state/ops_signout_cache_tests.rs
new file mode 100644
index 0000000000..d84aa5a7e6
--- /dev/null
+++ b/src/openhuman/desktop/app_state/ops_signout_cache_tests.rs
@@ -0,0 +1,460 @@
+// Sign-out invalidation for the current-user caches (#5758).
+//
+// `super` is the `tests` module; its `use super::*` re-exports both the ops
+// items under test and this suite's shared cache lock.
+use super::*;
+
+// The failure-cache test fixtures live in the backoff suite, which owns that
+// global. Borrowing its lock rather than declaring a second one is the point:
+// two locks over one static is exactly the interference this suite hit.
+use super::super::current_user_backoff_tests::{
+ seed_current_user_failure, CurrentUserFailureResetGuard, CurrentUserStalenessResetGuard,
+ CURRENT_USER_FAILURE_TEST_LOCK,
+};
+
+// ── Sign-out cache invalidation (#5758) ────────────────────────────────────
+//
+// Both caches are keyed on `(api_base, token)`, so leaving either behind lets a
+// re-login with the same JWT replay pre-logout state: the stale `/auth/me`
+// snapshot from the positive cache, or the stale error from the negative one.
+//
+// `forget_current_user_caches` touches BOTH globals, so both cases hold both of
+// this suite's cache locks — in this order, consistently, since no other test
+// takes more than one.
+
+// Sign-out itself must reach `forget_current_user_caches`, not merely be able
+// to. The two direct-call cases below cannot see that wiring: deleting the call
+// from `clear_session` leaves every test in this file, and in the credentials
+// suite, passing. This one goes through the real entry point.
+//
+// `clear_session` clears the active-user marker under
+// `default_root_openhuman_dir()`, which is derived from the process-global HOME,
+// so it takes the shared env lock and pins HOME to its own tempdir -- the same
+// precaution `clear_session_on_empty_store_reports_removed_false` documents.
+#[tokio::test]
+async fn signing_out_forgets_both_current_user_caches() {
+ let _env_lock = crate::openhuman::config::TEST_ENV_LOCK
+ .lock()
+ .unwrap_or_else(|e| e.into_inner());
+ let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock();
+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;
+ let _reset = CurrentUserFailureResetGuard;
+
+ let tmp = tempdir().expect("tempdir");
+ let previous_home = std::env::var_os("HOME");
+ unsafe { std::env::set_var("HOME", tmp.path()) };
+
+ let api_base = "https://api.example.test";
+ let token = "jwt-5758-signout";
+ *CURRENT_USER_CACHE.lock() = Some(CachedCurrentUser {
+ api_base: api_base.into(),
+ token: token.into(),
+ fetched_at: Instant::now(),
+ user: json!({ "userId": "user-5758" }),
+ });
+ seed_current_user_failure(
+ api_base,
+ token,
+ 1,
+ Duration::from_millis(0),
+ CurrentUserFetchError::FetchFailed("backend unreachable".to_string()),
+ );
+ assert!(
+ CURRENT_USER_CACHE.lock().is_some()
+ && suppressed_current_user_failure(api_base, token).is_some(),
+ "precondition: both caches must be populated"
+ );
+
+ let config = Config {
+ workspace_dir: tmp.path().join("workspace"),
+ action_dir: tmp.path().join("workspace"),
+ config_path: tmp.path().join("config.toml"),
+ ..Config::default()
+ };
+ crate::openhuman::security::credentials::ops::clear_session(&config)
+ .await
+ .expect("clear_session on an empty store still succeeds");
+
+ match previous_home {
+ Some(value) => unsafe { std::env::set_var("HOME", value) },
+ None => unsafe { std::env::remove_var("HOME") },
+ }
+
+ assert!(
+ CURRENT_USER_CACHE.lock().is_none(),
+ "sign-out left the pre-logout /auth/me snapshot behind"
+ );
+ assert!(
+ suppressed_current_user_failure(api_base, token).is_none(),
+ "sign-out left the pre-logout availability failure behind"
+ );
+}
+
+#[test]
+fn forget_current_user_caches_clears_the_positive_snapshot() {
+ let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock();
+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();
+ let _reset = CurrentUserFailureResetGuard;
+
+ *CURRENT_USER_CACHE.lock() = Some(CachedCurrentUser {
+ api_base: "https://api.example.test".into(),
+ token: "jwt-5758".into(),
+ fetched_at: Instant::now(),
+ user: json!({ "userId": "user-5758" }),
+ });
+ assert!(
+ CURRENT_USER_CACHE.lock().is_some(),
+ "precondition: the snapshot must be cached for this test to mean anything"
+ );
+
+ forget_current_user_caches();
+
+ assert!(
+ CURRENT_USER_CACHE.lock().is_none(),
+ "the pre-logout /auth/me snapshot survived sign-out"
+ );
+}
+
+#[test]
+fn forget_current_user_caches_clears_the_freshness_stamp() {
+ let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock();
+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();
+ let _reset = CurrentUserStalenessResetGuard;
+
+ let api_base = "https://api.example.test";
+ let token = "jwt-5758c";
+ note_current_user_success(api_base, token);
+ assert!(
+ current_user_staleness(api_base, token).1.is_some(),
+ "precondition: the stamp must be set for this test to mean anything"
+ );
+
+ forget_current_user_caches();
+
+ assert_eq!(
+ current_user_staleness(api_base, token).1,
+ None,
+ "the pre-logout freshness stamp survived sign-out, so the next account \
+ would be told this one's data age"
+ );
+}
+
+#[test]
+fn forget_current_user_caches_clears_the_negative_failure() {
+ let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock();
+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();
+ let _reset = CurrentUserFailureResetGuard;
+
+ let api_base = "https://api.example.test";
+ let token = "jwt-5758b";
+ seed_current_user_failure(
+ api_base,
+ token,
+ 1,
+ Duration::from_millis(0),
+ CurrentUserFetchError::FetchFailed("backend unreachable".to_string()),
+ );
+ assert!(
+ suppressed_current_user_failure(api_base, token).is_some(),
+ "precondition: the failure must be suppressing for this test to mean anything"
+ );
+
+ forget_current_user_caches();
+
+ assert!(
+ suppressed_current_user_failure(api_base, token).is_none(),
+ "the pre-logout availability failure survived sign-out, so a re-login with the same JWT would replay it"
+ );
+}
+
+// ── A refresh that races sign-out must not republish (#5758, review) ────────
+//
+// Clearing the two statics is not sufficient on its own. `fetch_current_user_cached`
+// awaits the network between reading the caches and writing them, so a refresh
+// already in flight when sign-out lands would write the pre-logout answer back
+// afterwards — restoring exactly what sign-out just dropped.
+//
+// The synchronisation here is structural, not timed: the fake backend accepts
+// the connection and then *waits*, so the request is provably in flight when
+// sign-out runs, and the response is not released until after it.
+
+/// Minimal `/auth/me` backend that hands control back to the test mid-request.
+///
+/// `Connection: close` rather than a Content-Length, so the body length is not
+/// a thing this test can get subtly wrong.
+async fn spawn_racing_backend(
+ body: &'static str,
+ status_line: &'static str,
+) -> (
+ u16,
+ tokio::sync::oneshot::Receiver<()>,
+ tokio::sync::oneshot::Sender<()>,
+ tokio::task::JoinHandle<()>,
+) {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind loopback");
+ let port = listener.local_addr().expect("local addr").port();
+
+ let (in_flight_tx, in_flight_rx) = tokio::sync::oneshot::channel();
+ let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>();
+
+ let handle = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.expect("accept");
+
+ // Drain enough of the request that the client has certainly sent it.
+ let mut buf = [0u8; 1024];
+ let _ = socket.read(&mut buf).await;
+
+ // The request is in flight. Sign-out can happen now.
+ let _ = in_flight_tx.send(());
+ let _ = release_rx.await;
+
+ let response = format!("{status_line}\r\nConnection: close\r\n\r\n{body}");
+ let _ = socket.write_all(response.as_bytes()).await;
+ let _ = socket.shutdown().await;
+ });
+
+ (port, in_flight_rx, release_tx, handle)
+}
+
+#[tokio::test]
+async fn a_successful_refresh_that_races_sign_out_does_not_repopulate_the_snapshot() {
+ let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock();
+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;
+ let _reset = CurrentUserFailureResetGuard;
+
+ forget_current_user_caches();
+
+ let (port, in_flight, release, server) = spawn_racing_backend(
+ r#"{"data":{"userId":"user-before-logout"}}"#,
+ "HTTP/1.1 200 OK",
+ )
+ .await;
+
+ let mut config = Config::default();
+ config.api_url = Some(format!("http://127.0.0.1:{port}/"));
+ // Read where the caller reads it: alongside the token, before the refresh.
+ let generation = current_user_generation();
+ // Resolved before `config` moves into the task; the freshness stamp is keyed
+ // on it, so the assertion at the end needs the same string the fetch used.
+ let api_base_probe = current_user_api_base(&config);
+
+ let fetch = tokio::spawn(async move {
+ fetch_current_user_cached(&config, "jwt-race", true, generation).await
+ });
+
+ in_flight.await.expect("backend saw the request");
+ // The user signs out while the refresh is on the wire.
+ forget_current_user_caches();
+ let _ = release.send(());
+
+ let result = fetch.await.expect("join fetch");
+ server.await.expect("join backend");
+
+ assert!(
+ result.is_ok(),
+ "the caller that asked before sign-out still gets its answer"
+ );
+ assert!(
+ CURRENT_USER_CACHE.lock().is_none(),
+ "a refresh that finished after sign-out republished the pre-logout snapshot, \
+ which is the state sign-out exists to drop"
+ );
+ assert_eq!(
+ current_user_staleness(&api_base_probe, "jwt-race").1,
+ None,
+ "the raced refresh stamped the signed-out identity as freshly loaded"
+ );
+}
+
+#[tokio::test]
+async fn a_failed_refresh_that_races_sign_out_does_not_record_a_failure() {
+ let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock();
+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;
+ let _reset = CurrentUserFailureResetGuard;
+
+ forget_current_user_caches();
+
+ // 500 is in AUTH_ME_REVALIDATION_TRANSIENT_STATUSES, so this takes the
+ // record-a-failure path rather than the rejection path.
+ let (port, in_flight, release, server) =
+ spawn_racing_backend("backend is down", "HTTP/1.1 500 Internal Server Error").await;
+
+ let mut config = Config::default();
+ config.api_url = Some(format!("http://127.0.0.1:{port}/"));
+ let api_base = current_user_api_base(&config);
+ // Read where the caller reads it: alongside the token, before the refresh.
+ let generation = current_user_generation();
+
+ let fetch = tokio::spawn(async move {
+ fetch_current_user_cached(&config, "jwt-race-err", true, generation).await
+ });
+
+ in_flight.await.expect("backend saw the request");
+ forget_current_user_caches();
+ let _ = release.send(());
+
+ let result = fetch.await.expect("join fetch");
+ server.await.expect("join backend");
+
+ assert!(result.is_err(), "precondition: the fetch must have failed");
+ assert!(
+ suppressed_current_user_failure(&api_base, "jwt-race-err").is_none(),
+ "a failure recorded after sign-out would suppress the first poll of the \
+ next session, replaying an outage the new session never saw"
+ );
+}
+
+// The two above prove the guard across a real await. These two close the
+// narrower window inside it: the moment between reading the generation and
+// taking the lock. There is nothing to pause here — the "pause" IS the call
+// order, which is why these are deterministic rather than timed.
+
+#[tokio::test]
+async fn a_sign_out_landing_after_the_generation_check_still_wins_the_snapshot() {
+ let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock();
+ // Both globals are touched here, so both guards are needed. The failure
+ // lock is async, which is why these three were sync-only and unguarded.
+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;
+ let _reset = CurrentUserFailureResetGuard;
+
+ forget_current_user_caches();
+ // The refresh reads the generation, and is descheduled right here.
+ let generation = current_user_generation();
+ // Sign-out lands in that gap: it bumps, then clears both records.
+ forget_current_user_caches();
+ // The refresh resumes and tries to publish.
+ let published = publish_current_user_unless_stale(
+ generation,
+ "http://127.0.0.1:1/",
+ "jwt-before-logout",
+ Some(json!({ "userId": "user-before-logout" })),
+ );
+
+ assert!(!published, "the publish must report that sign-out won");
+ assert!(
+ CURRENT_USER_CACHE.lock().is_none(),
+ "checking the generation before taking the cache lock leaves a window in \
+ which sign-out lands and the pre-logout snapshot is written anyway"
+ );
+}
+
+#[tokio::test]
+async fn a_sign_out_landing_after_the_generation_check_still_wins_the_failure_record() {
+ let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock();
+ // Both globals are touched here, so both guards are needed. The failure
+ // lock is async, which is why these three were sync-only and unguarded.
+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;
+ let _reset = CurrentUserFailureResetGuard;
+
+ forget_current_user_caches();
+ let generation = current_user_generation();
+ forget_current_user_caches();
+ let recorded = record_current_user_failure_unless_stale(
+ generation,
+ "http://127.0.0.1:1/",
+ "jwt-before-logout",
+ CurrentUserFetchError::FetchFailed("backend is down".to_string()),
+ );
+
+ assert!(!recorded, "the record must report that sign-out won");
+ assert!(
+ CURRENT_USER_FAILURE.lock().is_none(),
+ "an outage recorded into that same window outlives the session it \
+ belonged to, and suppresses the next session's first poll"
+ );
+}
+
+#[tokio::test]
+async fn publishing_under_the_current_generation_still_clears_a_recorded_outage() {
+ let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock();
+ // Both globals are touched here, so both guards are needed. The failure
+ // lock is async, which is why these three were sync-only and unguarded.
+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;
+ let _reset = CurrentUserFailureResetGuard;
+
+ forget_current_user_caches();
+ let generation = current_user_generation();
+ record_current_user_failure(
+ "http://127.0.0.1:1/",
+ "jwt-live",
+ CurrentUserFetchError::FetchFailed("backend was down".to_string()),
+ );
+
+ let published = publish_current_user_unless_stale(
+ generation,
+ "http://127.0.0.1:1/",
+ "jwt-live",
+ Some(json!({ "userId": "user-live" })),
+ );
+
+ assert!(
+ published,
+ "no sign-out happened; the answer must be published"
+ );
+ assert!(
+ CURRENT_USER_CACHE.lock().is_some(),
+ "the fresh snapshot must reach the positive cache"
+ );
+ assert!(
+ CURRENT_USER_FAILURE.lock().is_none(),
+ "a success must retire the outage, or the backoff outlives its cause"
+ );
+}
+
+/// Sign-out between the profile load and the refresh must still win.
+///
+/// This is the window the generation moved to cover. `snapshot` reads the token
+/// out of the auth profile — a load that busy-waits up to ~35s on a contended
+/// lock — and only then starts the refresh. Reading the generation inside the
+/// refresh meant a sign-out landing in that gap was already counted, so the
+/// refresh compared the new generation against itself, passed, and published an
+/// answer it had fetched with the token from before the sign-out.
+///
+/// Deterministic without a sleep: the sign-out is expressed by call order, and
+/// the generation handed to the refresh is the one read before it.
+#[tokio::test]
+async fn a_sign_out_between_the_token_load_and_the_refresh_still_wins() {
+ let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock();
+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;
+ let _reset = CurrentUserFailureResetGuard;
+
+ forget_current_user_caches();
+
+ // The snapshot reads the token, and the generation alongside it.
+ let generation = current_user_generation();
+
+ // The user signs out while the auth profile lock is still being waited on.
+ forget_current_user_caches();
+
+ let (port, in_flight, release, server) = spawn_racing_backend(
+ r#"{"data":{"userId":"user-before-logout"}}"#,
+ "HTTP/1.1 200 OK",
+ )
+ .await;
+
+ let mut config = Config::default();
+ config.api_url = Some(format!("http://127.0.0.1:{port}/"));
+
+ // Only now does the refresh start, still carrying the pre-sign-out token.
+ let fetch = tokio::spawn(async move {
+ fetch_current_user_cached(&config, "jwt-before-logout", true, generation).await
+ });
+
+ in_flight.await.expect("backend saw the request");
+ let _ = release.send(());
+
+ let result = fetch.await.expect("join fetch");
+ server.await.expect("join backend");
+
+ assert!(result.is_ok(), "the caller still gets its answer");
+ assert!(
+ CURRENT_USER_CACHE.lock().is_none(),
+ "a refresh holding the pre-sign-out token republished the identity that \
+ sign-out exists to drop, because it read the generation after the \
+ sign-out rather than alongside the token"
+ );
+}
diff --git a/src/openhuman/desktop/app_state/ops_staleness.rs b/src/openhuman/desktop/app_state/ops_staleness.rs
index a39cc84027..0d9a4fbd4e 100644
--- a/src/openhuman/desktop/app_state/ops_staleness.rs
+++ b/src/openhuman/desktop/app_state/ops_staleness.rs
@@ -43,7 +43,17 @@ struct CurrentUserSuccess {
/// serving has become. Callers must not invoke this for an answer that carried
/// no user — see [`LAST_CURRENT_USER_SUCCESS`].
fn note_current_user_success(api_base: &str, token: &str) {
- *LAST_CURRENT_USER_SUCCESS.lock() = Some(CurrentUserSuccess {
+ note_current_user_success_locked(&mut LAST_CURRENT_USER_SUCCESS.lock(), api_base, token);
+}
+
+/// The stamp itself, taking the guard rather than the lock, so a caller that
+/// must decide *under* the lock can do so without re-entering it.
+fn note_current_user_success_locked(
+ success: &mut Option<CurrentUserSuccess>,
+ api_base: &str,
+ token: &str,
+) {
+ *success = Some(CurrentUserSuccess {
api_base: api_base.to_string(),
token: token.to_string(),
at: Instant::now(),
diff --git a/src/openhuman/desktop/app_state/ops_tests.rs b/src/openhuman/desktop/app_state/ops_tests.rs
index b25772469d..f2aa1670b1 100644
--- a/src/openhuman/desktop/app_state/ops_tests.rs
+++ b/src/openhuman/desktop/app_state/ops_tests.rs
@@ -486,3 +486,6 @@ async fn current_user_fetch_carries_the_product_identity() {
crate::api::product::reset_product_identity_for_test();
}
+
+#[path = "ops_signout_cache_tests.rs"]
+mod signout_cache_tests;
diff --git a/src/openhuman/security/credentials/ops_part_02.rs b/src/openhuman/security/credentials/ops_part_02.rs
index 41f1ab4dd9..7e4cb01f2a 100644
--- a/src/openhuman/security/credentials/ops_part_02.rs
+++ b/src/openhuman/security/credentials/ops_part_02.rs
@@ -104,6 +104,11 @@ pub async fn clear_session(config: &Config) -> Result<RpcOutcome<serde_json::Val
}
crate::openhuman::platform::socket::medulla::workflows::clear_workflow_bridge();
+ // Forget the cached `/auth/me` snapshot and the cached availability failure.
+ // Both are keyed on `(api_base, token)`, so signing back in with the same JWT
+ // inside their windows would replay pre-logout state (#5758).
+ crate::openhuman::desktop::app_state::forget_current_user_caches();
+
// Clear the active user marker so subsequent config loads fall back to the
// default (unauthenticated) openhuman directory.
if let Ok(root_dir) = default_root_openhuman_dir() {