Skip to content

fix(messaging): synchronize FIRMessagingAuthKeychain cache access with a private lock - #17160

Open
leojaygoogle wants to merge 5 commits into
mainfrom
fix/messaging-keychain-cache-lock
Open

leojaygoogle wants to merge 5 commits into
mainfrom
fix/messaging-keychain-cache-lock

Conversation

@leojaygoogle

@leojaygoogle leojaygoogle commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

FIRMessagingAuthKeychain caches FCM tokens and checkin data in an NSMutableDictionary. Multiple threads read and write that dictionary without synchronization, which can crash the app.

This PR guards the cache with a private lock. The lock also stops readers from seeing an empty value partway through an overwrite, and from caching a token that was just deleted. In addition, passing nil data to setData: or setCacheData: no longer crashes.

The new FIRMessagingAuthKeychainCacheTest covers concurrent access, both races, and nil or empty data. Without the fix, it crashes under Thread Sanitizer. With the fix, it passes.

Trade-off: on a cache miss, the lock stays held while the keychain is read. Other cache reads and writes on the same instance wait for that read, possibly on the main thread. Holding the lock is what stops a stale read from refilling the cache after a delete. Misses happen only on first access and after wildcard removes, so the wait should be rare.

@gemini-code-assist

Copy link
Copy Markdown
Contributor
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Check nil and empty data against an existing cached value, cover removal with a wildcard account, and fail if the concurrent reader never starts.
@leojaygoogle

Copy link
Copy Markdown
Contributor Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request synchronizes in-memory keychain cache access in FIRMessagingAuthKeychain using a lock to prevent crashes from concurrent reads and writes, and adds comprehensive unit tests to verify thread safety and cache behaviors. The review feedback recommends adding defensive checks for nil or empty service and account strings across several methods to prevent potential crashes when accessing NSMutableDictionary with invalid keys.

