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
101 changes: 43 additions & 58 deletions firestore/src/main/credentials_provider_desktop.cc
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,14 @@

#include "firestore/src/main/credentials_provider_desktop.h"

#include <memory>
#include <string>
#include <utility>

#include "Firestore/core/src/util/status.h"
#include "app/src/function_registry.h"
#include "app/src/reference_counted_future_impl.h"
#include "firebase/auth/types.h"
#include "firebase/firestore/firestore_errors.h"
#include "firestore/src/common/futures.h"
#include "firestore/src/common/hard_assert_common.h"

namespace firebase {
Expand Down Expand Up @@ -70,8 +69,8 @@ Error FirestoreErrorFromAuthError(int error) {

/**
* Returns a Future that, when completed, will contain the token for the
* current user or an error. An empty token means that the current user is
* unauthenticated.
* current user or an error, or an invalid Future (`kFutureStatusInvalid`) if
* Auth is unavailable or no user is currently signed in.
*/
Future<std::string> GetAuthTokenAsync(App& app, bool force_refresh) {
Future<std::string> result;
Expand All @@ -83,11 +82,9 @@ Future<std::string> GetAuthTokenAsync(App& app, bool force_refresh) {
return result;
}

// If CallFunction does not succeed, it's because either Auth has not
// registered implementations for the FunctionId we're using or because there
// isn't an Auth instance for this App. In either case this means Auth is
// unavailable and we should treat the current user as unauthenticated.
return SuccessfulFuture<std::string>("");
// If CallFunction does not succeed, Auth is either unavailable for this App
// or no user is currently signed in.
return Future<std::string>();
}

User GetCurrentUser(App& app) {
Expand All @@ -96,8 +93,9 @@ User GetCurrentUser(App& app) {
::firebase::internal::FnAuthGetCurrentUserUid, &app, /* args= */ nullptr,
&uid);

// If Auth is unavailable, treat the user as unauthenticated.
if (!success) return {};
// If Auth is unavailable or no user is signed in (including if sign-out
// raced with reading the UID), treat the user as unauthenticated.
if (!success || uid.empty()) return {};

return User(uid);
}
Expand All @@ -112,7 +110,11 @@ StatusOr<AuthToken> ConvertToken(const Future<std::string>& future, App& app) {
std::to_string(future.error()) + ")");
}

return AuthToken(*future.result(), GetCurrentUser(app));
User user = GetCurrentUser(app);
if (!user.is_authenticated()) {
return AuthToken::Unauthenticated();
}
return AuthToken(*future.result(), std::move(user));
}

