Repository navigation
fix(messaging): synchronize FIRMessagingAuthKeychain cache access with a private lock - #17160
leojaygoogle wants to merge 5 commits into
Conversation
Using Gemini Code AssistThe 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
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 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.
|
/gemini review |
There was a problem hiding this comment.
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.
| - (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]; | ||
| } |
There was a problem hiding this comment.
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];
}There was a problem hiding this comment.
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.
| - (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]; |
There was a problem hiding this comment.
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];There was a problem hiding this comment.
I'd like to limit the scope of the PR strictly to cache access synchronization.
| - (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; | ||
| } |
There was a problem hiding this comment.
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.
| - (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; | |
| } |
There was a problem hiding this comment.
I'd like to limit the scope of the PR strictly to cache access synchronization.
There was a problem hiding this comment.
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
_cachedKeychainDatais now inside@synchronized(_cacheLock). - There's no deadlock risk. While holding the lock, the code only calls
FIRMessagingKeychain, whose serial-queue blocks never take_cacheLockand send handlers to the main queue withdispatch_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_syncon 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
_cachedKeychainDatawrite inremoveItemsMatchingService:. - 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. testWildcardQueryBypassesCachepasses either way, as expected.
- Under TSan, the concurrency test reports a data race on the
- 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 exampleremoveAllTokensWithHandler:racingsaveTokenInfo:. 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/accountchecks. That behavior predates this PR, and the parameters are nonnull on an internal class.
| if (handler) { | ||
| handler(error); | ||
| @synchronized(_cacheLock) { | ||
| [self removeItemsMatchingService:service |
There was a problem hiding this comment.
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]; | ||
| } |
There was a problem hiding this comment.
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.
| } | |
| } else if (handler) { | |
| handler(nil); | |
| } |
| if (data.length == 0) { | ||
| return; | ||
| } |
There was a problem hiding this comment.
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.
FIRMessagingAuthKeychaincaches FCM tokens and checkin data in anNSMutableDictionary. 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
nildata tosetData:orsetCacheData:no longer crashes.The new
FIRMessagingAuthKeychainCacheTestcovers concurrent access, both races, andnilor 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.