Skip to content

fix(auth): read User.metadata and multiFactor under propertyAccessQueue - #16976

Merged
paulb777 merged 4 commits into
mainfrom
pb-auth-user-metadata-race-16975
Oct 30, 2026
Merged

paulb777 merged 4 commits into
mainfrom
pb-auth-user-metadata-race-16975

Conversation

@paulb777

@paulb777 paulb777 commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

Fixes #16975

Problem

#15951 moved most User properties behind propertyAccessQueue, but metadata
and multiFactor stayed plain stored properties.
update(withGetAccountInfoResponse:) replaces both on reload, link, and profile,
email, password, and phone updates, from the UserProfileUpdate actor. A reader
on another thread, such as currentUser?.metadata on the main thread, can load
the old object just as the writer releases it, and then retain freed memory.

multiFactor was worse. Its write happened after the sync block, so it also
raced with the SDK's own queue-held read in encode(with:), which runs whenever
the 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

  • metadata and multiFactor are now get-only computed properties that read
    private backing storage under propertyAccessQueue, the same pattern as uid
    and email.
  • update(withGetAccountInfoResponse:) writes _metadata and _multiFactor
    inside its existing sync block. The multiFactor write moves into it.
  • encode(with:) and the initializers use the backing storage directly.
    encode(with:) already holds the queue, so reading through the getter there
    would dispatch_sync onto a queue the thread already owns.

I chose get-only over a guarded private(set) setter, like isAnonymous has,
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 multiFactor handling
differed from the Objective-C SDK or left MultiFactor.user unset:

  • update(withGetAccountInfoResponse:) now always rebuilds multiFactor, and
    treats a missing mfaInfo as no enrolled factors. Before, factors unenrolled
    on another device stayed listed after a reload, a regression in 11.0.0.
  • init?(coder:) now sets user on the stored MultiFactor, including the
    fallback for an archive without one, such as a macOS user saved before 12.2.0.
    Before, enroll and unenroll hit fatalError for those users.
  • init(withTokenService:backend:) now sets user too, so the link holds from
    construction instead of from the first refresh. This wasn't reachable in
    production, because retrieveUser refreshes the user before returning it.

API changes

None. Both properties were already read-only to clients, and the generated
FirebaseAuth-Swift.h is byte-identical before and after:

@property (nonatomic, readonly, strong) FIRUserMetadata * _Nonnull metadata;
@property (nonatomic, readonly, strong) FIRMultiFactor * _Nonnull multiFactor;

infra.api_diff compares Jazzy's declaration text, so it may still list these
two properties.

Testing

New FirebaseAuth/Tests/Unit/UserPropertyThreadSafetyTests.swift in AuthUnit:

  • testConcurrentMetadataReadDuringUpdate reads metadata on several threads
    while update(withGetAccountInfoResponse:) replaces it.
  • testConcurrentMultiFactorReadDuringUpdate does the same for multiFactor.
  • testConcurrentArchiveDuringUpdate archives the user, as Auth does for the
    keychain, while update(withGetAccountInfoResponse:) runs.

New UserTests cases for the review follow-ups. Each fails without its fix:

  • testUpdateWithoutMFAInfoClearsEnrolledFactors
  • testDecodingWithoutMultiFactorLinksMultiFactorToUser
  • testInitLinksMultiFactorToUser

Results with Thread Sanitizer (xcodebuild test -scheme AuthUnit -enableThreadSanitizer YES, iPhone 17 Pro simulator, iOS 26.5, Xcode 26.5):

main This PR
New thread-safety tests All 3 flagged: User.metadata, and User.multiFactor twice All 3 pass with no reports
Full AuthUnit 3 races in User No races in User, 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 to
contentType, request, and requestURL. They're timing-dependent and
unrelated to this change.

Without Thread Sanitizer, these tests won't reliably fail on main, the same
as testConcurrentProviderDataReadWrite. The race window is a few instructions
wide, and the reporter saw no crash in about 1.9 billion reads. The issue
suggested SwiftApiTests/UserThreadSafetyTests.swift, but that target needs
secrets. These tests live in AuthUnit instead, so they run on every PR,
including PRs from forks.

Not in this PR

User.tokenService has the same pattern. It's replaced from the
UserProfileUpdate actor and read from refreshToken under
kAuthGlobalWorkQueue, from internalGetTokenAsync, and from encode(with:)
under propertyAccessQueue. It's worth a separate issue.

#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
@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.

@paulb777

Copy link
Copy Markdown
Member 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 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.
@paulb777

Copy link
Copy Markdown
Member 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 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.
@paulb777

Copy link
Copy Markdown
Member 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 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.
@paulb777 paulb777 added this to the 13.2.0 - M189 milestone Oct 30, 2026
@paulb777
paulb777 merged commit a7f77f6 into main Oct 30, 2026
94 checks passed
@paulb777
paulb777 deleted the pb-auth-user-metadata-race-16975 branch October 30, 2026 14:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

2 participants