Skip to content

Commit 956b072

Browse files
authored
Fix race condition with App Check callback (#984)
* Fix race condition with App Check callback * Update app_check.i * Update readme.md
1 parent 38b67d2 commit 956b072

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

app_check/src/swig/app_check.i

+20-4
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ typedef void (SWIGSTDCALL *CompleteBuiltInGetToken)(int key, AppCheckToken* toke
4848
static GetTokenFromCSharp g_get_token_from_csharp = nullptr;
4949
static int g_pending_token_keys = 0;
5050
static std::map<int, std::function<void(AppCheckToken, int, const std::string&)>> g_pending_get_tokens;
51+
static ::firebase::Mutex g_pending_get_tokens_mutex;
5152

5253
// Should be set to the C# function FirebaseAppCheck.TokenChangedMethod
5354
static TokenChanged g_token_changed = nullptr;
@@ -59,8 +60,19 @@ static CompleteBuiltInGetToken g_complete_built_in_get_token = nullptr;
5960
void FinishGetTokenCallback(int key, const char* token, int64_t expire_ms,
6061
int error_code, const char* error_message) {
6162
// Get the function from the map, and erase it
62-
auto callback = g_pending_get_tokens[key];
63-
g_pending_get_tokens.erase(key);
63+
std::function<void(AppCheckToken, int, const std::string&)> callback;
64+
{
65+
MutexLock lock(g_pending_get_tokens_mutex);
66+
auto it = g_pending_get_tokens.find(key);
67+
if (it != g_pending_get_tokens.end()) {
68+
callback = it->second;
69+
g_pending_get_tokens.erase(it);
70+
} else {
71+
// The callback was missing. This is likely caused by trying to finish the same
72+
// callback multiple times, so ignore it.
73+
return;
74+
}
75+
}
6476

6577
AppCheckToken app_check_token;
6678
app_check_token.token = token;
@@ -98,8 +110,12 @@ class SwigAppCheckProvider : public AppCheckProvider {
98110
completion_callback) override {
99111
if (g_get_token_from_csharp) {
100112
// Save the callback in the map, and generate a key
101-
int key = g_pending_token_keys++;
102-
g_pending_get_tokens[key] = completion_callback;
113+
int key;
114+
{
115+
MutexLock lock(g_pending_get_tokens_mutex);
116+
key = g_pending_token_keys++;
117+
g_pending_get_tokens[key] = completion_callback;
118+
}
103119
// Queue a call to the C# function that will generate the token.
104120
firebase::callback::AddCallback(
105121
new firebase::callback::CallbackValue1String1<int>(

docs/readme.md

+5
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,11 @@ Support
7171

7272
Release Notes
7373
-------------
74+
### Upcoming
75+
- Changes
76+
- App Check: Fix potential crash when fetching a token.
77+
([#877](https://github.com/firebase/firebase-unity-sdk/issues/877))
78+
7479
### 11.8.1
7580
- Changes
7681
- Firestore (iOS): Fix undefined absl symbols error.

0 commit comments

Comments
 (0)