Comment on lines +129 to +134
- (NSArray<NSData *> *)itemsMatchingService:(NSString *)service account:(NSString *)account {
// If querying wildcard service or account, bypass the cache and always query from keychain.
if ([service isEqualToString:kFIRMessagingKeychainWildcardIdentifier] ||
[account isEqualToString:kFIRMessagingKeychainWildcardIdentifier]) {
// Do not update cache if it's wildcard query.
return [results copy];
} else if (_cachedKeychainData[service]) {
[_cachedKeychainData[service] setObject:[results copy] forKey:account];
} else {
NSMutableDictionary *entry = [@{account : [results copy]} mutableCopy];
[_cachedKeychainData setObject:entry forKey:service];
return [self queryKeychainForService:service account:account];
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

In Objective-C, passing nil as a key to an NSMutableDictionary (such as _cachedKeychainData[service][account]) will throw an NSInvalidArgumentException and crash the app. Adding a defensive check for service.length == 0 || account.length == 0 ensures that both nil and empty strings are handled gracefully before any dictionary access.

- (NSArray<NSData *> *)itemsMatchingService:(NSString *)service account:(NSString *)account {
  if (service.length == 0 || account.length == 0) {
    return @[];
  }
  // If querying wildcard service or account, bypass the cache and always query from keychain.
  if ([service isEqualToString:kFIRMessagingKeychainWildcardIdentifier] ||
      [account isEqualToString:kFIRMessagingKeychainWildcardIdentifier]) {
    return [self queryKeychainForService:service account:account];
  }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This behavior predates the PR. I'd like to limit the scope of the PR strictly to cache access synchronization.

Also, FIRMessagingAuthKeychain is not exposed to SDK users. Internally, neither the service nor the account can be nil.

Comment on lines 156 to +159
- (void)removeItemsMatchingService:(NSString *)service
account:(NSString *)account
handler:(void (^)(NSError *error))handler {
if ([service isEqualToString:kFIRMessagingKeychainWildcardIdentifier]) {
// Delete all keychain items.
_cachedKeychainData = [[NSMutableDictionary alloc] init];
} else if ([account isEqualToString:kFIRMessagingKeychainWildcardIdentifier]) {
// Delete all entries under service,
if (_cachedKeychainData[service]) {
_cachedKeychainData[service] = [[NSMutableDictionary alloc] init];
NSMutableDictionary *keychainQuery = [self keychainQueryForService:service account:account];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

To prevent potential crashes when service or account is nil or empty, we should add a defensive check at the beginning of removeItemsMatchingService:account:handler:. This ensures that any invalid inputs are handled gracefully by invoking the handler with a bad arguments error.

- (void)removeItemsMatchingService:(NSString *)service
                           account:(NSString *)account
                           handler:(void (^)(NSError *error))handler {
  if (service.length == 0 || account.length == 0) {
    if (handler) {
      handler([NSError errorWithDomain:kFIRMessagingKeychainErrorDomain
                                  code:kFIRMessagingKeychainErrorBadArguments
                              userInfo:nil]);
    }
    return;
  }
  NSMutableDictionary *keychainQuery = [self keychainQueryForService:service account:account];

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to limit the scope of the PR strictly to cache access synchronization.

Comment on lines 222 to +225
- (void)setCacheData:(NSData *)data forService:(NSString *)service account:(NSString *)account {
if (_cachedKeychainData[service]) {
if (_cachedKeychainData[service][account]) {
_cachedKeychainData[service][account] = @[ data ];
} else {
[_cachedKeychainData[service] setObject:@[ data ] forKey:account];
}
} else {
[_cachedKeychainData setObject:[@{account : @[ data ]} mutableCopy] forKey:service];
if (data.length == 0) {
return;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

To prevent potential crashes when service or account is nil or empty, we should add a defensive check at the beginning of setCacheData:forService:account: before accessing the cache dictionary.

Suggested change
- (void)setCacheData:(NSData *)data forService:(NSString *)service account:(NSString *)account {
if (_cachedKeychainData[service]) {
if (_cachedKeychainData[service][account]) {
_cachedKeychainData[service][account] = @[ data ];
} else {
[_cachedKeychainData[service] setObject:@[ data ] forKey:account];
}
} else {
[_cachedKeychainData setObject:[@{account : @[ data ]} mutableCopy] forKey:service];
if (data.length == 0) {
return;
}
- (void)setCacheData:(NSData *)data forService:(NSString *)service account:(NSString *)account {
if (service.length == 0 || account.length == 0) {
return;
}
if (data.length == 0) {
return;
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to limit the scope of the PR strictly to cache access synchronization.

@leojaygoogle
leojaygoogle marked this pull request as ready for review November 30, 2026 18:37

@paulb777 paulb777 left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this looks good to me. The locking is correct, and everything below is a nit or an FYI. None of it blocks merging.

Why I think the locking holds

  • Every production read and write of _cachedKeychainData is now inside @synchronized(_cacheLock).
  • There's no deadlock risk. While holding the lock, the code only calls FIRMessagingKeychain, whose serial-queue blocks never take _cacheLock and send handlers to the main queue with dispatch_async. So the lock order is always _cacheLock, then the keychain queue.
  • Wildcard removes queue their delete before releasing the lock, and a later cache miss takes the lock before its dispatch_sync on the same serial queue. So the read runs after the delete.

Local testing (Xcode 27.2, iPhone 17 Simulator on iOS 27.2, SPM MessagingUnit scheme, only FIRMessagingAuthKeychainCacheTest)

  • With the fix, all 6 tests pass, with Thread Sanitizer (halt_on_error=1) and without it, 25 iterations each. No TSan reports, and no new warnings in the changed files.
  • With the PR's tests against the base FIRMessagingAuthKeychain.m, 5 of 6 fail:
    • Under TSan, the concurrency test reports a data race on the _cachedKeychainData write in removeItemsMatchingService:.
    • Without TSan, which is how CI runs MessagingUnit, the concurrency test still crashed the test process in 6 of 6 runs, and both ordering tests failed in 20 of 20 iterations.
    • The nil-data tests throw NSInvalidArgumentException.
    • testWildcardQueryBypassesCache passes either way, as expected.
  • So the tests catch a regression in CI even without TSan.

Notes that don't belong on a single line

  • Known limitation, out of scope: setData: writes the keychain in two steps, delete then add from the delete's main-queue callback. A wildcard remove can land between them, for example removeAllTokensWithHandler: racing saveTokenInfo:. Then the new item stays in the keychain after the remove, and the next cache miss reads it back. The cache lock can't cover that. A line in the description would keep "caching a token that was just deleted" from being read as covering this case too.
  • Trade-off: I agree that holding the lock during the keychain read is the simplest correct design. If main-thread waits ever show up, a generation counter gives the same guarantee without holding the lock during the read: wildcard removes increment it, and a miss only stores its result if it hasn't changed. Not needed here.
  • Gemini's suggestions: I agree with declining the nil service/account checks. That behavior predates this PR, and the parameters are nonnull on an internal class.

if (handler) {
handler(error);
@synchronized(_cacheLock) {
[self removeItemsMatchingService:service

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this takes _cacheLock again inside removeItemsMatchingService:account:handler:, which works only because @synchronized is recursive. A later switch to os_unfair_lock or NSLock would deadlock here. Maybe add a one-line comment, or move the body of the remove into a -removeItemsLockedMatchingService:account:handler: helper (like setCacheValueLocked:) and call it from both places?

[[FIRMessagingKeychain sharedInstance]
addItemWithQuery:keychainQuery
handler:handler];
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (existing behavior): with nil or empty data, nothing is added and handler is never called on success. The PR now makes nil safe and tests it as "clear the entry", but a caller waiting on the completion would wait forever. This callback already runs on the main queue, where the add path also delivers handler, so calling it here keeps the same calling context. No production caller passes nil or empty data, so a follow-up is fine.

Suggested change
}
} else if (handler) {
handler(nil);
}

Comment on lines +223 to +225
if (data.length == 0) {
return;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: for empty data, setData: now leaves an empty entry (@[], which matches the keychain), but this keeps the previous cached value. Before this PR, both cached @[emptyData]. Either is fine, and there's no user impact (saveTokenInfoInCache: returns early when archiving fails). Still, a one-line comment on why this ignores empty data would help, and the PR description could mention the change.

@paulb777 paulb777 added this to the 13.3.0 - M190 milestone Nov 30, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants