From a5e7250b1c9b22c926d3e6498eb8a027e13e4c5c Mon Sep 17 00:00:00 2001 From: Codefarmer Date: Fri, 6 Nov 2026 14:37:31 +0100 Subject: [PATCH 1/6] fix(auth): link a colliding provider credential through the account that owns the address - The account-linking recovery opens the provider that owns the address: the opt-in legacy lookup names it when it can, a lone remaining provider is opened directly, and several are offered on the method picker. - Google, Facebook and OAuth sign-ins link the pending credential before reporting success, and only to an account with the same address; a mismatch or a failed link signs back out instead of half-finishing. - Account-linking errors carry the translated recovery message instead of hard-coded English. --- .../com/firebase/ui/auth/AuthFlowScope.kt | 23 + .../auth_provider/AccountLinking.kt | 83 ++++ .../EmailAuthProvider+FirebaseAuthUI.kt | 46 +- .../FacebookAuthProvider+FirebaseAuthUI.kt | 18 +- .../GoogleAuthProvider+FirebaseAuthUI.kt | 19 +- .../OAuthProvider+FirebaseAuthUI.kt | 19 +- .../auth/ui/components/ErrorRecoveryDialog.kt | 3 +- .../ui/auth/ui/screens/FirebaseAuthScreen.kt | 102 ++++- .../auth_provider/AccountLinkingTest.kt | 415 ++++++++++++++++++ .../FirebaseAuthScreenEmailRecoveryTest.kt | 175 ++++++++ 10 files changed, 847 insertions(+), 56 deletions(-) create mode 100644 auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinking.kt create mode 100644 auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt diff --git a/auth/src/main/java/com/firebase/ui/auth/AuthFlowScope.kt b/auth/src/main/java/com/firebase/ui/auth/AuthFlowScope.kt index 3a3564a60..d35cf704e 100644 --- a/auth/src/main/java/com/firebase/ui/auth/AuthFlowScope.kt +++ b/auth/src/main/java/com/firebase/ui/auth/AuthFlowScope.kt @@ -15,12 +15,15 @@ package com.firebase.ui.auth import androidx.compose.runtime.Composable +import androidx.compose.runtime.MutableState import androidx.compose.runtime.State import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.staticCompositionLocalOf import com.firebase.ui.auth.configuration.AuthUIConfiguration import com.firebase.ui.auth.configuration.auth_provider.AuthProvider +import com.google.firebase.auth.AuthCredential import com.google.firebase.auth.AuthResult import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser @@ -47,6 +50,12 @@ internal class AuthFlowScope( */ val state: State, private val sink: AuthStateSink, + /** + * A credential whose sign-in hit an existing account, waiting to be linked once the user signs + * in to that account. Shared with the screen hosting the flow, which sets it from the + * account-linking recovery and clears it when the flow ends. + */ + val pendingAccountLink: MutableState = mutableStateOf(null), ) { fun emit(state: AuthState) = sink.emit(state) @@ -65,6 +74,18 @@ internal class AuthFlowScope( } } +/** + * A credential to link once the user has signed in to the account that already owns [email]. + * + * @property credential The credential whose own sign-in collided with the existing account + * @property email The address of the existing account, when Firebase reported it. The account the + * user then signs in to must have this address, or the credential would be linked to someone else. + */ +internal data class PendingAccountLink( + val credential: AuthCredential, + val email: String?, +) + /** * What a signed-in [user] means as an [AuthState]: the single source of truth for whether they * still owe email verification. Callers must not re-derive it — only password users with an email @@ -107,6 +128,7 @@ internal fun hostAuthFlowScope( authUI: FirebaseAuthUI, configuration: AuthUIConfiguration, state: State, + pendingAccountLink: MutableState = mutableStateOf(null), ): AuthFlowScope = AuthFlowScope( auth = authUI.auth, config = configuration, @@ -114,4 +136,5 @@ internal fun hostAuthFlowScope( loginManagerProvider = authUI.testLoginManagerProvider, state = state, sink = { authUI.updateAuthState(it) }, + pendingAccountLink = pendingAccountLink, ) diff --git a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinking.kt b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinking.kt new file mode 100644 index 000000000..3afdb39dd --- /dev/null +++ b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinking.kt @@ -0,0 +1,83 @@ +/* + * Copyright 2025 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.firebase.ui.auth.configuration.auth_provider + +import com.firebase.ui.auth.AuthException +import com.firebase.ui.auth.AuthFlowScope +import com.google.firebase.auth.AuthResult +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.tasks.await + +/** + * Finishes an account-linking recovery: links [AuthFlowScope.pendingAccountLink] to the account + * [result] just signed in to, before the flow reports success. + * + * Linking happens here, inside the provider's sign-in, rather than once success is observed: by + * then the host has already been handed the unlinked result, and a failed link has nowhere to go. + * + * Either the sign-in and the link both stand, or neither does: + * - The signed-in account must have the address the collision named. Credential Manager and the + * OAuth flows let the user pick any account, and linking to a different one would attach the + * credential to someone else. A mismatch signs back out and raises the account-linking error + * again, with the credential still pending, so the user can pick the right account. + * - A link that fails signs back out and raises the failure, so the host is not left signed in to + * an account that silently lacks the credential it was asked to link. + * + * @return The link's result, or [result] unchanged when nothing is pending + */ +internal suspend fun AuthFlowScope.linkPendingAccountCredential(result: AuthResult): AuthResult { + val pending = pendingAccountLink.value ?: return result + if (config.isReauthenticationMode) return result + val user = result.user ?: return result + + val expectedEmail = pending.email + if (expectedEmail != null && !expectedEmail.equals(user.email, ignoreCase = true)) { + auth.signOut() + throw AuthException.AccountLinkingRequiredException( + message = config.stringProvider.errorUserMismatch, + email = expectedEmail, + credential = pending.credential, + ) + } + + val linked = try { + user.linkWithCredential(pending.credential).await() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + pendingAccountLink.value = null + auth.signOut() + throw when (val mapped = AuthException.from(e, config.stringProvider)) { + // Firebase reports some link failures as a collision, but there is no further account + // to recover to: offering the linking recovery again would loop. + is AuthException.AccountLinkingRequiredException -> AuthException.UnknownException( + message = config.stringProvider.unknownErrorRecoveryMessage, + cause = e, + ) + + else -> mapped + } + } + pendingAccountLink.value = null + return linked +} + +/** + * Whether [e], raised by a provider's own sign-in, is [linkPendingAccountCredential] rejecting the + * account the user picked rather than that provider's credential colliding. Only a collision of + * the provider's own credential is worth persisting for a later email-link sign-in. + */ +internal fun AuthFlowScope.isPendingLinkMismatch(e: AuthException.AccountLinkingRequiredException) = + e.credential != null && e.credential === pendingAccountLink.value?.credential diff --git a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/EmailAuthProvider+FirebaseAuthUI.kt b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/EmailAuthProvider+FirebaseAuthUI.kt index ea7e7e707..f5188532c 100644 --- a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/EmailAuthProvider+FirebaseAuthUI.kt +++ b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/EmailAuthProvider+FirebaseAuthUI.kt @@ -169,8 +169,7 @@ internal suspend fun AuthFlowScope.createOrLinkUserWithEmailAndPassword( } catch (e: FirebaseAuthUserCollisionException) { // Account collision: email already exists val accountLinkingException = AuthException.AccountLinkingRequiredException( - message = "An account already exists with this email. " + - "Please sign in with your existing account.", + message = config.stringProvider.accountLinkingRequiredRecoveryMessage, email = e.email ?: email, credential = when { canUpgrade -> e.updatedCredential ?: pendingCredential @@ -247,8 +246,7 @@ internal suspend fun AuthFlowScope.signInWithEmailAndPassword( .also { // Throw AccountLinkingRequiredException after successful validation val accountLinkingException = AuthException.AccountLinkingRequiredException( - message = "An account already exists with this email. " + - "Please sign in with your existing account to upgrade your anonymous account.", + message = config.stringProvider.accountLinkingRequiredRecoveryMessage, email = email, credential = credentialToValidate, cause = null @@ -265,8 +263,7 @@ internal suspend fun AuthFlowScope.signInWithEmailAndPassword( // Throw AccountLinkingRequiredException after successful validation // Account exists and user is anonymous - needs to link accounts val accountLinkingException = AuthException.AccountLinkingRequiredException( - message = "An account already exists with this email. " + - "Please sign in with your existing account to upgrade your anonymous account.", + message = config.stringProvider.accountLinkingRequiredRecoveryMessage, email = email, credential = credentialToValidate, cause = null @@ -419,6 +416,34 @@ private suspend fun AuthFlowScope.fetchLegacySignInMethods(email: String): List< } } +/** + * The sign-in method, among [candidates], that owns [email] according to the legacy + * `fetchSignInMethodsForEmail` lookup, for the account-linking recovery. + * + * Null when [AuthUIConfiguration.legacyFetchSignInWithEmail] is off, when the lookup comes back + * empty (as it always does with email enumeration protection on), or when it names nothing in + * [candidates]. Unlike [selectSuggestedLegacySignInMethod], a password account counts: for linking, + * the email sign-in step is exactly the way back in. + */ +internal suspend fun AuthFlowScope.findAccountOwnerSignInMethod( + email: String, + candidates: List, +): String? { + if (!config.legacyFetchSignInWithEmail) { + return null + } + + val emailProvider = candidates.filterIsInstance().firstOrNull() + val candidateIds = candidates.map { it.providerId }.toSet() + return fetchLegacySignInMethods(email).firstOrNull { signInMethod -> + when (signInMethod) { + EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD -> emailProvider != null + EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD -> emailProvider?.isEmailLinkSignInEnabled == true + else -> signInMethod in candidateIds + } + } +} + private fun SignInMethodQueryResult?.toSignInMethods(): List = this?.signInMethods?.filter { it.isNotBlank() } ?: emptyList() @@ -440,7 +465,7 @@ internal suspend fun AuthFlowScope.signInAndLinkWithCredential( val result = if (canUpgradeAnonymous(config, auth) || canLinkCredential(config, auth)) { auth.currentUser?.linkWithCredential(credential)?.await() } else { - signInOrReauth(credential) + signInOrReauth(credential)?.let { linkPendingAccountCredential(it) } } // signInOrReauth returns null in reauth mode (Task has no AuthResult). // Reconstruct success state from the now-reauthenticated current user. @@ -480,9 +505,7 @@ internal suspend fun AuthFlowScope.signInAndLinkWithCredential( } val accountLinkingException = AuthException.AccountLinkingRequiredException( - message = "An account already exists with the email ${email ?: ""}. " + - "Please sign in with your existing account to link " + - "your ${provider?.providerName ?: "this provider"} account.", + message = config.stringProvider.accountLinkingRequiredRecoveryMessage, email = email, credential = credentialForException, cause = e @@ -773,8 +796,7 @@ private suspend fun AuthFlowScope.handleEmailLinkCredentialLinkingFlow( .also { result -> // If safe link succeeds, throw AccountLinkingRequiredException for UI to handle val accountLinkingException = AuthException.AccountLinkingRequiredException( - message = "An account already exists with this email. " + - "Please sign in with your existing account to upgrade your anonymous account.", + message = config.stringProvider.accountLinkingRequiredRecoveryMessage, email = email, credential = storedCredentialForLink, cause = null diff --git a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/FacebookAuthProvider+FirebaseAuthUI.kt b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/FacebookAuthProvider+FirebaseAuthUI.kt index 591ae68b3..66d521748 100644 --- a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/FacebookAuthProvider+FirebaseAuthUI.kt +++ b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/FacebookAuthProvider+FirebaseAuthUI.kt @@ -190,13 +190,17 @@ internal suspend fun AuthFlowScope.signInWithFacebook( } } catch (e: AuthException.AccountLinkingRequiredException) { // Account collision occurred - save Facebook credential for linking after email link sign-in - // This happens when a user tries to sign in with Facebook but an email link account exists - EmailLinkPersistenceManager.default.saveCredentialForLinking( - context = context, - providerType = provider.providerId, - idToken = null, - accessToken = accessToken.token - ) + // This happens when a user tries to sign in with Facebook but an email link account exists. + // Not when the collision is the account-linking recovery refusing the account the user + // picked: this Facebook account is not the one waiting to be linked. + if (!isPendingLinkMismatch(e)) { + EmailLinkPersistenceManager.default.saveCredentialForLinking( + context = context, + providerType = provider.providerId, + idToken = null, + accessToken = accessToken.token + ) + } // Re-throw to let UI handle the account linking flow emit(AuthState.Error(e)) diff --git a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/GoogleAuthProvider+FirebaseAuthUI.kt b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/GoogleAuthProvider+FirebaseAuthUI.kt index 873be28da..970cb3e87 100644 --- a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/GoogleAuthProvider+FirebaseAuthUI.kt +++ b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/GoogleAuthProvider+FirebaseAuthUI.kt @@ -160,14 +160,17 @@ internal suspend fun AuthFlowScope.signInWithGoogle( android.util.Log.w("GoogleAuthProvider", "Failed to save sign-in preference", e) } } catch (e: AuthException.AccountLinkingRequiredException) { - // Account collision occurred - save Facebook credential for linking after email link sign-in - // This happens when a user tries to sign in with Facebook but an email link account exists - EmailLinkPersistenceManager.default.saveCredentialForLinking( - context = context, - providerType = provider.providerId, - idToken = idTokenFromResult, - accessToken = null - ) + // Account collision occurred - save the Google credential for linking after email link + // sign-in. Not when the collision is the account-linking recovery refusing the account + // the user picked: this Google account is not the one waiting to be linked. + if (!isPendingLinkMismatch(e)) { + EmailLinkPersistenceManager.default.saveCredentialForLinking( + context = context, + providerType = provider.providerId, + idToken = idTokenFromResult, + accessToken = null + ) + } // Re-throw to let UI handle the account linking flow emit(AuthState.Error(e)) diff --git a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/OAuthProvider+FirebaseAuthUI.kt b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/OAuthProvider+FirebaseAuthUI.kt index 86e40f3d1..3b3c318d9 100644 --- a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/OAuthProvider+FirebaseAuthUI.kt +++ b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/OAuthProvider+FirebaseAuthUI.kt @@ -107,9 +107,11 @@ internal suspend fun AuthFlowScope.signInWithProvider( return } + // Decided before signing in: an upgrade leaves the user no longer anonymous. + val isAnonymousUpgrade = canUpgradeAnonymous(config, auth) // Determine if we should upgrade anonymous user, reauthenticate, or do normal sign-in - val authResult = when { - canUpgradeAnonymous(config, auth) -> + val signInResult = when { + isAnonymousUpgrade -> auth.currentUser?.startActivityForLinkWithProvider(activity, oauthProvider)?.await() config.isReauthenticationMode -> { val currentUser = auth.currentUser @@ -119,9 +121,16 @@ internal suspend fun AuthFlowScope.signInWithProvider( else -> auth.startActivityForSignInWithProvider(activity, oauthProvider).await() } + // A plain sign-in may be finishing the account-linking recovery; an upgrade or a + // reauthentication has nothing pending to link. + val authResult = if (isAnonymousUpgrade || config.isReauthenticationMode) { + signInResult + } else { + signInResult?.let { linkPendingAccountCredential(it) } + } // Extract OAuth credential and complete sign-in - val credential = authResult?.credential as? OAuthCredential + val credential = signInResult?.credential as? OAuthCredential if (credential != null) { // The user is already signed in via startActivityForSignInWithProvider/startActivityForLinkWithProvider @@ -169,9 +178,7 @@ internal suspend fun AuthFlowScope.signInWithProvider( val credential = e.updatedCredential val accountLinkingException = AuthException.AccountLinkingRequiredException( - message = "An account already exists with the email ${email ?: ""}. " + - "Please sign in with your existing account to link " + - "your ${provider.providerName} account.", + message = config.stringProvider.accountLinkingRequiredRecoveryMessage, email = email, credential = credential, cause = e diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/components/ErrorRecoveryDialog.kt b/auth/src/main/java/com/firebase/ui/auth/ui/components/ErrorRecoveryDialog.kt index 2b4e90a76..15e0e4aea 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/components/ErrorRecoveryDialog.kt +++ b/auth/src/main/java/com/firebase/ui/auth/ui/components/ErrorRecoveryDialog.kt @@ -190,7 +190,8 @@ internal fun getRecoveryMessage( is AuthException.MfaRequiredException -> error.message?.takeIf { it.isNotBlank() } ?: stringProvider.mfaRequiredRecoveryMessage is AuthException.AccountLinkingRequiredException -> { - // Use the custom message which includes email and provider details + // The library raises this with translated copy; a host's own exception may carry + // its own message. error.message?.takeIf { it.isNotBlank() } ?: stringProvider.accountLinkingRequiredRecoveryMessage } diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt b/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt index 3be90a12a..4f5b8ce8d 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt +++ b/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt @@ -16,6 +16,7 @@ package com.firebase.ui.auth.ui.screens import com.firebase.ui.auth.AuthFlowScope import com.firebase.ui.auth.LocalAuthFlowScope +import com.firebase.ui.auth.PendingAccountLink import com.firebase.ui.auth.hostAuthFlowScope import android.util.Log import androidx.activity.compose.LocalActivity @@ -72,6 +73,7 @@ import com.firebase.ui.auth.configuration.DefaultAuthContentTransform import com.firebase.ui.auth.configuration.DefaultAuthPredictivePopContentTransform import com.firebase.ui.auth.configuration.MfaConfiguration import com.firebase.ui.auth.configuration.auth_provider.AuthProvider +import com.firebase.ui.auth.configuration.auth_provider.findAccountOwnerSignInMethod import com.firebase.ui.auth.configuration.auth_provider.rememberAnonymousSignInHandler import com.firebase.ui.auth.configuration.auth_provider.rememberGoogleSignInHandler import com.firebase.ui.auth.configuration.auth_provider.rememberOAuthSignInHandler @@ -121,7 +123,6 @@ import com.firebase.ui.auth.util.EmailLinkPersistenceManager import com.firebase.ui.auth.util.SignInPreferenceManager import com.firebase.ui.auth.util.displayIdentifier import com.firebase.ui.auth.util.getDisplayEmail -import com.google.firebase.auth.AuthCredential import com.google.firebase.auth.EmailAuthProvider import com.google.firebase.auth.AuthResult import com.google.firebase.auth.MultiFactorResolver @@ -200,13 +201,15 @@ fun FirebaseAuthScreen( val reauthState = reauthFlowState.phase val pendingReauth by authUI.pendingReauth.collectAsState() val hostStateHolder = rememberUpdatedState(rawAuthState) + // Shared with the provider flows, which link it once the user signs in to the account that + // owns the address. Cleared wherever the flow ends. + val pendingAccountLink = remember { mutableStateOf(null) } val hostScope = remember(authUI, configuration, hostStateHolder) { - hostAuthFlowScope(authUI, configuration, hostStateHolder) + hostAuthFlowScope(authUI, configuration, hostStateHolder, pendingAccountLink) } val authState = rawAuthState val dialogController = rememberTopLevelDialogController { authState } val lastSuccessfulUserId = remember { mutableStateOf(null) } - val pendingLinkingCredential = remember { mutableStateOf(null) } val pendingResolver = remember { mutableStateOf(null) } val mfaEnrollmentFlowState = rememberMfaEnrollmentFlowState(mfaConfiguration.allowedCountries) val phoneAuthFlowState = rememberPhoneAuthFlowState(configuration) @@ -450,13 +453,13 @@ fun FirebaseAuthScreen( authUI = authUI, content = emailContent, prefillEmail = { reauthPrefillEmail }, - credentialForLinking = { pendingLinkingCredential.value }, + credentialForLinking = { pendingAccountLink.value?.credential }, emailLinkFromDifferentDevice = { emailLinkFromDifferentDevice.value }, onEmailTyped = { typedEmail.value = it }, - onSuccess = { pendingLinkingCredential.value = null }, + onSuccess = { pendingAccountLink.value = null }, onError = { exception -> onSignInFailure(exception) }, onCancel = { - pendingLinkingCredential.value = null + pendingAccountLink.value = null if (!skipsMethodPicker && !backStack.popOrNull()) { backStack.resetBackStackTo(AuthRoute.MethodPicker) } @@ -491,7 +494,7 @@ fun FirebaseAuthScreen( } catch (e: Exception) { onSignInFailure(AuthException.from(e, stringProvider)) } finally { - pendingLinkingCredential.value = null + pendingAccountLink.value = null pendingResolver.value = null } } @@ -675,7 +678,7 @@ fun FirebaseAuthScreen( when (state) { is AuthState.Success -> { pendingResolver.value = null - pendingLinkingCredential.value = null + pendingAccountLink.value = null state.result?.let { result -> if (state.user.uid != lastSuccessfulUserId.value) { @@ -703,7 +706,7 @@ fun FirebaseAuthScreen( is AuthState.RequiresProfileCompletion, -> { pendingResolver.value = null - pendingLinkingCredential.value = null + pendingAccountLink.value = null // authUserState drops the result on these, so an exchange cannot be told // from a re-asserted session here — the confirmation wins either way. if (!ownsConfirmation && currentKey != AuthRoute.Success) { @@ -722,7 +725,7 @@ fun FirebaseAuthScreen( is AuthState.Cancelled -> { clearReauthPresentation() pendingResolver.value = null - pendingLinkingCredential.value = null + pendingAccountLink.value = null lastSuccessfulUserId.value = null typedEmail.value = null if (!currentKey.isAt(startRoute)) { @@ -740,7 +743,7 @@ fun FirebaseAuthScreen( pendingReauth?.request?.decline() if (activity !is FirebaseAuthActivity) { pendingResolver.value = null - pendingLinkingCredential.value = null + pendingAccountLink.value = null lastSuccessfulUserId.value = null typedEmail.value = null authUI.updateAuthState(AuthState.Idle) @@ -751,7 +754,7 @@ fun FirebaseAuthScreen( if (previous != null && !previous.isNotification) { clearReauthPresentation() pendingResolver.value = null - pendingLinkingCredential.value = null + pendingAccountLink.value = null lastSuccessfulUserId.value = null typedEmail.value = null // Number entry is a real position in the flow, so a retraction @@ -901,6 +904,69 @@ fun FirebaseAuthScreen( AuthRoute.Email.SignIn() } + /** + * Where the account-linking dialog sends the user: to sign in to the account that + * already owns the address, so the credential that collided with it can be linked. + * + * The owner comes from the opt-in legacy lookup when it can name one. With email + * enumeration protection on it never can, so a lone remaining provider is opened + * directly and several are offered on the method picker; whichever the user signs in + * with links the credential, provided the account has the same address. + */ + fun accountLinkingRecovery( + exception: AuthException.AccountLinkingRequiredException, + ): ((AuthException) -> Unit)? { + val credential = exception.credential + // Upgrading an anonymous user, or linking to a signed-in one: the collision is + // with the user already signed in, which only the email step's own handling + // resolves. Likewise with no credential there is nothing to carry anywhere else. + if (credential == null || authUI.auth.currentUser != null) { + return if (configuration.isEmailProviderConfigured()) { + { _ -> + pendingAccountLink.value = + credential?.let { PendingAccountLink(it, exception.email) } + navigateToEmailStep(AuthRoute.Email.SignIn(), exception.email) + } + } else { + null + } + } + + // Providers that can hold the existing account: not the one that just collided, + // and not phone or anonymous sign-in, which have no address to match. + val owners = configuration.providers.filter { provider -> + provider !is AuthProvider.Phone && + provider !is AuthProvider.Anonymous && + provider.providerId != credential.provider + } + if (owners.isEmpty()) return null + + return { _ -> + pendingAccountLink.value = PendingAccountLink(credential, exception.email) + coroutineScope.launch { + val ownerSignInMethod = exception.email?.let { email -> + hostScope.findAccountOwnerSignInMethod(email, owners) + } + val lone = owners.singleOrNull() + when { + ownerSignInMethod == EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD -> + navigateToEmailStep(emailLinkRecoveryStep, exception.email) + + ownerSignInMethod == EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD || + (ownerSignInMethod == null && lone is AuthProvider.Email) -> + navigateToEmailStep(AuthRoute.Email.SignIn(), exception.email) + + ownerSignInMethod != null -> continueWithProvider(ownerSignInMethod) + + lone != null -> onProviderSelected(lone) + + !backStack.lastOrNull().isAt(AuthRoute.MethodPicker) -> + backStack.resetBackStackTo(AuthRoute.MethodPicker) + } + } + } + } + val errorState = authState as? AuthState.Error if (errorState != null) { LaunchedEffect(errorState) { @@ -935,16 +1001,8 @@ fun FirebaseAuthScreen( } } - is AuthException.AccountLinkingRequiredException -> { - if (configuration.isEmailProviderConfigured()) { - { - pendingLinkingCredential.value = exception.credential - navigateToEmailStep(AuthRoute.Email.SignIn(), exception.email) - } - } else { - null - } - } + is AuthException.AccountLinkingRequiredException -> + accountLinkingRecovery(exception) is AuthException.EmailLinkPromptForEmailException -> { { diff --git a/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt b/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt new file mode 100644 index 000000000..724f8b3a2 --- /dev/null +++ b/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt @@ -0,0 +1,415 @@ +/* + * Copyright 2025 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.firebase.ui.auth.configuration.auth_provider + +import android.app.Activity +import android.content.Context +import androidx.credentials.CredentialManager +import androidx.test.core.app.ApplicationProvider +import com.firebase.ui.auth.AuthException +import com.firebase.ui.auth.AuthState +import com.firebase.ui.auth.FirebaseAuthUI +import com.firebase.ui.auth.PendingAccountLink +import com.firebase.ui.auth.configuration.AuthUIConfiguration +import com.firebase.ui.auth.configuration.authUIConfiguration +import com.firebase.ui.auth.configuration.string_provider.DefaultAuthUIStringProvider +import com.firebase.ui.auth.flowScope +import com.firebase.ui.auth.recordingScope +import com.google.android.gms.tasks.Tasks +import com.google.common.truth.Truth.assertThat +import com.google.firebase.FirebaseApp +import com.google.firebase.FirebaseNetworkException +import com.google.firebase.FirebaseOptions +import com.google.firebase.auth.AuthCredential +import com.google.firebase.auth.AuthResult +import com.google.firebase.auth.EmailAuthProvider +import com.google.firebase.auth.FirebaseAuth +import com.google.firebase.auth.FirebaseAuthUserCollisionException +import com.google.firebase.auth.FirebaseUser +import com.google.firebase.auth.GoogleAuthProvider +import com.google.firebase.auth.OAuthCredential +import com.google.firebase.auth.OAuthProvider +import com.google.firebase.auth.SignInMethodQueryResult +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.runTest +import org.junit.After +import org.junit.Assert.assertThrows +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mockito.mock +import org.mockito.Mockito.never +import org.mockito.Mockito.verify +import org.mockito.Mockito.`when` +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * The account-linking recovery's provider half: linking the credential that collided once the + * user signs in to the account that owns the address, the lookup that names that account, and + * the translated copy the collision now carries. + */ +@RunWith(RobolectricTestRunner::class) +@Config(manifest = Config.NONE) +class AccountLinkingTest { + + private lateinit var applicationContext: Context + private lateinit var firebaseApp: FirebaseApp + private lateinit var mockAuth: FirebaseAuth + private lateinit var stringProvider: DefaultAuthUIStringProvider + + /** The Facebook credential whose own sign-in hit the existing account. */ + private val pendingCredential = mock(AuthCredential::class.java) + + @Before + fun setUp() { + applicationContext = ApplicationProvider.getApplicationContext() + stringProvider = DefaultAuthUIStringProvider(applicationContext) + FirebaseAuthUI.clearInstanceCache() + FirebaseApp.getApps(applicationContext).forEach { it.delete() } + firebaseApp = FirebaseApp.initializeApp( + applicationContext, + FirebaseOptions.Builder() + .setApiKey("fake-api-key") + .setApplicationId("fake-app-id") + .setProjectId("fake-project-id") + .build() + ) + mockAuth = mock(FirebaseAuth::class.java) + `when`(mockAuth.currentUser).thenReturn(null) + } + + @After + fun tearDown() { + FirebaseAuthUI.clearInstanceCache() + try { + firebaseApp.delete() + } catch (_: Exception) { + } + } + + // ============================================================================================= + // linkPendingAccountCredential + // ============================================================================================= + + @Test + fun `links the pending credential to the account with the same address and clears it`() = + runTest { + val (signIn, user) = signedInAs(OWNER_EMAIL) + val linked = mock(AuthResult::class.java) + `when`(user.linkWithCredential(pendingCredential)).thenReturn(Tasks.forResult(linked)) + val scope = scopeWithPendingLink() + + val result = scope.linkPendingAccountCredential(signIn) + + assertThat(result).isSameInstanceAs(linked) + assertThat(scope.pendingAccountLink.value).isNull() + verify(mockAuth, never()).signOut() + } + + /** Addresses are case-insensitive, and Firebase does not normalise what the user typed. */ + @Test + fun `an address that differs only in case still matches`() = runTest { + val (signIn, user) = signedInAs(OWNER_EMAIL.uppercase()) + `when`(user.linkWithCredential(pendingCredential)) + .thenReturn(Tasks.forResult(mock(AuthResult::class.java))) + + scopeWithPendingLink().linkPendingAccountCredential(signIn) + + verify(user).linkWithCredential(pendingCredential) + } + + /** + * Credential Manager lets the user pick any Google account. Linking to one with a different + * address would hand the credential to someone else, so the sign-in is undone and the linking + * error raised again, still holding the credential, for the user to pick the right account. + */ + @Test + fun `a different account is signed back out and the linking error raised again`() = runTest { + val (signIn, user) = signedInAs("someone-else@example.com") + val scope = scopeWithPendingLink() + + val error = assertThrows(AuthException.AccountLinkingRequiredException::class.java) { + kotlinx.coroutines.runBlocking { scope.linkPendingAccountCredential(signIn) } + } + + assertThat(error.message).isEqualTo(stringProvider.errorUserMismatch) + assertThat(error.email).isEqualTo(OWNER_EMAIL) + assertThat(error.credential).isSameInstanceAs(pendingCredential) + assertThat(scope.isPendingLinkMismatch(error)).isTrue() + assertThat(scope.pendingAccountLink.value).isNotNull() + verify(mockAuth).signOut() + verify(user, never()).linkWithCredential(any()) + } + + /** A failed link must not leave the host signed in to an account missing the credential. */ + @Test + fun `a link that fails signs back out and reports the failure`() = runTest { + val (signIn, user) = signedInAs(OWNER_EMAIL) + `when`(user.linkWithCredential(pendingCredential)) + .thenReturn(Tasks.forException(FirebaseNetworkException("offline"))) + val scope = scopeWithPendingLink() + + assertThrows(AuthException.NetworkException::class.java) { + kotlinx.coroutines.runBlocking { scope.linkPendingAccountCredential(signIn) } + } + + assertThat(scope.pendingAccountLink.value).isNull() + verify(mockAuth).signOut() + } + + /** + * Firebase can report a link failure as a collision. Raising the linking error for it would + * send the user straight back round the recovery that just failed. + */ + @Test + fun `a link that fails as a collision is not offered the linking recovery again`() = runTest { + val (signIn, user) = signedInAs(OWNER_EMAIL) + `when`(user.linkWithCredential(pendingCredential)).thenReturn( + Tasks.forException( + FirebaseAuthUserCollisionException( + "ERROR_CREDENTIAL_ALREADY_IN_USE", + "already linked to another user" + ) + ) + ) + val scope = scopeWithPendingLink() + + val error = assertThrows(AuthException.UnknownException::class.java) { + kotlinx.coroutines.runBlocking { scope.linkPendingAccountCredential(signIn) } + } + + assertThat(error.message).isEqualTo(stringProvider.unknownErrorRecoveryMessage) + verify(mockAuth).signOut() + } + + @Test + fun `nothing pending leaves the sign-in as it was`() = runTest { + val (signIn, user) = signedInAs(OWNER_EMAIL) + val scope = FirebaseAuthUI.create(firebaseApp, mockAuth).recordingScope(config(), mutableListOf()) + + assertThat(scope.linkPendingAccountCredential(signIn)).isSameInstanceAs(signIn) + verify(user, never()).linkWithCredential(any()) + } + + /** A reauthentication proves who the user is; it is never the account-linking recovery. */ + @Test + fun `a reauthentication never links`() = runTest { + val (signIn, user) = signedInAs(OWNER_EMAIL) + val scope = scopeWithPendingLink(config(isReauthenticationMode = true)) + + assertThat(scope.linkPendingAccountCredential(signIn)).isSameInstanceAs(signIn) + verify(user, never()).linkWithCredential(any()) + } + + // ============================================================================================= + // The provider flows link before reporting success + // ============================================================================================= + + /** + * The point of linking inside the provider: the host is never handed the unlinked result. The + * Success the flow reports already carries the link's result. + */ + @Test + fun `a Google sign-in during the recovery links before it reports success`() = runTest { + val googleCredential = mock(AuthCredential::class.java) + val credentialManager = mock(AuthProvider.Google.CredentialManagerProvider::class.java) + `when`( + credentialManager.getGoogleCredential( + context = eq(applicationContext), + credentialManager = any(), + serverClientId = eq("test-client-id"), + filterByAuthorizedAccounts = eq(true), + autoSelectEnabled = eq(false) + ) + ).thenReturn( + AuthProvider.Google.GoogleSignInResult( + credential = googleCredential, + idToken = "test-id-token", + displayName = null, + photoUrl = null, + ) + ) + val (signIn, user) = signedInAs(OWNER_EMAIL) + `when`(mockAuth.signInWithCredential(googleCredential)).thenReturn(Tasks.forResult(signIn)) + val linked = mock(AuthResult::class.java) + `when`(linked.user).thenReturn(user) + `when`(user.linkWithCredential(pendingCredential)).thenReturn(Tasks.forResult(linked)) + val instance = FirebaseAuthUI.create(firebaseApp, mockAuth) + val scope = instance.flowScope(config()) + scope.pendingAccountLink.value = PendingAccountLink(pendingCredential, OWNER_EMAIL) + + scope.signInWithGoogle( + context = applicationContext, + provider = googleProvider, + credentialManagerProvider = credentialManager, + ) + + verify(user).linkWithCredential(pendingCredential) + val finalState = instance.authStateFlow().first { it !is AuthState.Loading } + assertThat(finalState).isEqualTo( + AuthState.Success(result = linked, user = user, isNewUser = false) + ) + } + + /** OAuth providers sign in through Firebase's own activity flow, not the shared credential path. */ + @Test + fun `an OAuth sign-in during the recovery links before it reports success`() = runTest { + val (signIn, user) = signedInAs(OWNER_EMAIL) + `when`(signIn.credential).thenReturn(mock(OAuthCredential::class.java)) + `when`(mockAuth.pendingAuthResult).thenReturn(null) + `when`(mockAuth.startActivityForSignInWithProvider(any(), any())) + .thenReturn(Tasks.forResult(signIn)) + val linked = mock(AuthResult::class.java) + `when`(linked.user).thenReturn(user) + `when`(user.linkWithCredential(pendingCredential)).thenReturn(Tasks.forResult(linked)) + val github = AuthProvider.Github(customParameters = emptyMap()) + val instance = FirebaseAuthUI.create(firebaseApp, mockAuth) + val scope = instance.flowScope(config(github)) + scope.pendingAccountLink.value = PendingAccountLink(pendingCredential, OWNER_EMAIL) + + scope.signInWithProvider(applicationContext, mock(Activity::class.java), github) + + verify(user).linkWithCredential(pendingCredential) + val finalState = instance.authStateFlow().first { it !is AuthState.Loading } + assertThat(finalState).isEqualTo( + AuthState.Success(result = linked, user = user, isNewUser = false) + ) + } + + // ============================================================================================= + // findAccountOwnerSignInMethod + // ============================================================================================= + + /** Off by default: with email enumeration protection on, the lookup reveals nothing. */ + @Test + fun `the owner lookup does nothing unless the legacy lookup is enabled`() = runTest { + val scope = FirebaseAuthUI.create(firebaseApp, mockAuth).flowScope(config()) + + assertThat(scope.findAccountOwnerSignInMethod(OWNER_EMAIL, listOf(googleProvider))).isNull() + verify(mockAuth, never()).fetchSignInMethodsForEmail(any()) + } + + /** + * The existing different-method lookup skips a password account; for linking it is exactly + * the account to sign back in to. + */ + @Test + fun `the owner lookup names a password account`() = runTest { + signInMethodsAre(EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD) + val scope = FirebaseAuthUI.create(firebaseApp, mockAuth).flowScope(config(legacyLookup = true)) + + assertThat(scope.findAccountOwnerSignInMethod(OWNER_EMAIL, listOf(emailProvider, googleProvider))) + .isEqualTo(EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD) + } + + @Test + fun `the owner lookup names a configured provider`() = runTest { + signInMethodsAre(GoogleAuthProvider.PROVIDER_ID) + val scope = FirebaseAuthUI.create(firebaseApp, mockAuth).flowScope(config(legacyLookup = true)) + + assertThat(scope.findAccountOwnerSignInMethod(OWNER_EMAIL, listOf(emailProvider, googleProvider))) + .isEqualTo(GoogleAuthProvider.PROVIDER_ID) + } + + @Test + fun `the owner lookup skips what the recovery cannot open`() = runTest { + // Email-link sign-in is not enabled, and Apple is not among the candidates. + signInMethodsAre(EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD, "apple.com") + val scope = FirebaseAuthUI.create(firebaseApp, mockAuth).flowScope(config(legacyLookup = true)) + + assertThat(scope.findAccountOwnerSignInMethod(OWNER_EMAIL, listOf(emailProvider, googleProvider))) + .isNull() + } + + // ============================================================================================= + // Translated copy (Part 3) + // ============================================================================================= + + /** The dialog shows the exception's message, so a hard-coded one is never translated. */ + @Test + fun `a provider collision carries the translated linking message`() = runTest { + val collision = mock(FirebaseAuthUserCollisionException::class.java) + `when`(collision.email).thenReturn(OWNER_EMAIL) + `when`(mockAuth.signInWithCredential(pendingCredential)) + .thenReturn(Tasks.forException(collision)) + val scope = FirebaseAuthUI.create(firebaseApp, mockAuth).recordingScope(config(), mutableListOf()) + + val error = assertThrows(AuthException.AccountLinkingRequiredException::class.java) { + kotlinx.coroutines.runBlocking { + scope.signInAndLinkWithCredential(pendingCredential, AuthProvider.Facebook()) + } + } + + assertThat(error.message).isEqualTo(stringProvider.accountLinkingRequiredRecoveryMessage) + assertThat(error.email).isEqualTo(OWNER_EMAIL) + assertThat(error.credential).isSameInstanceAs(pendingCredential) + } + + // ============================================================================================= + // Helpers + // ============================================================================================= + + private val emailProvider = AuthProvider.Email( + emailLinkActionCodeSettings = null, + passwordValidationRules = emptyList(), + ) + + private val googleProvider = AuthProvider.Google( + scopes = emptyList(), + serverClientId = "test-client-id", + ) + + private fun config( + vararg extra: AuthProvider, + legacyLookup: Boolean = false, + isReauthenticationMode: Boolean = false, + ): AuthUIConfiguration = authUIConfiguration { + context = applicationContext + providers { + provider(emailProvider) + provider(googleProvider) + extra.forEach { provider(it) } + } + legacyFetchSignInWithEmail = legacyLookup + this.isReauthenticationMode = isReauthenticationMode + } + + private fun scopeWithPendingLink(configuration: AuthUIConfiguration = config()) = + FirebaseAuthUI.create(firebaseApp, mockAuth) + .recordingScope(configuration, mutableListOf()) + .also { it.pendingAccountLink.value = PendingAccountLink(pendingCredential, OWNER_EMAIL) } + + private fun signedInAs(email: String): Pair { + val user = mock(FirebaseUser::class.java) + `when`(user.email).thenReturn(email) + `when`(user.uid).thenReturn("owner-uid") + val result = mock(AuthResult::class.java) + `when`(result.user).thenReturn(user) + return result to user + } + + private fun signInMethodsAre(vararg methods: String) { + val query = mock(SignInMethodQueryResult::class.java) + `when`(query.signInMethods).thenReturn(methods.toList()) + `when`(mockAuth.fetchSignInMethodsForEmail(OWNER_EMAIL)).thenReturn(Tasks.forResult(query)) + } + + private companion object { + const val OWNER_EMAIL = "owner@example.com" + } +} diff --git a/auth/src/test/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreenEmailRecoveryTest.kt b/auth/src/test/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreenEmailRecoveryTest.kt index d1a9095c6..8371c54b1 100644 --- a/auth/src/test/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreenEmailRecoveryTest.kt +++ b/auth/src/test/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreenEmailRecoveryTest.kt @@ -76,6 +76,10 @@ import org.junit.runner.RunWith import org.mockito.Mockito.mock import org.mockito.Mockito.verify import org.mockito.Mockito.`when` +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import kotlinx.coroutines.runBlocking +import androidx.credentials.CredentialManager import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @@ -878,6 +882,110 @@ class FirebaseAuthScreenEmailRecoveryTest { assertThat(cancelled).isEqualTo(1) } + /** + * firebase/FirebaseUI-Android#2550, the half the crash guard left: a Facebook sign-in hit an + * account Google created. With Google the only other provider that can hold the account, the + * recovery opens it, and the Facebook credential is linked to the account the user signs in + * to before the flow reports success. + */ + @Test + fun `an account that needs linking opens the lone other provider and links the credential`() { + val facebookCredential = facebookCredential() + val googleCredential = mock(AuthCredential::class.java) + val credentialManager = mock(AuthProvider.Google.CredentialManagerProvider::class.java) + runBlocking { + `when`( + credentialManager.getGoogleCredential( + context = any(), + credentialManager = any(), + serverClientId = eq(GOOGLE_CLIENT_ID), + filterByAuthorizedAccounts = any(), + autoSelectEnabled = any(), + ) + ).thenReturn( + AuthProvider.Google.GoogleSignInResult( + credential = googleCredential, + idToken = "google-id-token", + displayName = null, + photoUrl = null, + ) + ) + } + authUI.testCredentialManagerProvider = credentialManager + val owner = accountOwner() + `when`(mockAuth.signInWithCredential(googleCredential)) + .thenReturn(Tasks.forResult(owner.signIn)) + start(configuration = googleAndAnonymousConfiguration()) + + recoverFrom(accountLinkingRequired(facebookCredential)) + + verify(owner.user).linkWithCredential(facebookCredential) + composeTestRule.onNodeWithTag(AUTHENTICATED_TAG).assertIsDisplayed() + } + + /** + * Without the opt-in lookup nothing says which provider owns the address, so with several + * candidates the recovery offers the method picker. Whichever the user then signs in with + * carries the credential: here the email step, reached from the picker rather than from the + * recovery itself. + */ + @Test + fun `with several other providers the recovery offers the picker and the chosen sign-in links`() { + val facebookCredential = facebookCredential() + val owner = accountOwner() + `when`(mockAuth.signInWithEmailAndPassword(OTHER_EMAIL, PASSWORD)) + .thenReturn(Tasks.forResult(owner.signIn)) + start(configuration = emailAndGoogleConfiguration()) + + recoverFrom(accountLinkingRequired(facebookCredential)) + + composeTestRule.onNodeWithTag(FirebaseAuthTestTags.MethodPicker.PROVIDER_LIST) + .assertIsDisplayed() + composeTestRule.onNodeWithTag(FirebaseAuthTestTags.SignIn.EMAIL_FIELD).assertDoesNotExist() + + composeTestRule.onNodeWithText(stringProvider.signInWithEmail).performClick() + composeTestRule.waitForIdle() + composeTestRule.onNodeWithTag(FirebaseAuthTestTags.SignIn.EMAIL_FIELD) + .performTextInput(OTHER_EMAIL) + signInWithPassword() + + verify(owner.user).linkWithCredential(facebookCredential) + } + + /** + * Upgrading an anonymous user is a collision with the user already signed in, which only the + * email step's own handling resolves; the provider routing is for a signed-out flow. + */ + @Test + fun `an anonymous upgrade that needs linking still recovers to the email step`() { + start(configuration = emailAndGoogleConfiguration()) + val anonymous = mock(FirebaseUser::class.java) + `when`(anonymous.isAnonymous).thenReturn(true) + `when`(mockAuth.currentUser).thenReturn(anonymous) + + recoverFrom(accountLinkingRequired(facebookCredential())) + + composeTestRule.onNodeWithTag(FirebaseAuthTestTags.SignIn.EMAIL_FIELD).assertIsDisplayed() + composeTestRule.onNodeWithText(OTHER_EMAIL).assertIsDisplayed() + } + + /** Nothing else can hold the account, so there is no sign-in to send the user to. */ + @Test + fun `no recovery is offered when the colliding provider is the only one that can hold the account`() { + start(configuration = githubAndPhoneConfiguration()) + val githubCredential = mock(AuthCredential::class.java) + `when`(githubCredential.provider).thenReturn("github.com") + + composeTestRule.runOnIdle { + authUI.updateAuthState(AuthState.Error(accountLinkingRequired(githubCredential))) + } + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithText(stringProvider.errorDialogTitle).assertExists() + composeTestRule.onNodeWithTag(FirebaseAuthTestTags.ErrorRecovery.RETRY_BUTTON) + .assertDoesNotExist() + } + /** * The point of the recovery, and the half a landing assertion cannot see: the credential the * failure carried has to survive the move and be linked once the password sign-in it asked for @@ -1094,6 +1202,72 @@ class FirebaseAuthScreenEmailRecoveryTest { "${initialState.authRoute()?.let { it::class.simpleName }}->" + "${targetState.authRoute()?.let { it::class.simpleName }}" + /** A credential from a Facebook sign-in, which is what Firebase does not trust an address from. */ + private fun facebookCredential(): AuthCredential = mock(AuthCredential::class.java).also { + `when`(it.provider).thenReturn("facebook.com") + } + + private class AccountOwner(val user: FirebaseUser, val signIn: AuthResult) + + /** The existing account at [OTHER_EMAIL], which accepts the pending credential. */ + private fun accountOwner(): AccountOwner { + val user = mock(FirebaseUser::class.java) + `when`(user.uid).thenReturn("owner-uid") + `when`(user.email).thenReturn(OTHER_EMAIL) + `when`(user.isEmailVerified).thenReturn(true) + val signIn = mock(AuthResult::class.java) + `when`(signIn.user).thenReturn(user) + val linked = mock(AuthResult::class.java) + `when`(linked.user).thenReturn(user) + `when`(user.linkWithCredential(any())).thenReturn(Tasks.forResult(linked)) + return AccountOwner(user, signIn) + } + + private fun googleProvider() = AuthProvider.Google( + scopes = emptyList(), + serverClientId = GOOGLE_CLIENT_ID, + ) + + /** Google is the only provider besides one that cannot hold an address. */ + private fun googleAndAnonymousConfiguration(): AuthUIConfiguration = authUIConfiguration { + context = applicationContext + providers { + provider(googleProvider()) + provider(AuthProvider.Anonymous) + } + isCredentialManagerEnabled = false + } + + private fun emailAndGoogleConfiguration(): AuthUIConfiguration = authUIConfiguration { + context = applicationContext + providers { + provider( + AuthProvider.Email( + isDisplayNameRequired = false, + emailLinkActionCodeSettings = null, + passwordValidationRules = emptyList() + ) + ) + provider(googleProvider()) + } + isCredentialManagerEnabled = false + } + + private fun githubAndPhoneConfiguration(): AuthUIConfiguration = authUIConfiguration { + context = applicationContext + providers { + provider(AuthProvider.Github(customParameters = emptyMap())) + provider( + AuthProvider.Phone( + defaultNumber = null, + defaultCountryCode = null, + allowedCountries = null + ) + ) + } + isCredentialManagerEnabled = false + } + private fun accountLinkingRequired(credential: AuthCredential) = AuthException.AccountLinkingRequiredException( message = "an account already exists with this address", @@ -1199,6 +1373,7 @@ class FirebaseAuthScreenEmailRecoveryTest { const val OTHER_EMAIL = "someone.else@example.com" const val AUTHENTICATED_TAG = "recovery_test_authenticated" const val PASSWORD = "correct-horse-battery" + const val GOOGLE_CLIENT_ID = "test-client-id" const val EMAIL_LINK = "https://example.com/finish?oobCode=abc&mode=signIn" } } From 9801ef2b653a573c71f423081de60e3eafa96a64 Mon Sep 17 00:00:00 2001 From: Codefarmer Date: Fri, 6 Nov 2026 15:00:18 +0100 Subject: [PATCH 2/6] fix(auth): refuse an email-step sign-in at another address while a link is pending The account-linking recovery prefills the account's address, but the field stays editable. Signing in elsewhere would link the credential to someone else, so the email step now refuses before signing in, as the provider flows do after. --- .../EmailAuthProvider+FirebaseAuthUI.kt | 15 ++++ .../auth_provider/AccountLinkingTest.kt | 70 +++++++++++++++++++ 2 files changed, 85 insertions(+) diff --git a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/EmailAuthProvider+FirebaseAuthUI.kt b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/EmailAuthProvider+FirebaseAuthUI.kt index f5188532c..057222b87 100644 --- a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/EmailAuthProvider+FirebaseAuthUI.kt +++ b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/EmailAuthProvider+FirebaseAuthUI.kt @@ -273,6 +273,21 @@ internal suspend fun AuthFlowScope.signInWithEmailAndPassword( } } } else { + // The account-linking recovery prefills the address it named, but the field stays + // editable. Linking to an account at another address would attach the credential to + // someone else, so refuse before signing in at all. + val pending = pendingAccountLink.value + if (credentialForLinking != null && + credentialForLinking === pending?.credential && + pending.email != null && + !pending.email.equals(email, ignoreCase = true) + ) { + throw AuthException.AccountLinkingRequiredException( + message = config.stringProvider.errorUserMismatch, + email = pending.email, + credential = pending.credential, + ) + } // Normal sign-in auth.signInWithEmailAndPassword(email, password).await() .let { result -> diff --git a/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt b/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt index 724f8b3a2..5ae6a707a 100644 --- a/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt +++ b/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt @@ -291,6 +291,73 @@ class AccountLinkingTest { ) } + /** + * The email step the recovery opens is prefilled with the account's address, but the field is + * editable. Signing in at another address would link the credential to someone else, so it is + * refused before any sign-in happens. + */ + @Test + fun `the email step refuses an address other than the account's before signing in`() = runTest { + val scope = scopeWithPendingLink() + + val error = assertThrows(AuthException.AccountLinkingRequiredException::class.java) { + kotlinx.coroutines.runBlocking { + scope.signInWithEmailAndPassword( + context = applicationContext, + email = "someone-else@example.com", + password = PASSWORD, + credentialForLinking = pendingCredential, + ) + } + } + + assertThat(error.message).isEqualTo(stringProvider.errorUserMismatch) + assertThat(error.email).isEqualTo(OWNER_EMAIL) + assertThat(error.credential).isSameInstanceAs(pendingCredential) + verify(mockAuth, never()).signInWithEmailAndPassword(any(), any()) + } + + @Test + fun `the email step links when the address is the account's, whatever its case`() = runTest { + val typed = OWNER_EMAIL.uppercase() + val (signIn, user) = signedInAs(OWNER_EMAIL) + `when`(mockAuth.signInWithEmailAndPassword(typed, PASSWORD)).thenReturn(Tasks.forResult(signIn)) + `when`(user.linkWithCredential(pendingCredential)) + .thenReturn(Tasks.forResult(mock(AuthResult::class.java))) + + scopeWithPendingLink(config(credentialManager = false)).signInWithEmailAndPassword( + context = applicationContext, + email = typed, + password = PASSWORD, + credentialForLinking = pendingCredential, + ) + + verify(user).linkWithCredential(pendingCredential) + } + + /** + * `EmailAuthScreen` is public, and a host composing it directly may pass a credential of its + * own. That is not the recovery's, so there is no address to hold it to. + */ + @Test + fun `a host's own credential to link is not held to the recovery's address`() = runTest { + val hostCredential = mock(AuthCredential::class.java) + val (signIn, user) = signedInAs("host-user@example.com") + `when`(mockAuth.signInWithEmailAndPassword("host-user@example.com", PASSWORD)) + .thenReturn(Tasks.forResult(signIn)) + `when`(user.linkWithCredential(hostCredential)) + .thenReturn(Tasks.forResult(mock(AuthResult::class.java))) + + scopeWithPendingLink(config(credentialManager = false)).signInWithEmailAndPassword( + context = applicationContext, + email = "host-user@example.com", + password = PASSWORD, + credentialForLinking = hostCredential, + ) + + verify(user).linkWithCredential(hostCredential) + } + // ============================================================================================= // findAccountOwnerSignInMethod // ============================================================================================= @@ -378,6 +445,7 @@ class AccountLinkingTest { vararg extra: AuthProvider, legacyLookup: Boolean = false, isReauthenticationMode: Boolean = false, + credentialManager: Boolean = true, ): AuthUIConfiguration = authUIConfiguration { context = applicationContext providers { @@ -387,6 +455,7 @@ class AccountLinkingTest { } legacyFetchSignInWithEmail = legacyLookup this.isReauthenticationMode = isReauthenticationMode + isCredentialManagerEnabled = credentialManager } private fun scopeWithPendingLink(configuration: AuthUIConfiguration = config()) = @@ -411,5 +480,6 @@ class AccountLinkingTest { private companion object { const val OWNER_EMAIL = "owner@example.com" + const val PASSWORD = "correct-horse-battery" } } From 13a9b9fee784c5f38f1fd847d262ed70bc8372dd Mon Sep 17 00:00:00 2001 From: Codefarmer Date: Fri, 6 Nov 2026 16:11:46 +0100 Subject: [PATCH 3/6] fix(auth): keep the account-linking recovery all or nothing on every path - Only a sign-in through a provider the recovery offered finishes the link; any other, such as phone, drops it instead of being refused. - A mismatched account the sign-in only just created is deleted rather than left behind; a cancelled link signs back out. - The email step links the recovery's credential all or nothing, and the email-link step is held to the account's address too. - The provider credential a collision saved for a later email-link sign-in is forgotten once the recovery's link ends. --- .../com/firebase/ui/auth/AuthFlowScope.kt | 3 + .../auth_provider/AccountLinking.kt | 74 +++++++-- .../EmailAuthProvider+FirebaseAuthUI.kt | 29 ++-- .../OAuthProvider+FirebaseAuthUI.kt | 2 +- .../ui/auth/ui/screens/FirebaseAuthScreen.kt | 30 +++- .../auth/util/EmailLinkPersistenceManager.kt | 17 +++ .../auth_provider/AccountLinkingTest.kt | 143 ++++++++++++++++-- .../FirebaseAuthScreenEmailRecoveryTest.kt | 20 ++- 8 files changed, 272 insertions(+), 46 deletions(-) diff --git a/auth/src/main/java/com/firebase/ui/auth/AuthFlowScope.kt b/auth/src/main/java/com/firebase/ui/auth/AuthFlowScope.kt index d35cf704e..2bbef7cbb 100644 --- a/auth/src/main/java/com/firebase/ui/auth/AuthFlowScope.kt +++ b/auth/src/main/java/com/firebase/ui/auth/AuthFlowScope.kt @@ -80,10 +80,13 @@ internal class AuthFlowScope( * @property credential The credential whose own sign-in collided with the existing account * @property email The address of the existing account, when Firebase reported it. The account the * user then signs in to must have this address, or the credential would be linked to someone else. + * @property ownerProviderIds The providers the recovery offered for signing in to that account. A + * sign-in through any other provider is the user going another way, not the recovery finishing. */ internal data class PendingAccountLink( val credential: AuthCredential, val email: String?, + val ownerProviderIds: Set, ) /** diff --git a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinking.kt b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinking.kt index 3afdb39dd..0ad6d84fa 100644 --- a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinking.kt +++ b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinking.kt @@ -16,9 +16,12 @@ package com.firebase.ui.auth.configuration.auth_provider import com.firebase.ui.auth.AuthException import com.firebase.ui.auth.AuthFlowScope +import com.google.firebase.auth.AuthCredential import com.google.firebase.auth.AuthResult import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.tasks.await +import kotlinx.coroutines.withContext /** * Finishes an account-linking recovery: links [AuthFlowScope.pendingAccountLink] to the account @@ -27,34 +30,53 @@ import kotlinx.coroutines.tasks.await * Linking happens here, inside the provider's sign-in, rather than once success is observed: by * then the host has already been handed the unlinked result, and a failed link has nowhere to go. * - * Either the sign-in and the link both stand, or neither does: + * Only a sign-in through one of the providers the recovery offered can finish it + * ([com.firebase.ui.auth.PendingAccountLink.ownerProviderIds]). Any other sign-in, such as phone, + * means the user has gone another way: the pending link is dropped and the sign-in stands as it is. + * + * Otherwise the sign-in and the link both stand, or neither does: * - The signed-in account must have the address the collision named. Credential Manager and the * OAuth flows let the user pick any account, and linking to a different one would attach the - * credential to someone else. A mismatch signs back out and raises the account-linking error - * again, with the credential still pending, so the user can pick the right account. - * - A link that fails signs back out and raises the failure, so the host is not left signed in to - * an account that silently lacks the credential it was asked to link. + * credential to someone else. A mismatch is undone, and the account-linking error raised again + * with the credential still pending, so the user can pick the right account. An account the + * sign-in only just created is deleted rather than left behind. + * - A link that fails, or is cancelled, signs back out, so the host is not left signed in to an + * account that silently lacks the credential it was asked to link. * - * @return The link's result, or [result] unchanged when nothing is pending + * @param providerId The provider [result] signed in with + * @return The link's result, or [result] unchanged when nothing is pending for [providerId] */ -internal suspend fun AuthFlowScope.linkPendingAccountCredential(result: AuthResult): AuthResult { +internal suspend fun AuthFlowScope.linkPendingAccountCredential( + result: AuthResult, + providerId: String?, +): AuthResult { val pending = pendingAccountLink.value ?: return result if (config.isReauthenticationMode) return result + if (providerId == null || providerId !in pending.ownerProviderIds) { + pendingAccountLink.value = null + return result + } val user = result.user ?: return result val expectedEmail = pending.email if (expectedEmail != null && !expectedEmail.equals(user.email, ignoreCase = true)) { + if (result.additionalUserInfo?.isNewUser == true) { + try { + user.delete().await() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // Signing out below still undoes the sign-in; only the empty account remains. + } + } auth.signOut() - throw AuthException.AccountLinkingRequiredException( - message = config.stringProvider.errorUserMismatch, - email = expectedEmail, - credential = pending.credential, - ) + throw pendingLinkMismatch() } val linked = try { user.linkWithCredential(pending.credential).await() } catch (e: CancellationException) { + withContext(NonCancellable) { auth.signOut() } throw e } catch (e: Exception) { pendingAccountLink.value = null @@ -74,6 +96,34 @@ internal suspend fun AuthFlowScope.linkPendingAccountCredential(result: AuthResu return linked } +/** + * Refuses an email step about to sign in, or send a sign-in link, to an address other than the + * one the account-linking recovery is finishing. The step is prefilled with that address but the + * field stays editable, and the credential must not end up on someone else's account. + * + * Applies only to the recovery's own credential: a host passing a credential of its own to the + * public `EmailAuthScreen` has no recovery address to be held to. + */ +internal fun AuthFlowScope.requirePendingLinkAddress( + credentialForLinking: AuthCredential?, + email: String, +) { + val pending = pendingAccountLink.value ?: return + if (credentialForLinking == null || credentialForLinking !== pending.credential) return + val expectedEmail = pending.email ?: return + if (!expectedEmail.equals(email, ignoreCase = true)) throw pendingLinkMismatch() +} + +/** The account-linking error again, for the account the recovery still wants. */ +private fun AuthFlowScope.pendingLinkMismatch(): AuthException.AccountLinkingRequiredException { + val pending = checkNotNull(pendingAccountLink.value) + return AuthException.AccountLinkingRequiredException( + message = config.stringProvider.errorUserMismatch, + email = pending.email, + credential = pending.credential, + ) +} + /** * Whether [e], raised by a provider's own sign-in, is [linkPendingAccountCredential] rejecting the * account the user picked rather than that provider's credential colliding. Only a collision of diff --git a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/EmailAuthProvider+FirebaseAuthUI.kt b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/EmailAuthProvider+FirebaseAuthUI.kt index 057222b87..b2be2c060 100644 --- a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/EmailAuthProvider+FirebaseAuthUI.kt +++ b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/EmailAuthProvider+FirebaseAuthUI.kt @@ -273,26 +273,18 @@ internal suspend fun AuthFlowScope.signInWithEmailAndPassword( } } } else { - // The account-linking recovery prefills the address it named, but the field stays - // editable. Linking to an account at another address would attach the credential to - // someone else, so refuse before signing in at all. - val pending = pendingAccountLink.value - if (credentialForLinking != null && - credentialForLinking === pending?.credential && - pending.email != null && - !pending.email.equals(email, ignoreCase = true) - ) { - throw AuthException.AccountLinkingRequiredException( - message = config.stringProvider.errorUserMismatch, - email = pending.email, - credential = pending.credential, - ) - } + // Refused before signing in at all, rather than undone after. + requirePendingLinkAddress(credentialForLinking, email) + val isPendingLink = credentialForLinking != null && + credentialForLinking === pendingAccountLink.value?.credential // Normal sign-in auth.signInWithEmailAndPassword(email, password).await() .let { result -> - // If there's a credential to link, link it after sign-in - if (credentialForLinking != null) { + if (isPendingLink) { + // The account-linking recovery's credential: linked all or nothing. + linkPendingAccountCredential(result, EmailAuthProvider.PROVIDER_ID) + } else if (credentialForLinking != null) { + // A host's own credential to link, linked after sign-in as before. val linkResult = result.user ?.linkWithCredential(credentialForLinking) ?.await() @@ -480,7 +472,7 @@ internal suspend fun AuthFlowScope.signInAndLinkWithCredential( val result = if (canUpgradeAnonymous(config, auth) || canLinkCredential(config, auth)) { auth.currentUser?.linkWithCredential(credential)?.await() } else { - signInOrReauth(credential)?.let { linkPendingAccountCredential(it) } + signInOrReauth(credential)?.let { linkPendingAccountCredential(it, provider?.providerId) } } // signInOrReauth returns null in reauth mode (Task has no AuthResult). // Reconstruct success state from the now-reauthenticated current user. @@ -565,6 +557,7 @@ internal suspend fun AuthFlowScope.sendSignInLinkToEmail( ) { try { emit(AuthState.Loading(config.stringProvider.loadingSendingEmailLink)) + requirePendingLinkAddress(credentialForLinking, email) // Get anonymousUserId if can upgrade anonymously else default to empty string. // NOTE: check for empty string instead of null to validate anonymous user ID matches diff --git a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/OAuthProvider+FirebaseAuthUI.kt b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/OAuthProvider+FirebaseAuthUI.kt index 3b3c318d9..fb28fce1b 100644 --- a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/OAuthProvider+FirebaseAuthUI.kt +++ b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/OAuthProvider+FirebaseAuthUI.kt @@ -126,7 +126,7 @@ internal suspend fun AuthFlowScope.signInWithProvider( val authResult = if (isAnonymousUpgrade || config.isReauthenticationMode) { signInResult } else { - signInResult?.let { linkPendingAccountCredential(it) } + signInResult?.let { linkPendingAccountCredential(it, provider.providerId) } } // Extract OAuth credential and complete sign-in diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt b/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt index 4f5b8ce8d..86af9022e 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt +++ b/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt @@ -50,6 +50,7 @@ import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.snapshotFlow import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment @@ -73,6 +74,7 @@ import com.firebase.ui.auth.configuration.DefaultAuthContentTransform import com.firebase.ui.auth.configuration.DefaultAuthPredictivePopContentTransform import com.firebase.ui.auth.configuration.MfaConfiguration import com.firebase.ui.auth.configuration.auth_provider.AuthProvider +import com.firebase.ui.auth.configuration.auth_provider.Provider import com.firebase.ui.auth.configuration.auth_provider.findAccountOwnerSignInMethod import com.firebase.ui.auth.configuration.auth_provider.rememberAnonymousSignInHandler import com.firebase.ui.auth.configuration.auth_provider.rememberGoogleSignInHandler @@ -331,6 +333,19 @@ fun FirebaseAuthScreen( lastSignInPreference.value = SignInPreferenceManager.getLastSignIn(context) } + // A collided Facebook or Google sign-in saved its credential for a later email-link sign-in. + // Once the recovery's link ends, whether linked another way or given up, that copy must go, + // or the next email-link sign-in on this device would try to link it. + LaunchedEffect(pendingAccountLink) { + var previous: PendingAccountLink? = null + snapshotFlow { pendingAccountLink.value }.collect { current -> + if (previous != null && current == null) { + EmailLinkPersistenceManager.clearCredentialForLinking(context) + } + previous = current + } + } + val emailProvider = configuration.providers.filterIsInstance().firstOrNull() val logoAsset = configuration.logo val onOuterProviderSelected = hostScope.rememberOnProviderSelected( @@ -923,8 +938,13 @@ fun FirebaseAuthScreen( if (credential == null || authUI.auth.currentUser != null) { return if (configuration.isEmailProviderConfigured()) { { _ -> - pendingAccountLink.value = - credential?.let { PendingAccountLink(it, exception.email) } + pendingAccountLink.value = credential?.let { + PendingAccountLink( + credential = it, + email = exception.email, + ownerProviderIds = setOf(Provider.EMAIL.id), + ) + } navigateToEmailStep(AuthRoute.Email.SignIn(), exception.email) } } else { @@ -942,7 +962,11 @@ fun FirebaseAuthScreen( if (owners.isEmpty()) return null return { _ -> - pendingAccountLink.value = PendingAccountLink(credential, exception.email) + pendingAccountLink.value = PendingAccountLink( + credential = credential, + email = exception.email, + ownerProviderIds = owners.map { it.providerId }.toSet(), + ) coroutineScope.launch { val ownerSignInMethod = exception.email?.let { email -> hostScope.findAccountOwnerSignInMethod(email, owners) diff --git a/auth/src/main/java/com/firebase/ui/auth/util/EmailLinkPersistenceManager.kt b/auth/src/main/java/com/firebase/ui/auth/util/EmailLinkPersistenceManager.kt index 9cb080ca2..35163fd4e 100644 --- a/auth/src/main/java/com/firebase/ui/auth/util/EmailLinkPersistenceManager.kt +++ b/auth/src/main/java/com/firebase/ui/auth/util/EmailLinkPersistenceManager.kt @@ -45,6 +45,23 @@ object EmailLinkPersistenceManager { * Default instance. */ internal val default: PersistenceManager = DefaultPersistenceManager() + + /** + * Forgets a provider credential saved by [PersistenceManager.saveCredentialForLinking], + * leaving any email-link session in place. + * + * A provider sign-in that collides saves its credential so a later email-link sign-in can link + * it. Once the account-linking recovery has linked that credential another way, or the flow + * has given up on it, the saved copy must go: otherwise the next email-link sign-in on this + * device, by anyone, tries to link it. + */ + internal suspend fun clearCredentialForLinking(context: Context) { + context.dataStore.edit { prefs -> + prefs.remove(AuthProvider.Email.KEY_PROVIDER) + prefs.remove(AuthProvider.Email.KEY_IDP_TOKEN) + prefs.remove(AuthProvider.Email.KEY_IDP_SECRET) + } + } /** * The default implementation of [PersistenceManager] that uses DataStore. diff --git a/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt b/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt index 5ae6a707a..0e336bcd7 100644 --- a/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt +++ b/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt @@ -32,6 +32,8 @@ import com.google.common.truth.Truth.assertThat import com.google.firebase.FirebaseApp import com.google.firebase.FirebaseNetworkException import com.google.firebase.FirebaseOptions +import com.google.android.gms.tasks.TaskCompletionSource +import com.google.firebase.auth.AdditionalUserInfo import com.google.firebase.auth.AuthCredential import com.google.firebase.auth.AuthResult import com.google.firebase.auth.EmailAuthProvider @@ -43,6 +45,7 @@ import com.google.firebase.auth.OAuthCredential import com.google.firebase.auth.OAuthProvider import com.google.firebase.auth.SignInMethodQueryResult import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Assert.assertThrows @@ -114,7 +117,7 @@ class AccountLinkingTest { `when`(user.linkWithCredential(pendingCredential)).thenReturn(Tasks.forResult(linked)) val scope = scopeWithPendingLink() - val result = scope.linkPendingAccountCredential(signIn) + val result = scope.linkPendingAccountCredential(signIn, GOOGLE) assertThat(result).isSameInstanceAs(linked) assertThat(scope.pendingAccountLink.value).isNull() @@ -128,7 +131,7 @@ class AccountLinkingTest { `when`(user.linkWithCredential(pendingCredential)) .thenReturn(Tasks.forResult(mock(AuthResult::class.java))) - scopeWithPendingLink().linkPendingAccountCredential(signIn) + scopeWithPendingLink().linkPendingAccountCredential(signIn, GOOGLE) verify(user).linkWithCredential(pendingCredential) } @@ -144,7 +147,7 @@ class AccountLinkingTest { val scope = scopeWithPendingLink() val error = assertThrows(AuthException.AccountLinkingRequiredException::class.java) { - kotlinx.coroutines.runBlocking { scope.linkPendingAccountCredential(signIn) } + kotlinx.coroutines.runBlocking { scope.linkPendingAccountCredential(signIn, GOOGLE) } } assertThat(error.message).isEqualTo(stringProvider.errorUserMismatch) @@ -165,7 +168,7 @@ class AccountLinkingTest { val scope = scopeWithPendingLink() assertThrows(AuthException.NetworkException::class.java) { - kotlinx.coroutines.runBlocking { scope.linkPendingAccountCredential(signIn) } + kotlinx.coroutines.runBlocking { scope.linkPendingAccountCredential(signIn, GOOGLE) } } assertThat(scope.pendingAccountLink.value).isNull() @@ -190,7 +193,7 @@ class AccountLinkingTest { val scope = scopeWithPendingLink() val error = assertThrows(AuthException.UnknownException::class.java) { - kotlinx.coroutines.runBlocking { scope.linkPendingAccountCredential(signIn) } + kotlinx.coroutines.runBlocking { scope.linkPendingAccountCredential(signIn, GOOGLE) } } assertThat(error.message).isEqualTo(stringProvider.unknownErrorRecoveryMessage) @@ -202,17 +205,87 @@ class AccountLinkingTest { val (signIn, user) = signedInAs(OWNER_EMAIL) val scope = FirebaseAuthUI.create(firebaseApp, mockAuth).recordingScope(config(), mutableListOf()) - assertThat(scope.linkPendingAccountCredential(signIn)).isSameInstanceAs(signIn) + assertThat(scope.linkPendingAccountCredential(signIn, GOOGLE)).isSameInstanceAs(signIn) verify(user, never()).linkWithCredential(any()) } + /** + * The method picker the recovery leaves the user on still shows phone, which cannot hold the + * address. Signing in with it is the user going another way: it must not be refused, and the + * link the recovery was holding is dropped rather than left to block every sign-in after. + */ + @Test + fun `a sign-in through a provider the recovery did not offer drops the link and stands`() = + runTest { + val (signIn, user) = signedInAs(null) + val scope = scopeWithPendingLink() + + assertThat(scope.linkPendingAccountCredential(signIn, "phone")) + .isSameInstanceAs(signIn) + + assertThat(scope.pendingAccountLink.value).isNull() + verify(user, never()).linkWithCredential(any()) + verify(mockAuth, never()).signOut() + } + + /** + * A Google or OAuth account at another address may have no Firebase user yet, so signing in + * with it creates one. Undoing the sign-in must not leave that empty account behind. + */ + @Test + fun `a different account the sign-in only just created is deleted, not left behind`() = + runTest { + val (signIn, user) = signedInAs("someone-else@example.com") + val info = mock(AdditionalUserInfo::class.java) + `when`(info.isNewUser).thenReturn(true) + `when`(signIn.additionalUserInfo).thenReturn(info) + `when`(user.delete()).thenReturn(Tasks.forResult(null)) + val scope = scopeWithPendingLink() + + assertThrows(AuthException.AccountLinkingRequiredException::class.java) { + kotlinx.coroutines.runBlocking { scope.linkPendingAccountCredential(signIn, GOOGLE) } + } + + verify(user).delete() + verify(mockAuth).signOut() + } + + /** An existing account at another address is only signed out of, never deleted. */ + @Test + fun `a different account that already existed is signed out of, not deleted`() = runTest { + val (signIn, user) = signedInAs("someone-else@example.com") + val scope = scopeWithPendingLink() + + assertThrows(AuthException.AccountLinkingRequiredException::class.java) { + kotlinx.coroutines.runBlocking { scope.linkPendingAccountCredential(signIn, GOOGLE) } + } + + verify(user, never()).delete() + verify(mockAuth).signOut() + } + + /** Cancelled mid-link, the sign-in is undone like any other failed link. */ + @Test + fun `a link that is cancelled signs back out`() = runTest { + val (signIn, user) = signedInAs(OWNER_EMAIL) + `when`(user.linkWithCredential(pendingCredential)).thenReturn(TaskCompletionSource().task) + val scope = scopeWithPendingLink() + + val job = launch { scope.linkPendingAccountCredential(signIn, GOOGLE) } + testScheduler.advanceUntilIdle() + job.cancel() + job.join() + + verify(mockAuth).signOut() + } + /** A reauthentication proves who the user is; it is never the account-linking recovery. */ @Test fun `a reauthentication never links`() = runTest { val (signIn, user) = signedInAs(OWNER_EMAIL) val scope = scopeWithPendingLink(config(isReauthenticationMode = true)) - assertThat(scope.linkPendingAccountCredential(signIn)).isSameInstanceAs(signIn) + assertThat(scope.linkPendingAccountCredential(signIn, GOOGLE)).isSameInstanceAs(signIn) verify(user, never()).linkWithCredential(any()) } @@ -251,7 +324,7 @@ class AccountLinkingTest { `when`(user.linkWithCredential(pendingCredential)).thenReturn(Tasks.forResult(linked)) val instance = FirebaseAuthUI.create(firebaseApp, mockAuth) val scope = instance.flowScope(config()) - scope.pendingAccountLink.value = PendingAccountLink(pendingCredential, OWNER_EMAIL) + scope.pendingAccountLink.value = PendingAccountLink(pendingCredential, OWNER_EMAIL, OWNER_PROVIDERS) scope.signInWithGoogle( context = applicationContext, @@ -280,7 +353,7 @@ class AccountLinkingTest { val github = AuthProvider.Github(customParameters = emptyMap()) val instance = FirebaseAuthUI.create(firebaseApp, mockAuth) val scope = instance.flowScope(config(github)) - scope.pendingAccountLink.value = PendingAccountLink(pendingCredential, OWNER_EMAIL) + scope.pendingAccountLink.value = PendingAccountLink(pendingCredential, OWNER_EMAIL, OWNER_PROVIDERS) scope.signInWithProvider(applicationContext, mock(Activity::class.java), github) @@ -335,6 +408,52 @@ class AccountLinkingTest { verify(user).linkWithCredential(pendingCredential) } + /** + * The email step is the recovery's way back in for a password account, so it gets the same + * all-or-nothing link as the provider flows: a failed link must not leave the user signed in. + */ + @Test + fun `the email step signs back out when the recovery's link fails`() = runTest { + val (signIn, user) = signedInAs(OWNER_EMAIL) + `when`(mockAuth.signInWithEmailAndPassword(OWNER_EMAIL, PASSWORD)).thenReturn(Tasks.forResult(signIn)) + `when`(user.linkWithCredential(pendingCredential)) + .thenReturn(Tasks.forException(FirebaseNetworkException("offline"))) + val scope = scopeWithPendingLink(config(credentialManager = false)) + + assertThrows(AuthException.NetworkException::class.java) { + kotlinx.coroutines.runBlocking { + scope.signInWithEmailAndPassword( + context = applicationContext, + email = OWNER_EMAIL, + password = PASSWORD, + credentialForLinking = pendingCredential, + ) + } + } + + verify(mockAuth).signOut() + } + + /** The email-link step's address is just as editable, and the link would land on it. */ + @Test + fun `the email-link step refuses to send to an address other than the account's`() = runTest { + val scope = scopeWithPendingLink() + + val error = assertThrows(AuthException.AccountLinkingRequiredException::class.java) { + kotlinx.coroutines.runBlocking { + scope.sendSignInLinkToEmail( + context = applicationContext, + provider = emailProvider, + email = "someone-else@example.com", + credentialForLinking = pendingCredential, + ) + } + } + + assertThat(error.message).isEqualTo(stringProvider.errorUserMismatch) + verify(mockAuth, never()).sendSignInLinkToEmail(any(), any()) + } + /** * `EmailAuthScreen` is public, and a host composing it directly may pass a credential of its * own. That is not the recovery's, so there is no address to hold it to. @@ -461,9 +580,9 @@ class AccountLinkingTest { private fun scopeWithPendingLink(configuration: AuthUIConfiguration = config()) = FirebaseAuthUI.create(firebaseApp, mockAuth) .recordingScope(configuration, mutableListOf()) - .also { it.pendingAccountLink.value = PendingAccountLink(pendingCredential, OWNER_EMAIL) } + .also { it.pendingAccountLink.value = PendingAccountLink(pendingCredential, OWNER_EMAIL, OWNER_PROVIDERS) } - private fun signedInAs(email: String): Pair { + private fun signedInAs(email: String?): Pair { val user = mock(FirebaseUser::class.java) `when`(user.email).thenReturn(email) `when`(user.uid).thenReturn("owner-uid") @@ -480,6 +599,8 @@ class AccountLinkingTest { private companion object { const val OWNER_EMAIL = "owner@example.com" + const val GOOGLE = "google.com" + val OWNER_PROVIDERS = setOf("password", GOOGLE, "github.com") const val PASSWORD = "correct-horse-battery" } } diff --git a/auth/src/test/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreenEmailRecoveryTest.kt b/auth/src/test/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreenEmailRecoveryTest.kt index 8371c54b1..2c9b9f0ce 100644 --- a/auth/src/test/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreenEmailRecoveryTest.kt +++ b/auth/src/test/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreenEmailRecoveryTest.kt @@ -77,6 +77,7 @@ import org.mockito.Mockito.mock import org.mockito.Mockito.verify import org.mockito.Mockito.`when` import org.mockito.kotlin.any +import com.firebase.ui.auth.util.EmailLinkPersistenceManager import org.mockito.kotlin.eq import kotlinx.coroutines.runBlocking import androidx.credentials.CredentialManager @@ -886,10 +887,20 @@ class FirebaseAuthScreenEmailRecoveryTest { * firebase/FirebaseUI-Android#2550, the half the crash guard left: a Facebook sign-in hit an * account Google created. With Google the only other provider that can hold the account, the * recovery opens it, and the Facebook credential is linked to the account the user signs in - * to before the flow reports success. + * to before the flow reports success. The copy of the Facebook credential the collision saved + * for a later email-link sign-in is then forgotten, so that sign-in cannot try to link it again. */ @Test fun `an account that needs linking opens the lone other provider and links the credential`() { + runBlocking { + EmailLinkPersistenceManager.default.saveEmail(applicationContext, OTHER_EMAIL, "session", null) + EmailLinkPersistenceManager.default.saveCredentialForLinking( + applicationContext, + providerType = "facebook.com", + idToken = null, + accessToken = "facebook-access-token", + ) + } val facebookCredential = facebookCredential() val googleCredential = mock(AuthCredential::class.java) val credentialManager = mock(AuthProvider.Google.CredentialManagerProvider::class.java) @@ -921,6 +932,11 @@ class FirebaseAuthScreenEmailRecoveryTest { verify(owner.user).linkWithCredential(facebookCredential) composeTestRule.onNodeWithTag(AUTHENTICATED_TAG).assertIsDisplayed() + val saved = runBlocking { + EmailLinkPersistenceManager.default.retrieveSessionRecord(applicationContext) + } + assertThat(saved?.email).isEqualTo(OTHER_EMAIL) + assertThat(saved?.credentialForLinking).isNull() } /** @@ -997,6 +1013,8 @@ class FirebaseAuthScreenEmailRecoveryTest { fun `signing in after an account-linking recovery links the credential the failure carried`() { val credential = mock(AuthCredential::class.java) val signedInUser = mock(FirebaseUser::class.java) + // The account the recovery named: the link is held to its address. + `when`(signedInUser.email).thenReturn(OTHER_EMAIL) val signInResult = mock(AuthResult::class.java) `when`(signInResult.user).thenReturn(signedInUser) `when`(mockAuth.signInWithEmailAndPassword(OTHER_EMAIL, PASSWORD)) From 6a24dc03b9fb4d034347360d38edcb1f0899c299 Mon Sep 17 00:00:00 2001 From: Codefarmer Date: Fri, 6 Nov 2026 16:24:06 +0100 Subject: [PATCH 4/6] fix(auth): close the remaining gaps in the account-linking recovery - A mismatch undone while cancelled still signs out. - An email-link sign-in counts as the Email provider, so it finishes the recovery's link instead of dropping it. - A linking error with no credential keeps the link already pending. - The credential saved for email-link sign-in is forgotten where the link resolves, not only from the screen. - No provider recovery when the collision names no address. - The email step merges the linked provider's profile again. --- .../auth_provider/AccountLinking.kt | 41 ++++++--- .../EmailAuthProvider+FirebaseAuthUI.kt | 15 ++- .../ui/auth/ui/screens/FirebaseAuthScreen.kt | 12 ++- .../auth_provider/AccountLinkingTest.kt | 91 +++++++++++++++++++ .../FirebaseAuthScreenEmailRecoveryTest.kt | 49 ++++++++++ 5 files changed, 191 insertions(+), 17 deletions(-) diff --git a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinking.kt b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinking.kt index 0ad6d84fa..5383db3ea 100644 --- a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinking.kt +++ b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinking.kt @@ -16,6 +16,7 @@ package com.firebase.ui.auth.configuration.auth_provider import com.firebase.ui.auth.AuthException import com.firebase.ui.auth.AuthFlowScope +import com.firebase.ui.auth.util.EmailLinkPersistenceManager import com.google.firebase.auth.AuthCredential import com.google.firebase.auth.AuthResult import kotlinx.coroutines.CancellationException @@ -53,23 +54,25 @@ internal suspend fun AuthFlowScope.linkPendingAccountCredential( val pending = pendingAccountLink.value ?: return result if (config.isReauthenticationMode) return result if (providerId == null || providerId !in pending.ownerProviderIds) { - pendingAccountLink.value = null + forgetPendingLink() return result } val user = result.user ?: return result val expectedEmail = pending.email if (expectedEmail != null && !expectedEmail.equals(user.email, ignoreCase = true)) { - if (result.additionalUserInfo?.isNewUser == true) { - try { - user.delete().await() - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - // Signing out below still undoes the sign-in; only the empty account remains. + // Undone even if the flow is cancelled meanwhile: stopping halfway would leave the user + // signed in to the wrong account. + withContext(NonCancellable) { + if (result.additionalUserInfo?.isNewUser == true) { + try { + user.delete().await() + } catch (e: Exception) { + // Signing out below still undoes the sign-in; only the empty account remains. + } } + auth.signOut() } - auth.signOut() throw pendingLinkMismatch() } @@ -79,8 +82,8 @@ internal suspend fun AuthFlowScope.linkPendingAccountCredential( withContext(NonCancellable) { auth.signOut() } throw e } catch (e: Exception) { - pendingAccountLink.value = null auth.signOut() + forgetPendingLink() throw when (val mapped = AuthException.from(e, config.stringProvider)) { // Firebase reports some link failures as a collision, but there is no further account // to recover to: offering the linking recovery again would loop. @@ -92,10 +95,26 @@ internal suspend fun AuthFlowScope.linkPendingAccountCredential( else -> mapped } } - pendingAccountLink.value = null + forgetPendingLink() return linked } +/** + * Ends the pending link, and forgets the copy of its credential a collided Facebook or Google + * sign-in saved for a later email-link sign-in. Done here, where the link resolves, rather than by + * the screen observing it: a host may dispose the screen as soon as the sign-in succeeds. + */ +private suspend fun AuthFlowScope.forgetPendingLink() { + pendingAccountLink.value = null + withContext(NonCancellable) { + try { + EmailLinkPersistenceManager.clearCredentialForLinking(auth.app.applicationContext) + } catch (e: Exception) { + // Best effort: the screen also clears it when the pending link ends. + } + } +} + /** * Refuses an email step about to sign in, or send a sign-in link, to an address other than the * one the account-linking recovery is finishing. The step is prefilled with that address but the diff --git a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/EmailAuthProvider+FirebaseAuthUI.kt b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/EmailAuthProvider+FirebaseAuthUI.kt index b2be2c060..9d9993f62 100644 --- a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/EmailAuthProvider+FirebaseAuthUI.kt +++ b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/EmailAuthProvider+FirebaseAuthUI.kt @@ -281,8 +281,14 @@ internal suspend fun AuthFlowScope.signInWithEmailAndPassword( auth.signInWithEmailAndPassword(email, password).await() .let { result -> if (isPendingLink) { - // The account-linking recovery's credential: linked all or nothing. + // The account-linking recovery's credential: linked all or nothing, then + // its profile merged in as a host's own credential's is. linkPendingAccountCredential(result, EmailAuthProvider.PROVIDER_ID) + .also { linked -> + linked.user?.let { user -> + mergeProfile(auth, user.displayName, user.photoUrl) + } + } } else if (credentialForLinking != null) { // A host's own credential to link, linked after sign-in as before. val linkResult = result.user @@ -703,7 +709,7 @@ internal suspend fun AuthFlowScope.signInWithEmailLink( val result = if (storedCredentialForLink == null) { // Normal Flow: Just sign in with email link - handleEmailLinkNormalFlow(emailLinkCredential) + handleEmailLinkNormalFlow(emailLinkCredential, provider) } else { // Linking Flow: Sign in with email link, then link the social credential handleEmailLinkCredentialLinkingFlow( @@ -777,8 +783,11 @@ private suspend fun AuthFlowScope.handleDifferentDeviceErrorFlow( private suspend fun AuthFlowScope.handleEmailLinkNormalFlow( emailLinkCredential: AuthCredential, + provider: AuthProvider.Email, ): AuthResult? { - return signInAndLinkWithCredential(emailLinkCredential) + // Passing the provider is what lets an email-link sign-in finish the account-linking + // recovery when the account it names is an email-link one. + return signInAndLinkWithCredential(emailLinkCredential, provider) } private suspend fun AuthFlowScope.handleEmailLinkCredentialLinkingFlow( diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt b/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt index 86af9022e..27a535a2b 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt +++ b/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt @@ -938,9 +938,11 @@ fun FirebaseAuthScreen( if (credential == null || authUI.auth.currentUser != null) { return if (configuration.isEmailProviderConfigured()) { { _ -> - pendingAccountLink.value = credential?.let { - PendingAccountLink( - credential = it, + // No credential (such as "Sign up" tried on the recovery's own email + // step) is no reason to drop the link that is already pending. + if (credential != null) { + pendingAccountLink.value = PendingAccountLink( + credential = credential, email = exception.email, ownerProviderIds = setOf(Provider.EMAIL.id), ) @@ -952,6 +954,10 @@ fun FirebaseAuthScreen( } } + // Without the address there is nothing to hold the owner's account to, so any + // account the user signed in to would get the credential. + if (exception.email.isNullOrEmpty()) return null + // Providers that can hold the existing account: not the one that just collided, // and not phone or anonymous sign-in, which have no address to match. val owners = configuration.providers.filter { provider -> diff --git a/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt b/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt index 0e336bcd7..b53bb860b 100644 --- a/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt +++ b/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt @@ -27,6 +27,9 @@ import com.firebase.ui.auth.configuration.authUIConfiguration import com.firebase.ui.auth.configuration.string_provider.DefaultAuthUIStringProvider import com.firebase.ui.auth.flowScope import com.firebase.ui.auth.recordingScope +import com.firebase.ui.auth.util.EmailLinkPersistenceManager +import com.firebase.ui.auth.util.MockPersistenceManager +import com.google.firebase.auth.ActionCodeSettings import com.google.android.gms.tasks.Tasks import com.google.common.truth.Truth.assertThat import com.google.firebase.FirebaseApp @@ -279,6 +282,94 @@ class AccountLinkingTest { verify(mockAuth).signOut() } + /** Cancelled while undoing a mismatch, the user must still not stay on the wrong account. */ + @Test + fun `a mismatch cancelled while deleting the new account still signs out`() = runTest { + val (signIn, user) = signedInAs("someone-else@example.com") + val info = mock(AdditionalUserInfo::class.java) + `when`(info.isNewUser).thenReturn(true) + `when`(signIn.additionalUserInfo).thenReturn(info) + val deletion = TaskCompletionSource() + `when`(user.delete()).thenReturn(deletion.task) + val scope = scopeWithPendingLink() + + // The mismatch error still follows once the undo finishes; it is not what is under test. + val job = launch { runCatching { scope.linkPendingAccountCredential(signIn, GOOGLE) } } + testScheduler.advanceUntilIdle() + job.cancel() + deletion.setResult(null) + job.join() + + verify(mockAuth).signOut() + } + + /** + * Where the link resolves, the copy of the credential a collided sign-in saved for a later + * email-link sign-in goes too. Not left to the screen: a host may dispose it on success. + */ + @Test + fun `a finished link forgets the credential saved for email-link sign-in`() = runTest { + `when`(mockAuth.app).thenReturn(firebaseApp) + val saved = EmailLinkPersistenceManager.default + saved.saveEmail(applicationContext, OWNER_EMAIL, "session", null) + saved.saveCredentialForLinking(applicationContext, "facebook.com", null, "facebook-token") + val (signIn, user) = signedInAs(OWNER_EMAIL) + `when`(user.linkWithCredential(pendingCredential)) + .thenReturn(Tasks.forResult(mock(AuthResult::class.java))) + + scopeWithPendingLink().linkPendingAccountCredential(signIn, GOOGLE) + + val record = saved.retrieveSessionRecord(applicationContext) + assertThat(record?.email).isEqualTo(OWNER_EMAIL) + assertThat(record?.credentialForLinking).isNull() + } + + /** + * When the account is an email-link one, finishing that sign-in is the recovery's way back in, + * so it must count as the Email provider rather than as a sign-in the recovery did not offer. + */ + @Test + fun `an email-link sign-in finishes the recovery's link`() = runTest { + val (signIn, user) = signedInAs(OWNER_EMAIL) + `when`(mockAuth.isSignInWithEmailLink(any())).thenReturn(true) + `when`(mockAuth.signInWithCredential(any())).thenReturn(Tasks.forResult(signIn)) + `when`(user.linkWithCredential(pendingCredential)) + .thenReturn(Tasks.forResult(mock(AuthResult::class.java))) + val linkProvider = AuthProvider.Email( + isEmailLinkSignInEnabled = true, + emailLinkActionCodeSettings = ActionCodeSettings.newBuilder() + .setUrl("https://example.com") + .setHandleCodeInApp(true) + .build(), + passwordValidationRules = emptyList(), + ) + val configuration = authUIConfiguration { + context = applicationContext + providers { provider(linkProvider) } + } + val persistence = MockPersistenceManager().apply { + setSessionRecord( + EmailLinkPersistenceManager.SessionRecord( + sessionId = "session123", + email = OWNER_EMAIL, + anonymousUserId = null, + credentialForLinking = null, + ) + ) + } + + scopeWithPendingLink(configuration).signInWithEmailLink( + context = applicationContext, + provider = linkProvider, + email = OWNER_EMAIL, + emailLink = "https://example.com/__/auth/action?apiKey=key&mode=signIn" + + "&oobCode=code&continueUrl=https://example.com?ui_sid=session123", + persistenceManager = persistence, + ) + + verify(user).linkWithCredential(pendingCredential) + } + /** A reauthentication proves who the user is; it is never the account-linking recovery. */ @Test fun `a reauthentication never links`() = runTest { diff --git a/auth/src/test/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreenEmailRecoveryTest.kt b/auth/src/test/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreenEmailRecoveryTest.kt index 2c9b9f0ce..f6479abd8 100644 --- a/auth/src/test/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreenEmailRecoveryTest.kt +++ b/auth/src/test/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreenEmailRecoveryTest.kt @@ -985,6 +985,55 @@ class FirebaseAuthScreenEmailRecoveryTest { composeTestRule.onNodeWithText(OTHER_EMAIL).assertIsDisplayed() } + /** + * "Sign up" on the recovery's own email step, with the address already taken, raises the + * linking error again but with no credential of its own. That must not drop the one pending: + * signing in afterwards still links it. + */ + @Test + fun `a linking error with no credential keeps the link already pending`() { + val facebookCredential = facebookCredential() + val owner = accountOwner() + `when`(mockAuth.signInWithEmailAndPassword(OTHER_EMAIL, PASSWORD)) + .thenReturn(Tasks.forResult(owner.signIn)) + start(configuration = emailAndPhoneConfiguration()) + recoverFrom(accountLinkingRequired(facebookCredential)) + + recoverFrom( + AuthException.AccountLinkingRequiredException( + message = "an account already exists with this address", + email = OTHER_EMAIL, + credential = null, + ) + ) + signInWithPassword() + + verify(owner.user).linkWithCredential(facebookCredential) + } + + /** Without the address there is nothing to hold the owner's account to. */ + @Test + fun `no provider recovery is offered when the collision names no address`() { + start(configuration = emailAndGoogleConfiguration()) + + composeTestRule.runOnIdle { + authUI.updateAuthState( + AuthState.Error( + AuthException.AccountLinkingRequiredException( + message = "an account already exists", + email = null, + credential = facebookCredential(), + ) + ) + ) + } + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithText(stringProvider.errorDialogTitle).assertExists() + composeTestRule.onNodeWithTag(FirebaseAuthTestTags.ErrorRecovery.RETRY_BUTTON) + .assertDoesNotExist() + } + /** Nothing else can hold the account, so there is no sign-in to send the user to. */ @Test fun `no recovery is offered when the colliding provider is the only one that can hold the account`() { From 93de3c58bd66fee7c3fdd95c2413227435f528a3 Mon Sep 17 00:00:00 2001 From: Codefarmer Date: Fri, 6 Nov 2026 16:29:52 +0100 Subject: [PATCH 5/6] fix(auth): keep the account-linking recovery through recreation, lookups and auto-select - The pending link is saveable, so an Activity recreated while the owner's sign-in UI is open still finishes the link. - The opt-in owner lookup shows loading, so no second sign-in can start while it runs. - Google auto-select is off while a link is pending, so a wrong pick is not handed back again. --- .../GoogleAuthProvider+FirebaseAuthUI.kt | 10 ++- .../ui/auth/ui/screens/FirebaseAuthScreen.kt | 52 +++++++++++++-- .../auth_provider/AccountLinkingTest.kt | 41 ++++++++++++ .../FirebaseAuthScreenEmailRecoveryTest.kt | 66 ++++++++++++++++++- 4 files changed, 161 insertions(+), 8 deletions(-) diff --git a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/GoogleAuthProvider+FirebaseAuthUI.kt b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/GoogleAuthProvider+FirebaseAuthUI.kt index 970cb3e87..b44131e6f 100644 --- a/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/GoogleAuthProvider+FirebaseAuthUI.kt +++ b/auth/src/main/java/com/firebase/ui/auth/configuration/auth_provider/GoogleAuthProvider+FirebaseAuthUI.kt @@ -77,6 +77,10 @@ internal suspend fun AuthFlowScope.signInWithGoogle( } } + // While the account-linking recovery waits on the account that owns an address, always + // show the chooser: auto-select would pick the same account again after a wrong pick. + val autoSelectEnabled = provider.autoSelectEnabled && pendingAccountLink.value == null + // Try with configured filterByAuthorizedAccounts setting // If default (true), fallback to false if no authorized accounts found // See: https://developer.android.com/identity/sign-in/credential-manager-siwg#siwg-button @@ -88,7 +92,7 @@ internal suspend fun AuthFlowScope.signInWithGoogle( credentialManager = CredentialManager.create(context), serverClientId = provider.serverClientId!!, filterByAuthorizedAccounts = true, - autoSelectEnabled = provider.autoSelectEnabled + autoSelectEnabled = autoSelectEnabled ) } catch (e: NoCredentialException) { // No authorized accounts found, try again with all accounts for sign-up flow @@ -99,7 +103,7 @@ internal suspend fun AuthFlowScope.signInWithGoogle( credentialManager = CredentialManager.create(context), serverClientId = provider.serverClientId!!, filterByAuthorizedAccounts = false, - autoSelectEnabled = provider.autoSelectEnabled + autoSelectEnabled = autoSelectEnabled ) } catch (fallbackException: NoCredentialException) { // Credential Manager doesn't distinguish "no account on device" from @@ -131,7 +135,7 @@ internal suspend fun AuthFlowScope.signInWithGoogle( credentialManager = CredentialManager.create(context), serverClientId = provider.serverClientId!!, filterByAuthorizedAccounts = false, - autoSelectEnabled = provider.autoSelectEnabled + autoSelectEnabled = autoSelectEnabled ) } idTokenFromResult = result.idToken diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt b/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt index 27a535a2b..10d93b281 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt +++ b/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt @@ -51,6 +51,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.snapshotFlow +import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment @@ -125,6 +126,7 @@ import com.firebase.ui.auth.util.EmailLinkPersistenceManager import com.firebase.ui.auth.util.SignInPreferenceManager import com.firebase.ui.auth.util.displayIdentifier import com.firebase.ui.auth.util.getDisplayEmail +import com.google.firebase.auth.AuthCredential import com.google.firebase.auth.EmailAuthProvider import com.google.firebase.auth.AuthResult import com.google.firebase.auth.MultiFactorResolver @@ -205,7 +207,12 @@ fun FirebaseAuthScreen( val hostStateHolder = rememberUpdatedState(rawAuthState) // Shared with the provider flows, which link it once the user signs in to the account that // owns the address. Cleared wherever the flow ends. - val pendingAccountLink = remember { mutableStateOf(null) } + // Saveable: the owner's sign-in opens UI outside the app (Credential Manager, Facebook, a + // browser), and an Activity recreated meanwhile must still have the link to finish. + val pendingAccountLink = rememberSaveable(stateSaver = PendingAccountLinkSaver) { + mutableStateOf(null) + } + val isLookingUpAccountOwner = remember { mutableStateOf(false) } val hostScope = remember(authUI, configuration, hostStateHolder) { hostAuthFlowScope(authUI, configuration, hostStateHolder, pendingAccountLink) } @@ -956,7 +963,8 @@ fun FirebaseAuthScreen( // Without the address there is nothing to hold the owner's account to, so any // account the user signed in to would get the credential. - if (exception.email.isNullOrEmpty()) return null + val ownerEmail = exception.email + if (ownerEmail.isNullOrEmpty()) return null // Providers that can hold the existing account: not the one that just collided, // and not phone or anonymous sign-in, which have no address to match. @@ -974,8 +982,17 @@ fun FirebaseAuthScreen( ownerProviderIds = owners.map { it.providerId }.toSet(), ) coroutineScope.launch { - val ownerSignInMethod = exception.email?.let { email -> - hostScope.findAccountOwnerSignInMethod(email, owners) + // Shown as loading so no other sign-in can start while the lookup runs. + // Not the shared Loading state: the Idle after it would end the link. + val ownerSignInMethod = if (configuration.legacyFetchSignInWithEmail) { + isLookingUpAccountOwner.value = true + try { + hostScope.findAccountOwnerSignInMethod(ownerEmail, owners) + } finally { + isLookingUpAccountOwner.value = false + } + } else { + null } val lone = owners.singleOrNull() when { @@ -1082,6 +1099,8 @@ fun FirebaseAuthScreen( authState is AuthState.Reauthentication.Authenticating if (isLoading && !reauthSlotActive) { LoadingDialog(loadingMessage ?: stringProvider.progressDialogLoading) + } else if (isLookingUpAccountOwner.value) { + LoadingDialog(stringProvider.progressDialogLoading) } } @@ -1095,6 +1114,31 @@ fun FirebaseAuthScreen( * Returns an [AuthRoute] rather than an [AuthRoute.Destination], because a single-provider * configuration names a *flow*; [toKey] is what resolves it to the step to actually push. */ +/** + * Saves a [PendingAccountLink] across Activity recreation. Firebase's [AuthCredential] is + * Parcelable, so the three fields go into the saved state as they are. + */ +private val PendingAccountLinkSaver = listSaver( + save = { link -> + if (link == null) { + emptyList() + } else { + listOf(link.credential, link.email, ArrayList(link.ownerProviderIds)) + } + }, + restore = { saved -> + if (saved.isEmpty()) { + null + } else { + PendingAccountLink( + credential = saved[0] as AuthCredential, + email = saved[1] as String?, + ownerProviderIds = (saved[2] as List<*>).map { it as String }.toSet(), + ) + } + }, +) + internal fun getStartRoute(configuration: AuthUIConfiguration): AuthRoute { if (configuration.isProviderChoiceAlwaysShown || configuration.providers.size != 1) { return AuthRoute.MethodPicker diff --git a/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt b/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt index b53bb860b..90019fd5b 100644 --- a/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt +++ b/auth/src/test/java/com/firebase/ui/auth/configuration/auth_provider/AccountLinkingTest.kt @@ -430,6 +430,47 @@ class AccountLinkingTest { ) } + /** + * After a wrong pick, auto-select would hand back the same Google account every time. While a + * link is pending the chooser is always shown, whatever the provider is configured to do. + */ + @Test + fun `Google auto-select is off while a link is pending`() = runTest { + val credentialManager = mock(AuthProvider.Google.CredentialManagerProvider::class.java) + `when`( + credentialManager.getGoogleCredential( + context = any(), + credentialManager = any(), + serverClientId = any(), + filterByAuthorizedAccounts = any(), + autoSelectEnabled = any(), + ) + ).thenThrow(RuntimeException("stop after the request")) + val autoSelecting = AuthProvider.Google( + scopes = emptyList(), + serverClientId = "test-client-id", + autoSelectEnabled = true, + ) + val scope = FirebaseAuthUI.create(firebaseApp, mockAuth).flowScope(config()) + scope.pendingAccountLink.value = PendingAccountLink(pendingCredential, OWNER_EMAIL, OWNER_PROVIDERS) + + runCatching { + scope.signInWithGoogle( + context = applicationContext, + provider = autoSelecting, + credentialManagerProvider = credentialManager, + ) + } + + verify(credentialManager).getGoogleCredential( + context = any(), + credentialManager = any(), + serverClientId = any(), + filterByAuthorizedAccounts = any(), + autoSelectEnabled = eq(false), + ) + } + /** OAuth providers sign in through Firebase's own activity flow, not the shared credential path. */ @Test fun `an OAuth sign-in during the recovery links before it reports success`() = runTest { diff --git a/auth/src/test/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreenEmailRecoveryTest.kt b/auth/src/test/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreenEmailRecoveryTest.kt index f6479abd8..9f9b928bc 100644 --- a/auth/src/test/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreenEmailRecoveryTest.kt +++ b/auth/src/test/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreenEmailRecoveryTest.kt @@ -77,6 +77,10 @@ import org.mockito.Mockito.mock import org.mockito.Mockito.verify import org.mockito.Mockito.`when` import org.mockito.kotlin.any +import com.google.android.gms.tasks.TaskCompletionSource +import com.google.firebase.auth.SignInMethodQueryResult +import com.google.firebase.auth.FacebookAuthCredential +import com.google.firebase.auth.FacebookAuthProvider import com.firebase.ui.auth.util.EmailLinkPersistenceManager import org.mockito.kotlin.eq import kotlinx.coroutines.runBlocking @@ -1034,6 +1038,63 @@ class FirebaseAuthScreenEmailRecoveryTest { .assertDoesNotExist() } + /** + * The owner's sign-in opens UI outside the app, and the Activity can be recreated meanwhile. + * The pending link has to come back with it, or the owner signs in and nothing is linked. + */ + @Test + fun `the pending link survives an Activity recreation`() { + // A real credential: saving the state parcels it, which a mock cannot do. + val facebookCredential = FacebookAuthProvider.getCredential("facebook-access-token") + val owner = accountOwner() + `when`(mockAuth.signInWithEmailAndPassword(OTHER_EMAIL, PASSWORD)) + .thenReturn(Tasks.forResult(owner.signIn)) + val restorationTester = StateRestorationTester(composeTestRule) + restorationTester.setContent { + FirebaseAuthScreen( + configuration = emailAndPhoneConfiguration(), + authUI = authUI, + onSignInSuccess = {}, + onSignInFailure = {}, + onSignInCancelled = {}, + ) + } + composeTestRule.waitForIdle() + recoverFrom(accountLinkingRequired(facebookCredential)) + + restorationTester.emulateSavedInstanceStateRestore() + composeTestRule.waitForIdle() + signInWithPassword() + + // Parcelled and restored, so an equal credential rather than the same instance. + verify(owner.user).linkWithCredential( + org.mockito.kotlin.argThat { this is FacebookAuthCredential && provider == "facebook.com" } + ) + } + + /** + * The opt-in lookup is a network call. Until it answers, the picker underneath must not take + * another tap, or a second sign-in would race the one the lookup is about to start. + */ + @Test + fun `the owner lookup blocks the screen until it answers`() { + val lookup = TaskCompletionSource() + `when`(mockAuth.fetchSignInMethodsForEmail(OTHER_EMAIL)).thenReturn(lookup.task) + start(configuration = emailAndGoogleConfiguration(legacyLookup = true)) + + recoverFrom(accountLinkingRequired(facebookCredential())) + + composeTestRule.onNodeWithText(stringProvider.progressDialogLoading).assertIsDisplayed() + + val methods = mock(SignInMethodQueryResult::class.java) + `when`(methods.signInMethods).thenReturn(listOf(EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD)) + composeTestRule.runOnIdle { lookup.setResult(methods) } + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithText(stringProvider.progressDialogLoading).assertDoesNotExist() + composeTestRule.onNodeWithTag(FirebaseAuthTestTags.SignIn.EMAIL_FIELD).assertIsDisplayed() + } + /** Nothing else can hold the account, so there is no sign-in to send the user to. */ @Test fun `no recovery is offered when the colliding provider is the only one that can hold the account`() { @@ -1305,7 +1366,9 @@ class FirebaseAuthScreenEmailRecoveryTest { isCredentialManagerEnabled = false } - private fun emailAndGoogleConfiguration(): AuthUIConfiguration = authUIConfiguration { + private fun emailAndGoogleConfiguration( + legacyLookup: Boolean = false, + ): AuthUIConfiguration = authUIConfiguration { context = applicationContext providers { provider( @@ -1318,6 +1381,7 @@ class FirebaseAuthScreenEmailRecoveryTest { provider(googleProvider()) } isCredentialManagerEnabled = false + legacyFetchSignInWithEmail = legacyLookup } private fun githubAndPhoneConfiguration(): AuthUIConfiguration = authUIConfiguration { From fd82ee15c55ffe66dc3814de87d3411078ca23ef Mon Sep 17 00:00:00 2001 From: Codefarmer Date: Mon, 16 Nov 2026 12:57:10 +0100 Subject: [PATCH 6/6] docs(auth): restore the getStartRoute KDoc above its function --- .../ui/auth/ui/screens/FirebaseAuthScreen.kt | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt b/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt index 10d93b281..011352e30 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt +++ b/auth/src/main/java/com/firebase/ui/auth/ui/screens/FirebaseAuthScreen.kt @@ -1107,13 +1107,6 @@ fun FirebaseAuthScreen( } } -/** - * Where the flow starts, from the configuration alone: a single email or phone provider opens - * that flow directly, anything else opens the method picker. - * - * Returns an [AuthRoute] rather than an [AuthRoute.Destination], because a single-provider - * configuration names a *flow*; [toKey] is what resolves it to the step to actually push. - */ /** * Saves a [PendingAccountLink] across Activity recreation. Firebase's [AuthCredential] is * Parcelable, so the three fields go into the saved state as they are. @@ -1139,6 +1132,13 @@ private val PendingAccountLinkSaver = listSaver( }, ) +/** + * Where the flow starts, from the configuration alone: a single email or phone provider opens + * that flow directly, anything else opens the method picker. + * + * Returns an [AuthRoute] rather than an [AuthRoute.Destination], because a single-provider + * configuration names a *flow*; [toKey] is what resolves it to the step to actually push. + */ internal fun getStartRoute(configuration: AuthUIConfiguration): AuthRoute { if (configuration.isProviderChoiceAlwaysShown || configuration.providers.size != 1) { return AuthRoute.MethodPicker