Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions auth/src/auth.cc
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#include <assert.h>

#include <algorithm>
#include <atomic>
#include <cstdint>
#include <map>
#include <string>
Expand Down Expand Up @@ -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);
}
}
Expand All @@ -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_);
Expand Down Expand Up @@ -323,7 +326,8 @@ static inline bool VectorContains(const T& entry, const std::vector<T>& 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 */ \
Expand Down
9 changes: 6 additions & 3 deletions auth/src/data.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#ifndef FIREBASE_AUTH_SRC_DATA_H_
#define FIREBASE_AUTH_SRC_DATA_H_

#include <atomic>
#include <string>

#include "app/src/include/firebase/internal/mutex.h"
Expand Down Expand Up @@ -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.
Expand All @@ -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<bool> persistent_cache_load_pending;

// Mutex protecting `expect_id_token_listener_callback`
Mutex expect_id_token_mutex;
Expand Down
33 changes: 20 additions & 13 deletions auth/src/desktop/auth_desktop.cc
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#include "auth/src/desktop/auth_desktop.h"

#include <algorithm>
#include <atomic>
#include <cassert>
#include <cstdint>
#include <cstring>
Expand Down Expand Up @@ -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<std::string*>(out);
MutexLock lock(auth->auth_data_->token_listener_mutex);
auto auth_impl = static_cast<AuthImpl*>(auth->auth_data_->auth_impl);
*result = auth_impl->token_refresh_thread.CurrentAuthToken();
if (out) {
auto result = static_cast<std::string*>(out);
result->clear();
UserView::TryRead(auth->auth_data_, [&](const UserView::Reader& user) {
*result = user->id_token;
});
}
return true;
}
return false;
Expand Down Expand Up @@ -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());
Expand Down
134 changes: 134 additions & 0 deletions auth/tests/desktop/auth_desktop_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,12 @@

#include "auth/src/desktop/auth_desktop.h"

#include <atomic>
#include <cstddef>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <utility>

#include "app/rest/transport_builder.h"
Expand All @@ -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"
Expand Down Expand Up @@ -278,6 +282,8 @@ class AuthDesktopTest : public ::testing::Test {
return future;
}

AuthData* auth_data() { return firebase_auth_->auth_data_; }

std::unique_ptr<App> firebase_app_;
std::unique_ptr<Auth> firebase_auth_;

Expand Down Expand Up @@ -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<bool> armed{false};
std::atomic<int> 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<std::mutex> 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<std::mutex> 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<bool> 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<AuthResult> future = firebase_auth_->SignInWithProvider(&provider);
Expand Down
3 changes: 3 additions & 0 deletions release_build_files/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading