Repository navigation
fix(auth): read User.metadata and multiFactor under propertyAccessQueue - #16976
Conversation
#15951 moved most User properties behind propertyAccessQueue but left metadata and multiFactor as plain stored properties. update(withGetAccountInfoResponse:) replaces both on reload, link, and profile updates, so a reader on another thread could load the old object just as the writer released it. The multiFactor write wasn't on the queue at all, so it also raced with the queue-held read in encode(with:), which runs when the user is saved to the keychain. Read both through the queue from private backing storage, and write the storage inside the existing sync block. encode(with:) and the initializers use the storage directly, since they already hold the queue or run before the user is shared. The public declarations don't change; the generated Objective-C header is identical. Add UserPropertyThreadSafetyTests, which Thread Sanitizer flags on main and which pass with this change. Fixes #16975
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. |
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request addresses a data race in User properties (metadata and multiFactor) by backing them with private variables and synchronizing access via propertyAccessQueue. It also adds thread-safety unit tests. The review feedback highlights two issues: first, in init(coder:), _multiFactor.user should be set directly instead of using the optional multiFactor to avoid a potential crash; second, in update(withGetAccountInfoResponse:), _multiFactor should be updated even when user.mfaEnrollments is nil to properly handle unenrollment.
Address review feedback on two ways the Swift port's multiFactor handling differed from the Objective-C SDK: - update(withGetAccountInfoResponse:) kept the previous MultiFactor when the response had no mfaInfo, so factors unenrolled on another device stayed listed after a reload. Always rebuild it, and treat a missing mfaInfo as no enrolled factors. The new object also gets its user before any reader can see it. - init?(coder:) set user only on the decoded MultiFactor, not on the MultiFactor() fallback for an archive without one, such as a macOS user saved before 12.2.0. Enrolling or unenrolling a factor then hit fatalError. Set it on the stored value. Add a UserTests case for each; both fail without this change.
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request addresses thread-safety issues and bugs in User properties within FirebaseAuth. Specifically, it resolves a data race by synchronizing access to metadata and multiFactor using propertyAccessQueue.sync, ensures enrolled factors are cleared when MFA info is missing, and prevents crashes on macOS when decoding older user data. New unit and thread-safety tests are also added. The review feedback correctly identifies that _multiFactor.user is not set to self in init(withTokenService:backend:), which could lead to a crash if accessed before an update.
Address review feedback: init(withTokenService:backend:) created a MultiFactor without setting its user, which stayed nil until the first update(withGetAccountInfoResponse:). retrieveUser, the only production caller, always refreshes the user before returning it, so this wasn't reachable. Call super.init() explicitly and set the user, as init?(coder:) does, so the link holds from construction on. Add testInitLinksMultiFactorToUser, which fails without this change.
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request addresses several issues in FirebaseAuth related to thread safety and multi-factor authentication (MFA). Specifically, it resolves a data race by synchronizing access to User.metadata and User.multiFactor using propertyAccessQueue. It also ensures that User.multiFactor is correctly cleared when a reload response contains no MFA enrollments, and fixes a crash on macOS for users saved by older versions by ensuring the MultiFactor object is properly linked back to the User instance. Additionally, comprehensive unit and thread-safety tests have been added. The reviewer suggested calling super.init() unconditionally in the initializer to ensure consistency and explicit initialization across all platforms.
…er:) Address review feedback: init?(coder:) called super.init() only inside the iOS and macOS block, and relied on the compiler to insert it on other platforms. Call it unconditionally, as init(withTokenService:backend:) now does, so both initializers have the same shape. Behavior doesn't change.
Fixes #16975
Problem
#15951 moved most
Userproperties behindpropertyAccessQueue, butmetadataand
multiFactorstayed plain stored properties.update(withGetAccountInfoResponse:)replaces both on reload, link, and profile,email, password, and phone updates, from the
UserProfileUpdateactor. A readeron another thread, such as
currentUser?.metadataon the main thread, can loadthe old object just as the writer releases it, and then retain freed memory.
multiFactorwas worse. Its write happened after thesyncblock, so it alsoraced with the SDK's own queue-held read in
encode(with:), which runs wheneverthe user is saved to the keychain.
The race isn't a regression. Both declarations, and the "This class is
thread-safe." doc comment, are unchanged since 11.0.0.
Fix
metadataandmultiFactorare now get-only computed properties that readprivate backing storage under
propertyAccessQueue, the same pattern asuidand
email.update(withGetAccountInfoResponse:)writes_metadataand_multiFactorinside its existing
syncblock. ThemultiFactorwrite moves into it.encode(with:)and the initializers use the backing storage directly.encode(with:)already holds the queue, so reading through the getter therewould
dispatch_synconto a queue the thread already owns.I chose get-only over a guarded
private(set)setter, likeisAnonymoushas,because every write either already holds the queue or runs during init. A setter
would have no safe caller, and without one the compiler rejects a write through
the property inside the queue.
Review follow-ups (cee242c, 0f85423)
Code review turned up places where the Swift port's
multiFactorhandlingdiffered from the Objective-C SDK or left
MultiFactor.userunset:update(withGetAccountInfoResponse:)now always rebuildsmultiFactor, andtreats a missing
mfaInfoas no enrolled factors. Before, factors unenrolledon another device stayed listed after a reload, a regression in 11.0.0.
init?(coder:)now setsuseron the storedMultiFactor, including thefallback for an archive without one, such as a macOS user saved before 12.2.0.
Before,
enrollandunenrollhitfatalErrorfor those users.init(withTokenService:backend:)now setsusertoo, so the link holds fromconstruction instead of from the first refresh. This wasn't reachable in
production, because
retrieveUserrefreshes the user before returning it.API changes
None. Both properties were already read-only to clients, and the generated
FirebaseAuth-Swift.his byte-identical before and after:infra.api_diffcompares Jazzy's declaration text, so it may still list thesetwo properties.
Testing
New
FirebaseAuth/Tests/Unit/UserPropertyThreadSafetyTests.swiftin AuthUnit:testConcurrentMetadataReadDuringUpdatereadsmetadataon several threadswhile
update(withGetAccountInfoResponse:)replaces it.testConcurrentMultiFactorReadDuringUpdatedoes the same formultiFactor.testConcurrentArchiveDuringUpdatearchives the user, asAuthdoes for thekeychain, while
update(withGetAccountInfoResponse:)runs.New
UserTestscases for the review follow-ups. Each fails without its fix:testUpdateWithoutMFAInfoClearsEnrolledFactorstestDecodingWithoutMultiFactorLinksMultiFactorToUsertestInitLinksMultiFactorToUserResults with Thread Sanitizer (
xcodebuild test -scheme AuthUnit -enableThreadSanitizer YES, iPhone 17 Pro simulator, iOS 26.5, Xcode 26.5):mainUser.metadata, andUser.multiFactortwiceUserUser, no assertion failures (413 tests, all commits)Both full-suite runs also show 10 to 11 reports in the test-only
FakeBackendRPCIssuer.asyncCallToURL, from its own unsynchronized writes tocontentType,request, andrequestURL. They're timing-dependent andunrelated to this change.
Without Thread Sanitizer, these tests won't reliably fail on
main, the sameas
testConcurrentProviderDataReadWrite. The race window is a few instructionswide, and the reporter saw no crash in about 1.9 billion reads. The issue
suggested
SwiftApiTests/UserThreadSafetyTests.swift, but that target needssecrets. These tests live in AuthUnit instead, so they run on every PR,
including PRs from forks.
Not in this PR
User.tokenServicehas the same pattern. It's replaced from theUserProfileUpdateactor and read fromrefreshTokenunderkAuthGlobalWorkQueue, frominternalGetTokenAsync, and fromencode(with:)under
propertyAccessQueue. It's worth a separate issue.