From da68d53b6b2025ff26369e971b70d855502e7e25 Mon Sep 17 00:00:00 2001 From: austinbenoit Date: Thu, 3 Dec 2026 20:06:00 +0000 Subject: [PATCH] Auth (Desktop): avoid listeners_mutex in current_user() after cache load Fixes #1972. Makes AuthData::persistent_cache_load_pending a std::atomic so desktop Auth::current_user() skips registering a temporary CurrentUserBlockListener (and acquiring listeners_mutex) once the initial persistent cache load has completed, breaking the lock-order deadlock between Auth::SignOut() and concurrent Firestore token requests. Also updates Auth::GetAuthTokenForRegistry() (FnAuthGetCurrentToken) to read user->id_token directly via UserView::TryRead after ensuring persistent cache load, avoiding a startup race before NotifyIdTokenListeners() populates IdTokenRefreshListener. --- auth/src/auth.cc | 10 +- auth/src/data.h | 9 +- auth/src/desktop/auth_desktop.cc | 33 +++--- auth/tests/desktop/auth_desktop_test.cc | 134 ++++++++++++++++++++++++ release_build_files/readme.md | 3 + 5 files changed, 170 insertions(+), 19 deletions(-) diff --git a/auth/src/auth.cc b/auth/src/auth.cc index 9794629d52..4caa174aa0 100644 --- a/auth/src/auth.cc +++ b/auth/src/auth.cc @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -222,7 +223,8 @@ void Auth::AddAuthStateListener(AuthStateListener* listener) { // If the listener is registered successfully and persistent cache has been // loaded, trigger OnAuthStateChanged() immediately. Otherwise, wait until // the cache is loaded, through AuthStateListener event. - if (added && !auth_data_->persistent_cache_load_pending) { + if (added && !auth_data_->persistent_cache_load_pending.load( + std::memory_order_acquire)) { listener->OnAuthStateChanged(this); } } @@ -241,7 +243,8 @@ void Auth::AddIdTokenListener(IdTokenListener* listener) { // If the listener is registered successfully and persistent cache has been // loaded, trigger OnAuthStateChanged() immediately. Otherwise, wait until // the cache is loaded, through AuthStateListener event - if (!auth_data_->persistent_cache_load_pending) { + if (!auth_data_->persistent_cache_load_pending.load( + std::memory_order_acquire)) { listener->OnIdTokenChanged(this); } EnableTokenAutoRefresh(auth_data_); @@ -323,7 +326,8 @@ static inline bool VectorContains(const T& entry, const std::vector& v) { \ /* Auth should have loaded persistent cache if exists when the listener */ \ /* event is triggered for the first time. */ \ - auth_data->persistent_cache_load_pending = false; \ + auth_data->persistent_cache_load_pending.store(false, \ + std::memory_order_release); \ \ /* Make a copy of the listener list in case it gets modified during */ \ /* notification_method(). Note that modification is possible because */ \ diff --git a/auth/src/data.h b/auth/src/data.h index 58098bb421..0288cf5901 100644 --- a/auth/src/data.h +++ b/auth/src/data.h @@ -17,6 +17,7 @@ #ifndef FIREBASE_AUTH_SRC_DATA_H_ #define FIREBASE_AUTH_SRC_DATA_H_ +#include #include #include "app/src/include/firebase/internal/mutex.h" @@ -161,7 +162,7 @@ struct AuthData { /// Mutex protecting the `listeners`, `id_token_listeners`, and /// `phone_auth_provider.data_->listeners vectors`. /// 'listeners' are added and removed and accessed on different threads. - /// This is also protecting persistent_cache_load_pending flag. + /// Also serializes transitions of `persistent_cache_load_pending`. Mutex listeners_mutex; // Mutex for changes to the internal token listener state. @@ -170,8 +171,10 @@ struct AuthData { // Tracks if the Id Token listener is expecting a callback to occur. bool expect_id_token_listener_callback; - // Tracks if the persistent cache load is pending. - bool persistent_cache_load_pending; + // Tracks if the persistent cache load is pending. Cleared once under + // `listeners_mutex`; atomic so `Auth::current_user()` can fast-path without + // acquiring `listeners_mutex` after cache load completes. + std::atomic persistent_cache_load_pending; // Mutex protecting `expect_id_token_listener_callback` Mutex expect_id_token_mutex; diff --git a/auth/src/desktop/auth_desktop.cc b/auth/src/desktop/auth_desktop.cc index f9607fdaaa..d6badbf1e8 100644 --- a/auth/src/desktop/auth_desktop.cc +++ b/auth/src/desktop/auth_desktop.cc @@ -15,6 +15,7 @@ #include "auth/src/desktop/auth_desktop.h" #include +#include #include #include #include @@ -169,10 +170,13 @@ bool Auth::GetAuthTokenForRegistry(App* app, void* /*unused*/, void* out) { // Make sure the persistent cache is loaded. (void)auth->current_user(); - auto result = static_cast(out); - MutexLock lock(auth->auth_data_->token_listener_mutex); - auto auth_impl = static_cast(auth->auth_data_->auth_impl); - *result = auth_impl->token_refresh_thread.CurrentAuthToken(); + if (out) { + auto result = static_cast(out); + result->clear(); + UserView::TryRead(auth->auth_data_, [&](const UserView::Reader& user) { + *result = user->id_token; + }); + } return true; } return false; @@ -543,15 +547,18 @@ class CurrentUserBlockListener : public firebase::auth::AuthStateListener { User Auth::current_user() { if (!auth_data_) return User(nullptr); - // Add a listener and wait for the first trigger. - CurrentUserBlockListener listener; - AddAuthStateListener(&listener); - // If the persistent cache has not be loaded, this would wait until the - // loading is finished and OnAuthStateChanged() is triggered. - // If it has been loaded, OnAuthStateChanged() should be triggered recursively - // and synchronously when AddAuthStateListener() is called. - listener.WaitForEvent(); - RemoveAuthStateListener(&listener); + if (auth_data_->persistent_cache_load_pending.load( + std::memory_order_acquire)) { + // Add a listener and wait for the first trigger. + CurrentUserBlockListener listener; + AddAuthStateListener(&listener); + // If the persistent cache has not been loaded, this waits until loading + // finishes and OnAuthStateChanged() is triggered. + // If it finished racing with the check above, OnAuthStateChanged() is + // triggered synchronously inside AddAuthStateListener(). + listener.WaitForEvent(); + RemoveAuthStateListener(&listener); + } { MutexLock lock(auth_data_->future_impl.mutex()); diff --git a/auth/tests/desktop/auth_desktop_test.cc b/auth/tests/desktop/auth_desktop_test.cc index dbf69ec0d2..07b3e15c10 100644 --- a/auth/tests/desktop/auth_desktop_test.cc +++ b/auth/tests/desktop/auth_desktop_test.cc @@ -14,9 +14,12 @@ #include "auth/src/desktop/auth_desktop.h" +#include #include #include +#include #include +#include #include #include "app/rest/transport_builder.h" @@ -25,6 +28,7 @@ #include "app/src/function_registry.h" #include "app/src/include/firebase/app.h" #include "app/src/include/firebase/internal/mutex.h" +#include "app/src/semaphore.h" #include "app/tests/include/firebase/app_for_testing.h" #include "auth/src/desktop/sign_in_flow.h" #include "auth/src/desktop/user_desktop.h" @@ -278,6 +282,8 @@ class AuthDesktopTest : public ::testing::Test { return future; } + AuthData* auth_data() { return firebase_auth_->auth_data_; } + std::unique_ptr firebase_app_; std::unique_ptr firebase_auth_; @@ -317,6 +323,134 @@ TEST_F(AuthDesktopTest, DestroyingAuthUnregistersRegistryFunctions) { } } +// Regression test for https://github.com/firebase/firebase-cpp-sdk/issues/1972: +// Auth::SignOut() notifies AuthStateListeners while holding listeners_mutex. +// A listener (such as Firestore's credentials provider) may acquire its own +// mutex in OnAuthStateChanged(), while another thread holding that same mutex +// calls Auth::current_user(). Once persistent cache loading has completed, +// Auth::current_user() must not acquire listeners_mutex or it will deadlock. +TEST_F(AuthDesktopTest, SignOutDoesNotDeadlockWithConcurrentCurrentUser) { + ASSERT_FALSE(auth_data()->persistent_cache_load_pending.load( + std::memory_order_acquire)); + SetupAuthDataForPersist(auth_data()); + ASSERT_TRUE(firebase_auth_->current_user().is_valid()); + + struct DeadlockProbeListener : public AuthStateListener { + std::mutex external_mutex; + Semaphore listener_entered{0}; + std::atomic armed{false}; + std::atomic notifications{0}; + + void OnAuthStateChanged(Auth* /*auth*/) override { + if (!armed.load(std::memory_order_acquire)) { + return; + } + // Signal the worker thread that we are inside NotifyAuthStateListeners() + // (holding AuthData::listeners_mutex), then acquire external_mutex in the + // opposite lock order from the worker thread. + listener_entered.Post(); + std::lock_guard lock(external_mutex); + notifications.fetch_add(1, std::memory_order_relaxed); + } + }; + + DeadlockProbeListener probe; + firebase_auth_->AddAuthStateListener(&probe); + probe.armed.store(true, std::memory_order_release); + + id_token_listener.ExpectChanges(2); + auth_state_listener.ExpectChanges(2); + + Semaphore worker_holding_mutex{0}; + bool worker_saw_valid_user = true; + std::thread worker([&]() { + std::lock_guard lock(probe.external_mutex); + worker_holding_mutex.Post(); + // Wait until SignOut() is inside NotifyAuthStateListeners() holding + // listeners_mutex, then call current_user() while holding external_mutex. + probe.listener_entered.Wait(); + worker_saw_valid_user = firebase_auth_->current_user().is_valid(); + }); + + worker_holding_mutex.Wait(); + firebase_auth_->SignOut(); + worker.join(); + + firebase_auth_->RemoveAuthStateListener(&probe); + + EXPECT_EQ(probe.notifications.load(std::memory_order_relaxed), 1); + EXPECT_FALSE(worker_saw_valid_user); + EXPECT_FALSE(firebase_auth_->current_user().is_valid()); +} + +// Verifies FnAuthGetCurrentToken returns the persisted user's ID token even +// when called from another thread during LoadFinishTriggerListeners() -> +// NotifyAuthStateListeners(), after persistent_cache_load_pending is cleared +// and before NotifyIdTokenListeners() updates IdTokenRefreshListener. +TEST_F(AuthDesktopTest, + GetAuthTokenForRegistryReturnsPersistedTokenBeforeIdTokenListenersRun) { + ASSERT_FALSE(auth_data()->persistent_cache_load_pending.load( + std::memory_order_acquire)); + + // Populate UserView directly without triggering IdTokenListeners, then reset + // persistent_cache_load_pending to simulate startup right before + // LoadFinishTriggerListeners() runs. + SetupAuthDataForPersist(auth_data()); + { + MutexLock lock(auth_data()->listeners_mutex); + auth_data()->persistent_cache_load_pending.store(true, + std::memory_order_release); + } + + struct StartupTokenProbeListener : public AuthStateListener { + Semaphore auth_listener_entered{0}; + Semaphore token_read_done{0}; + std::atomic armed{false}; + + void OnAuthStateChanged(Auth* /*auth*/) override { + if (!armed.exchange(false, std::memory_order_acq_rel)) { + return; + } + // Persistent cache load flag is now false, but NotifyIdTokenListeners() + // has not run yet. Hold here until the worker reads the token. + auth_listener_entered.Post(); + token_read_done.Wait(); + } + }; + + StartupTokenProbeListener probe; + firebase_auth_->AddAuthStateListener(&probe); + probe.armed.store(true, std::memory_order_release); + + id_token_listener.ExpectChanges(3); + auth_state_listener.ExpectChanges(3); + + bool call_ok = false; + std::string observed_token; + std::thread worker([&]() { + probe.auth_listener_entered.Wait(); + call_ok = firebase_app_->function_registry()->CallFunction( + ::firebase::internal::FnAuthGetCurrentToken, firebase_app_.get(), + /*args=*/nullptr, &observed_token); + probe.token_read_done.Post(); + }); + + LoadFinishTriggerListeners(auth_data()); + worker.join(); + firebase_auth_->RemoveAuthStateListener(&probe); + + EXPECT_TRUE(call_ok); + EXPECT_EQ(observed_token, "persist_token"); + + // Also verify cleared token after SignOut(). + firebase_auth_->SignOut(); + std::string signed_out_token = "stale"; + EXPECT_TRUE(firebase_app_->function_registry()->CallFunction( + ::firebase::internal::FnAuthGetCurrentToken, firebase_app_.get(), + /*args=*/nullptr, &signed_out_token)); + EXPECT_TRUE(signed_out_token.empty()); +} + TEST_F(AuthDesktopTest, TestSignInWithProviderReturnsUnsupportedError) { FederatedOAuthProvider provider; Future future = firebase_auth_->SignInWithProvider(&provider); diff --git a/release_build_files/readme.md b/release_build_files/readme.md index ed6b0fdaa5..569a55c52a 100644 --- a/release_build_files/readme.md +++ b/release_build_files/readme.md @@ -615,6 +615,9 @@ code. ## Release Notes ### Upcoming - Changes + - Auth (Desktop): Fixed a deadlock when `Auth::SignOut()` (or other auth + state notifications) runs concurrently with another thread calling + `Auth::current_user()`, such as Firestore token requests. - Remote Config: Fixed `ConfigInfo::throttled_end_time` being left uninitialized in `RemoteConfig::EnsureInitialized()` on Android, added default member initializers to `ConfigInfo`, captured throttle end times