// Converts the result of the given future into an
Expand Down Expand Up @@ -181,11 +183,37 @@ void FirebaseCppCredentialsProvider::GetToken(
TokenListener<AuthToken> listener) {
std::lock_guard<std::recursive_mutex> lock(contents_->mutex);

if (IsSignedIn()) {
RequestToken(std::move(listener));
} else {
// Take note of the current value of `token_generation` so that this request
// can fail if there is a token change while the request is outstanding.
int expected_generation = contents_->token_generation;

bool force_refresh = force_refresh_.exchange(false);
Future<std::string> future = GetAuthTokenAsync(contents_->app, force_refresh);
if (future.status() == kFutureStatusInvalid) {
listener(AuthToken::Unauthenticated());
return;
}

std::weak_ptr<Contents> weak_contents(contents_);

// Note: if the future happens to be already completed (either because the
// token was readily available, or theoretically because the Auth token
// request finished so quickly), this completion will be invoked
// synchronously. Because the mutex is recursive, it's okay to lock it again
// in that case.
future.OnCompletion([listener = std::move(listener), expected_generation,
weak_contents](const Future<std::string>& future_token) {
auto contents = weak_contents.lock();
// Auth may invoke the callback when credentials provider has already
// been destroyed.
if (!contents) {
return;
}

std::lock_guard<std::recursive_mutex> lock(contents->mutex);
OnToken(future_token, contents->app, contents->token_generation, listener,
expected_generation);
});
}

void FirebaseCppCredentialsProvider::AddAuthStateListener() {
Expand Down Expand Up @@ -218,48 +246,5 @@ void FirebaseCppCredentialsProvider::OnAuthStateChanged(void* context) {
}
}

// Private member functions

void FirebaseCppCredentialsProvider::RequestToken(
TokenListener<AuthToken> listener) {
SIMPLE_HARD_ASSERT(IsSignedIn(),
"Cannot get token when there is no signed-in user");

// Take note of the current value of `token_generation` so that this request
// can fail if there is a token change while the request is outstanding.
int expected_generation = contents_->token_generation;

bool force_refresh = force_refresh_;
force_refresh_ = false;
auto future = GetAuthTokenAsync(contents_->app, force_refresh);

std::weak_ptr<Contents> weak_contents(contents_);

// Note: if the future happens to be already completed (either because the
// token was readily available, or theoretically because the Auth token
// request finished so quickly), this completion will be invoked
// synchronously. Because the mutex is recursive, it's okay to lock it again
// in that case.
future.OnCompletion(
// TODO(c++14): move `listener` into the lambda.
[listener, expected_generation,
weak_contents](const Future<std::string>& future_token) {
auto contents = weak_contents.lock();
// Auth may invoke the callback when credentials provider has already
// been destroyed.
if (!contents) {
return;
}

std::lock_guard<std::recursive_mutex> lock(contents->mutex);
OnToken(future_token, contents->app, contents->token_generation,
std::move(listener), expected_generation);
});
}

bool FirebaseCppCredentialsProvider::IsSignedIn() const {
return GetCurrentUser(contents_->app).is_authenticated();
}

} // namespace firestore
} // namespace firebase
24 changes: 7 additions & 17 deletions firestore/src/main/credentials_provider_desktop.h
Original file line number Diff line number Diff line change
Expand Up @@ -68,16 +68,6 @@ class FirebaseCppCredentialsProvider
// interface.
static void OnAuthStateChanged(void* context);

// Requests an auth token for the currently signed-in user asynchronously; the
// given `listener` will eventually be invoked with the token (or an error).
// If there is no signed-in user, immediately invokes the `listener` with
// `AuthToken::Unauthenticated()`.
void RequestToken(
firestore::credentials::TokenListener<firestore::credentials::AuthToken>
listener);

bool IsSignedIn() const;

// Wraps the data that is used by `auth::User::GetToken` callback. This
// credentials provider holds a shared pointer to `Contents`, while the
// `GetToken` callback stores a weak pointer. This makes safe the case where
Expand All @@ -87,13 +77,13 @@ class FirebaseCppCredentialsProvider
explicit Contents(App& app) : app(app) {}

// FirebaseCppCredentialsProvider may be used by more than one thread. The
// mutex is locked in all public member functions and none of the private
// member functions (with the exception of `RequestToken` that locks the
// mutex in a lambda that gets involved asynchronously later). Therefore,
// the invariant is that when a private member function is involved, the
// mutex is always already locked. The mutex is recursive to avoid one
// potential case of deadlock (attaching a continuation to a `Future` which
// may be invoked immediately or asynchronously).
// mutex guards `change_listener_` and `token_generation` in
// `SetCredentialChangeListener`, `GetToken`, `GetToken`'s completion
// callback, and `OnAuthStateChanged` (`AddAuthStateListener` and
// `RemoveAuthStateListener` do not acquire the mutex themselves). The mutex
// is recursive to avoid one potential case of deadlock (attaching a
// continuation to a `Future` which may be invoked immediately or
// asynchronously).
//
// TODO(b/148688333): make sure not to hold the mutex while calling methods
// on `app`.
Expand Down
2 changes: 2 additions & 0 deletions release_build_files/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,8 @@ code.
- Database (Desktop): Fixed cached objects with priorities set (via
`SetPriority()` or `SetValueAndPriority()`) being read back from the
offline persistence cache as corrupted or null values.
- Firestore (Desktop): Fixed an assertion abort when `Auth::SignOut()`
races a Firestore token request.

### 14.2.0
- Changes
Expand Down
Loading