Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MFA Integration Testing fixes #12223

Merged
merged 4 commits into from
Dec 28, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -274,23 +274,20 @@ import Foundation
let startMFARequestInfo = AuthProtoStartMFAPhoneRequestInfo(phoneNumber: phoneNumber,
codeIdentity: codeIdentity)
do {
switch codeIdentity {
case .credential:
let request = StartMFAEnrollmentRequest(idToken: session.idToken,
if let idToken = session.idToken {
let request = StartMFAEnrollmentRequest(idToken: idToken,
enrollmentInfo: startMFARequestInfo,
requestConfiguration: auth.requestConfiguration)
let response = try await AuthBackend.call(with: request)
return response.phoneSessionInfo?.sessionInfo
case .recaptcha:
} else {
let request = StartMFASignInRequest(MFAPendingCredential: session.mfaPendingCredential,
MFAEnrollmentID: session.multiFactorInfo?.uid,
signInInfo: startMFARequestInfo,
requestConfiguration: auth.requestConfiguration)

let response = try await AuthBackend.call(with: request)
return response.responseInfo?.sessionInfo
case .empty:
return nil
}
} catch {
return try await handleVerifyErrorWithRetry(
Expand Down
8 changes: 3 additions & 5 deletions FirebaseAuth/Sources/Swift/Backend/AuthBackend.swift
Original file line number Diff line number Diff line change
Expand Up @@ -185,18 +185,16 @@ private class AuthBackendRPCImplementation: NSObject, AuthBackendImplementation

#if os(iOS)
private class func generateMFAError(response: AuthRPCResponse, auth: Auth) -> Error? {
if let mfaResponse = response as? EmailLinkSignInResponse,
if let mfaResponse = response as? AuthMFAResponse,
mfaResponse.idToken == nil,
let enrollments = mfaResponse.mfaInfo {
var info: [MultiFactorInfo] = []
for enrollment in enrollments {
// check which MFA factors are enabled.
if let _ = enrollment.phoneInfo {
info.append(MultiFactorInfo(proto: enrollment,
factorID: PhoneMultiFactorInfo.PhoneMultiFactorID))
info.append(PhoneMultiFactorInfo(proto: enrollment))
} else if let _ = enrollment.totpInfo {
info.append(MultiFactorInfo(proto: enrollment,
factorID: PhoneMultiFactorInfo.TOTPMultiFactorID))
info.append(TOTPMultiFactorInfo(proto: enrollment))
} else {
AuthLog.logError(code: "I-AUT000021", message: "Multifactor type is not supported")
}
Expand Down
28 changes: 28 additions & 0 deletions FirebaseAuth/Sources/Swift/Backend/RPC/AuthMFAResponse.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright 2023 Google LLC
//
// 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.

import Foundation

/// Protocol for responses that support Multi-Factor Authentication.
protocol AuthMFAResponse {
/// An opaque string that functions as proof that the user has successfully passed the first
/// factor check.
var mfaPendingCredential: String? { get }

/// Info on which multi-factor authentication providers are enabled.
var mfaInfo: [AuthProtoMFAEnrollment]? { get }

/// MFA is only done when the idToken is nil.
var idToken: String? { get }
}
paulb777 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@ import Foundation
/** @class FIRVerifyAssertionResponse
@brief Represents the response from the emailLinkSignin endpoint.
*/
class EmailLinkSignInResponse: NSObject, AuthRPCResponse {
class EmailLinkSignInResponse: NSObject, AuthRPCResponse, AuthMFAResponse {
override required init() {}

/** @property IDToken
@brief The ID token in the email link sign-in response.
*/
var idToken: String?
private var _idToken: String?

/** @property email
@brief The email returned by the IdP.
Expand All @@ -45,20 +45,28 @@ class EmailLinkSignInResponse: NSObject, AuthRPCResponse {
*/
var isNewUser: Bool = false

// MARK: - AuthMFAResponse

var mfaPendingCredential: String? { return _mfaPendingCredential }

var mfaInfo: [AuthProtoMFAEnrollment]? { return _mfaInfo }

var idToken: String? { return _idToken }

/** @property MFAPendingCredential
@brief An opaque string that functions as proof that the user has successfully passed the first
factor check.
*/
var mfaPendingCredential: String?
private var _mfaPendingCredential: String?

/** @property MFAInfo
@brief Info on which multi-factor authentication providers are enabled.
*/
var mfaInfo: [AuthProtoMFAEnrollment]?
private var _mfaInfo: [AuthProtoMFAEnrollment]?

func setFields(dictionary: [String: AnyHashable]) throws {
email = dictionary["email"] as? String
idToken = dictionary["idToken"] as? String
_idToken = dictionary["idToken"] as? String
isNewUser = dictionary["isNewUser"] as? Bool ?? false
refreshToken = dictionary["refreshToken"] as? String

Expand All @@ -72,8 +80,8 @@ class EmailLinkSignInResponse: NSObject, AuthRPCResponse {
let enrollment = AuthProtoMFAEnrollment(dictionary: entry)
mfaInfo.append(enrollment)
}
self.mfaInfo = mfaInfo
_mfaInfo = mfaInfo
}
mfaPendingCredential = dictionary["mfaPendingCredential"] as? String
_mfaPendingCredential = dictionary["mfaPendingCredential"] as? String
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import Foundation
@brief Represents the response from the verifyAssertion endpoint.
@see https://developers.google.com/identity/toolkit/web/reference/relyingparty/verifyAssertion
*/
class VerifyAssertionResponse: AuthRPCResponse {
class VerifyAssertionResponse: AuthRPCResponse, AuthMFAResponse {
required init() {}

/** @property federatedID
Expand Down Expand Up @@ -97,7 +97,7 @@ class VerifyAssertionResponse: AuthRPCResponse {
access token from Secure Token Service, depending on whether @c returnSecureToken is set
on the request.
*/
var idToken: String?
private var _idToken: String?

/** @property approximateExpirationDate
@brief The approximate expiration date of the access token.
Expand Down Expand Up @@ -201,9 +201,17 @@ class VerifyAssertionResponse: AuthRPCResponse {
*/
var pendingToken: String?

var MFAPendingCredential: String?
// MARK: - AuthMFAResponse

var MFAInfo: [AuthProtoMFAEnrollment]?
var mfaPendingCredential: String? { return _mfaPendingCredential }

var mfaInfo: [AuthProtoMFAEnrollment]? { return _mfaInfo }

var idToken: String? { return _idToken }

private var _mfaPendingCredential: String?

private var _mfaInfo: [AuthProtoMFAEnrollment]?

func setFields(dictionary: [String: AnyHashable]) throws {
federatedID = dictionary["federatedId"] as? String
Expand All @@ -221,7 +229,7 @@ class VerifyAssertionResponse: AuthRPCResponse {
fullName = dictionary["fullName"] as? String
nickName = dictionary["nickName"] as? String
displayName = dictionary["displayName"] as? String
idToken = dictionary["idToken"] as? String
_idToken = dictionary["idToken"] as? String
if let expiresIn = dictionary["expiresIn"] as? String {
approximateExpirationDate = Date(timeIntervalSinceNow: (expiresIn as NSString)
.doubleValue)
Expand Down Expand Up @@ -267,10 +275,10 @@ class VerifyAssertionResponse: AuthRPCResponse {
pendingToken = dictionary["pendingToken"] as? String

if let mfaInfoDicts = dictionary["mfaInfo"] as? [[String: AnyHashable]] {
MFAInfo = mfaInfoDicts.map {
_mfaInfo = mfaInfoDicts.map {
AuthProtoMFAEnrollment(dictionary: $0)
}
}
MFAPendingCredential = dictionary["mfaPendingCredential"] as? String
_mfaPendingCredential = dictionary["mfaPendingCredential"] as? String
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import Foundation
- FIRAuthInternalErrorCodeEmailNotFound
@see https://developers.google.com/identity/toolkit/web/reference/relyingparty/verifyPassword
*/
class VerifyPasswordResponse: AuthRPCResponse {
class VerifyPasswordResponse: AuthRPCResponse, AuthMFAResponse {
required init() {}

/** @property localID
Expand All @@ -45,7 +45,7 @@ class VerifyPasswordResponse: AuthRPCResponse {
access token from Secure Token Service, depending on whether @c returnSecureToken is set
on the request.
*/
var idToken: String?
private var _idToken: String?

/** @property approximateExpirationDate
@brief The approximate expiration date of the access token.
Expand All @@ -62,15 +62,23 @@ class VerifyPasswordResponse: AuthRPCResponse {
*/
var photoURL: URL?

var mfaPendingCredential: String?
// MARK: - AuthMFAResponse

var mfaInfo: [AuthProtoMFAEnrollment]?
var mfaPendingCredential: String? { return _mfaPendingCredential }

var mfaInfo: [AuthProtoMFAEnrollment]? { return _mfaInfo }

var idToken: String? { return _idToken }

private var _mfaPendingCredential: String?

private var _mfaInfo: [AuthProtoMFAEnrollment]?

func setFields(dictionary: [String: AnyHashable]) throws {
localID = dictionary["localId"] as? String
email = dictionary["email"] as? String
displayName = dictionary["displayName"] as? String
idToken = dictionary["idToken"] as? String
_idToken = dictionary["idToken"] as? String
if let expiresIn = dictionary["expiresIn"] as? String {
approximateExpirationDate = Date(timeIntervalSinceNow: (expiresIn as NSString)
.doubleValue)
Expand All @@ -79,8 +87,8 @@ class VerifyPasswordResponse: AuthRPCResponse {
photoURL = (dictionary["photoUrl"] as? String).flatMap { URL(string: $0) }

if let mfaInfo = dictionary["mfaInfo"] as? [[String: AnyHashable]] {
self.mfaInfo = mfaInfo.map { AuthProtoMFAEnrollment(dictionary: $0) }
_mfaInfo = mfaInfo.map { AuthProtoMFAEnrollment(dictionary: $0) }
}
mfaPendingCredential = dictionary["mfaPendingCredential"] as? String
_mfaPendingCredential = dictionary["mfaPendingCredential"] as? String
}
}
8 changes: 4 additions & 4 deletions FirebaseAuth/Sources/Swift/User/User.swift
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ extension User: NSSecureCoding {}

@remarks See `AuthErrors` for a list of error codes that are common to all API methods.
*/
@objc public func reload(withCompletion completion: ((Error?) -> Void)? = nil) {
@objc public func reload(completion: ((Error?) -> Void)? = nil) {
kAuthGlobalWorkQueue.async {
self.getAccountInfoRefreshingCache { user, error in
User.callInMainThreadWithError(callback: completion, error: error)
Expand Down Expand Up @@ -1023,7 +1023,7 @@ extension User: NSSecureCoding {}
*/
@objc(sendEmailVerificationWithCompletion:)
public func __sendEmailVerification(withCompletion completion: ((Error?) -> Void)?) {
sendEmailVerification(withCompletion: completion)
sendEmailVerification(completion: completion)
}

/** @fn sendEmailVerificationWithActionCodeSettings:completion:
Expand Down Expand Up @@ -1052,7 +1052,7 @@ extension User: NSSecureCoding {}
*/
@objc(sendEmailVerificationWithActionCodeSettings:completion:)
public func sendEmailVerification(with actionCodeSettings: ActionCodeSettings? = nil,
withCompletion completion: ((Error?) -> Void)? = nil) {
completion: ((Error?) -> Void)? = nil) {
kAuthGlobalWorkQueue.async {
self.internalGetToken { accessToken, error in
if let error {
Expand Down Expand Up @@ -1136,7 +1136,7 @@ extension User: NSSecureCoding {}

@remarks See `AuthErrors` for a list of error codes that are common to all `User` methods.
*/
@objc public func delete(withCompletion completion: ((Error?) -> Void)? = nil) {
@objc public func delete(completion: ((Error?) -> Void)? = nil) {
kAuthGlobalWorkQueue.async {
self.internalGetToken { accessToken, error in
if let error {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ import Foundation
@param completion Optionally; the block invoked when the user profile change has been applied.
Invoked asynchronously on the main thread in the future.
*/
@objc public func commitChanges(withCompletion completion: ((Error?) -> Void)? = nil) {
@objc public func commitChanges(completion: ((Error?) -> Void)? = nil) {
kAuthGlobalWorkQueue.async {
if self.consumed {
fatalError("Internal Auth Error: commitChanges should only be called once.")
Expand Down