From 3ad4cd880c1b07d5d65776f4ec2225e23a7fea38 Mon Sep 17 00:00:00 2001 From: Ademola Fadumo <48495111+demolaf@users.noreply.github.com> Date: Thu, 5 Nov 2026 14:26:38 +0100 Subject: [PATCH 1/4] fix(auth): finish email-link reauthentication when the link opens after a cold launch AuthPickerContent now completes reauthentication with a link the app opens while EmailLinkReauthView isn't showing, and leaves it to that view while it shows. A reauthentication link already in flight is ignored, so a link delivered to several onOpenURL handlers is used once. --- .../Sources/Services/AuthService.swift | 27 +++++++--- .../Sources/Views/AuthPickerContent.swift | 20 ++++++- .../Sources/Views/EmailLinkReauthScreen.swift | 3 ++ FirebaseSwiftUI/README.md | 2 +- .../EmailLinkDeviceTests.swift | 52 ++++++++++++++++++- .../TestHarness.swift | 4 +- 6 files changed, 94 insertions(+), 14 deletions(-) diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift index b866b6ea06..5a105ce34c 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift @@ -250,6 +250,8 @@ public final class AuthService { /// A sign-in link the app opened while ``EmailLinkScreen`` wasn't showing, handed to it /// when it appears. var incomingEmailLink: URL? + /// Whether ``EmailLinkReauthScreen`` is showing, so it handles reauthentication links itself. + @ObservationIgnored var isShowingEmailLinkReauth = false public var legacySignInRecovery: LegacySignInRecoveryContext? public var suggestedEmailAddress: String? /// How many in-place email forms (an ``EmailAuthScreen`` without a fixed flow) exist on the @@ -702,19 +704,20 @@ public extension AuthService { /// set. A link that is already being handled waits for that attempt and gets its outcome, and /// a link that already signed in is ignored until sign-out. func handleSignInLink(url: URL) async throws { - if isReauthenticating { - try await handleEmailLinkReauthentication(url: url) - return - } - - // A second caller with the same link waits for the first and gets the same outcome. + // A second caller with the same link waits for the first and gets the same outcome, + // whether it signs in or reauthenticates. if let inFlight = emailLinkInFlight, inFlight.url == url { try await inFlight.task.value return } - guard url != lastSignedInEmailLink else { return } - let task = Task { try await self.signInWithOpenedLink(url: url) } + let task: Task + if isReauthenticating { + task = Task { try await self.handleEmailLinkReauthentication(url: url) } + } else { + guard url != lastSignedInEmailLink else { return } + task = Task { try await self.signInWithOpenedLink(url: url) } + } emailLinkInFlight = (url, task) defer { if emailLinkInFlight?.url == url { @@ -804,6 +807,14 @@ public extension AuthService { navigator.push(.emailLink) } + /// Finishes email-link reauthentication with a link the app opened while + /// ``EmailLinkReauthView`` isn't showing, for example after a cold launch. Does nothing for + /// other links, or when that view is showing to handle the link itself. + internal func finishEmailLinkReauthentication(with url: URL) async throws { + guard isReauthenticating, !isShowingEmailLinkReauth, currentUser != nil else { return } + try await handleSignInLink(url: url) + } + private func signInWithEmailLink(email: String, link: String, anonymousUserID: String?) async throws { diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/AuthPickerContent.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/AuthPickerContent.swift index c5b06fa37d..69b9c92a9e 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/AuthPickerContent.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/AuthPickerContent.swift @@ -59,8 +59,12 @@ public struct AuthPickerContent< @Bindable var authService = authService content() // A sign-in link opened while the email-link screen isn't showing, for example on - // another device or after a cold launch, opens that screen to finish signing in. - .onOpenURL { authService.presentEmailLinkScreen(for: $0) } + // another device or after a cold launch, opens that screen to finish signing in. A + // reauthentication link opened while its screen isn't showing finishes it here. + .onOpenURL { url in + authService.presentEmailLinkScreen(for: url) + finishEmailLinkReauthentication(with: url) + } // Reopening the sheet starts from the first screen, not a half-finished pushed one. .sheet(isPresented: $authService.isPresented, onDismiss: { authService.navigator.clear() @@ -194,6 +198,18 @@ public struct AuthPickerContent< ) } + private func finishEmailLinkReauthentication(with url: URL) { + Task { @MainActor in + do { + try await authService.finishEmailLinkReauthentication(with: url) + } catch { + // The sheet holds the error alert, and may be closed after a cold launch. + authService.isPresented = true + reportError(error) + } + } + } + /// Closure for reporting errors from child views private func reportError(_ error: Error) { Task { @MainActor in diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift index 4b2c68f865..940bdd5ae9 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift @@ -111,6 +111,9 @@ public struct EmailLinkReauthScreen: View { guard authService.isEmailSignInLink(url) else { return } handleReauthURL(url) } + // `AuthPickerContent` leaves reauthentication links to this screen while it shows. + .onAppear { authService.isShowingEmailLinkReauth = true } + .onDisappear { authService.isShowingEmailLinkReauth = false } .task { await sendLink() } diff --git a/FirebaseSwiftUI/README.md b/FirebaseSwiftUI/README.md index ad6fb8aaac..8af243b6f5 100644 --- a/FirebaseSwiftUI/README.md +++ b/FirebaseSwiftUI/README.md @@ -279,7 +279,7 @@ When a sensitive operation requires reauthentication, the default views automati - **Email/Password**: Present a sheet prompting the user to enter their password before continuing. -- **Email Link**: Show an alert asking to send a verification email, then present a sheet with instructions to check email. The user taps the link in their email to complete reauthentication. +- **Email Link**: Show an alert asking to send a verification email, then present a sheet with instructions to check email. The user taps the link in their email to complete reauthentication. `AuthPickerView` also completes it when the link opens the app after the sheet closed, for example after a cold launch. - **Phone**: Show an alert explaining verification is needed, then present a sheet for SMS code verification. diff --git a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift index dcfb6e22f4..755996de71 100644 --- a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift +++ b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift @@ -22,9 +22,14 @@ import Testing @MainActor struct EmailLinkDeviceTests { private func makeService(continueURL: String = "https://flutterfire-e2e-tests.firebaseapp.com", - forceSameDevice: Bool = false) async throws -> AuthService { + forceSameDevice: Bool = false, + clearingEmulator: Bool = true) async throws -> AuthService { configureFirebaseIfNeeded() - try await clearAuthEmulatorState() + if clearingEmulator { + try await clearAuthEmulatorState() + } else { + try await isEmulatorRunning() + } let settings = makeEmailLinkActionCodeSettings() settings.url = URL(string: continueURL) return AuthService( @@ -205,6 +210,49 @@ struct EmailLinkDeviceTests { #expect(service.pendingEmailLink == nil) } + @Test + func reauthLinkOpenedAfterColdLaunchFinishesReauthentication() async throws { + let service = try await makeService() + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + let signInLink = try await fetchEmailSignInLinkFromEmulator(email: email) + try await service.handleSignInLink(url: signInLink) + try await waitForStateChange { + service.currentUser?.email?.caseInsensitiveCompare(email) == .orderedSame + } + + try await service.sendEmailSignInLink(email: email, isReauth: true) + var reauthLink = signInLink + try await waitForStateChange(timeout: 15) { + reauthLink != signInLink + } refresh: { + reauthLink = try await fetchEmailSignInLinkFromEmulator(email: email) + } + + // While `EmailLinkReauthView` shows, its own handler takes the link. + service.isShowingEmailLinkReauth = true + try await service.finishEmailLinkReauthentication(with: reauthLink) + #expect(service.isReauthenticating) + service.isShowingEmailLinkReauth = false + + // A cold launch starts a new service with the reauthentication state kept in storage. + let relaunched = try await makeService(clearingEmulator: false) + try await waitForStateChange { + relaunched.currentUser?.email?.caseInsensitiveCompare(email) == .orderedSame + } + #expect(relaunched.isReauthenticating) + + // `AuthPickerContent` may pass the same link more than once. + let link = reauthLink + let first = Task { try await relaunched.finishEmailLinkReauthentication(with: link) } + let second = Task { try await relaunched.finishEmailLinkReauthentication(with: link) } + try await first.value + try await second.value + + #expect(!relaunched.isReauthenticating) + try await relaunched.signOut() + } + @Test func openedLinkPresentsEmailLinkScreen() throws { configureFirebaseIfNeeded() diff --git a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/TestHarness.swift b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/TestHarness.swift index 0cd0a14f97..7dcf06c843 100644 --- a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/TestHarness.swift +++ b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/TestHarness.swift @@ -66,7 +66,8 @@ func createEmail() -> String { @MainActor func waitForStateChange(timeout: TimeInterval = 10.0, - condition: @escaping () -> Bool) async throws { + condition: @escaping () -> Bool, + refresh: () async throws -> Void = {}) async throws { let startTime = Date() while !condition() { @@ -75,6 +76,7 @@ func waitForStateChange(timeout: TimeInterval = 10.0, } try await Task.sleep(nanoseconds: 50_000_000) // 50ms + try await refresh() } } From dfc84b3b2d78692d1828f241265f4362c68bf434 Mon Sep 17 00:00:00 2001 From: Ademola Fadumo <48495111+demolaf@users.noreply.github.com> Date: Thu, 5 Nov 2026 14:49:04 +0100 Subject: [PATCH 2/4] fix(auth): finish email-link reauthentication only once the link is handled EmailLinkReauthView no longer resumes the waiting action when a second tap of the link returns while the first is still in flight. The email-link tests reset stored reauthentication state before each test, and the README notes the user retries the action after a cold-launch reauthentication. --- .../Sources/Views/EmailLinkReauthScreen.swift | 2 ++ FirebaseSwiftUI/README.md | 2 +- .../FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift | 6 ++++++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift index 940bdd5ae9..f39e1ba808 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift @@ -140,6 +140,8 @@ public struct EmailLinkReauthScreen: View { Task { do { try await authService.handleSignInLink(url: url) + // The URL wasn't a sign-in link, so reauthentication isn't finished. + guard !authService.isReauthenticating else { return } coordinator.reauthCompleted() } catch let AuthServiceError.multiFactorReauthenticationRequired(mfaRequired) { self.mfaRequired = mfaRequired diff --git a/FirebaseSwiftUI/README.md b/FirebaseSwiftUI/README.md index 8af243b6f5..2da8e5306d 100644 --- a/FirebaseSwiftUI/README.md +++ b/FirebaseSwiftUI/README.md @@ -279,7 +279,7 @@ When a sensitive operation requires reauthentication, the default views automati - **Email/Password**: Present a sheet prompting the user to enter their password before continuing. -- **Email Link**: Show an alert asking to send a verification email, then present a sheet with instructions to check email. The user taps the link in their email to complete reauthentication. `AuthPickerView` also completes it when the link opens the app after the sheet closed, for example after a cold launch. +- **Email Link**: Show an alert asking to send a verification email, then present a sheet with instructions to check email. The user taps the link in their email to complete reauthentication. `AuthPickerView` also completes it when the link opens the app after the sheet closed, for example after a cold launch. The action that asked for reauthentication isn't resumed then, so the user retries it. - **Phone**: Show an alert explaining verification is needed, then present a sheet for SMS code verification. diff --git a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift index 755996de71..45c7ec3293 100644 --- a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift +++ b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift @@ -21,6 +21,12 @@ import Testing @Suite(.serialized) @MainActor struct EmailLinkDeviceTests { + init() { + // Reauthentication state persists in `UserDefaults`; don't let a failed test leak it. + UserDefaults.standard.removeObject(forKey: "is-reauthenticating") + UserDefaults.standard.removeObject(forKey: "email-link-reauth") + } + private func makeService(continueURL: String = "https://flutterfire-e2e-tests.firebaseapp.com", forceSameDevice: Bool = false, clearingEmulator: Bool = true) async throws -> AuthService { From 5edc3b8a6ad10c28cf1465131eb98e0790ecb8e9 Mon Sep 17 00:00:00 2001 From: Ademola Fadumo <48495111+demolaf@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:02:20 +0100 Subject: [PATCH 3/4] fix(auth): keep cold-launch reauthentication links from being dropped or reused finishEmailLinkReauthentication checked AuthService.currentUser, which the auth listener fills in after launch, so a link that opened the app could arrive before it and be dropped. It now checks auth.currentUser. A link delivered again after reauthentication finished was taken for a sign-in link and threw; it is now remembered like a used sign-in link. --- .../Sources/Services/AuthService.swift | 6 +++++- .../EmailLinkDeviceTests.swift | 10 ++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift index 5a105ce34c..0f54108e84 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift @@ -811,7 +811,9 @@ public extension AuthService { /// ``EmailLinkReauthView`` isn't showing, for example after a cold launch. Does nothing for /// other links, or when that view is showing to handle the link itself. internal func finishEmailLinkReauthentication(with url: URL) async throws { - guard isReauthenticating, !isShowingEmailLinkReauth, currentUser != nil else { return } + // `auth.currentUser`, not `currentUser`: after a cold launch the link can arrive before the + // auth listener has filled in `currentUser`. + guard isReauthenticating, !isShowingEmailLinkReauth, auth.currentUser != nil else { return } try await handleSignInLink(url: url) } @@ -860,6 +862,8 @@ public extension AuthService { } emailLinkReauth = nil isReauthenticating = false + // The same link can be delivered again; don't take it for a sign-in link then. + lastSignedInEmailLink = url } /// The continue URL of the sign-in link inside a URL the app opened. Read before diff --git a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift index 45c7ec3293..b90cd4bdaf 100644 --- a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift +++ b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift @@ -241,11 +241,9 @@ struct EmailLinkDeviceTests { #expect(service.isReauthenticating) service.isShowingEmailLinkReauth = false - // A cold launch starts a new service with the reauthentication state kept in storage. + // A cold launch starts a new service with the reauthentication state kept in storage. The + // link can arrive before its auth listener has filled in `currentUser`, so don't wait for it. let relaunched = try await makeService(clearingEmulator: false) - try await waitForStateChange { - relaunched.currentUser?.email?.caseInsensitiveCompare(email) == .orderedSame - } #expect(relaunched.isReauthenticating) // `AuthPickerContent` may pass the same link more than once. @@ -256,6 +254,10 @@ struct EmailLinkDeviceTests { try await second.value #expect(!relaunched.isReauthenticating) + + // Delivered again after reauthentication finished, the link isn't taken for a sign-in link. + try await relaunched.handleSignInLink(url: link) + #expect(relaunched.pendingEmailLink == nil) try await relaunched.signOut() } From 043dd032daebc38434937076019b1c670dc2adfd Mon Sep 17 00:00:00 2001 From: Ademola Fadumo <48495111+demolaf@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:12:30 +0100 Subject: [PATCH 4/4] test: give pasted UI test text time to land before retrying On a busy CI simulator the pasted text can appear several seconds after the Paste tap, so enterText failed while the field already held the right value. Wait up to 10 seconds instead of 3, and paste once more only when none of the text has arrived. --- .../TestUtils.swift | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleUITests/TestUtils.swift b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleUITests/TestUtils.swift index cc32b41ef1..9f53ddfca1 100644 --- a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleUITests/TestUtils.swift +++ b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleUITests/TestUtils.swift @@ -91,15 +91,24 @@ func createEmail() -> String { return pasteMenuItem } +/// How long a paste has to show up in a field. On a busy CI simulator the pasted text can +/// appear several seconds after the Paste tap. +private let pasteTimeout: TimeInterval = 10 + @MainActor private func typeIntoField(_ field: XCUIElement, text: String, app: XCUIApplication) throws { UIPasteboard.general.string = text - let pasteMenuItem = try showPasteMenu(for: field, text: text, app: app) - pasteMenuItem.tap() - - let success = waitForFieldValue(field, expectedText: text, timeout: 3) - UIPasteboard.general.string = nil + defer { UIPasteboard.general.string = nil } + + var success = false + for attempt in 0 ..< 2 { + // Paste again only into a field without the text, so a late first paste isn't doubled. + if attempt > 0, let value = field.value as? String, value.contains(text) { break } + try showPasteMenu(for: field, text: text, app: app).tap() + success = waitForFieldValue(field, expectedText: text, timeout: pasteTimeout) + if success { break } + } guard success else { throw NSError( @@ -122,7 +131,7 @@ func createEmail() -> String { // Poll until the value changes rather than relying on a fixed sleep. // Secure fields show bullet characters so we can only detect a change, not the exact value. - let deadline = Date().addingTimeInterval(3.0) + let deadline = Date().addingTimeInterval(pasteTimeout) var pasted = false while Date() < deadline { if (field.value as? String) != originalValue {