AuthBackend.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. // Copyright 2023 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import FirebaseCore
  15. import FirebaseCoreExtension
  16. import Foundation
  17. #if COCOAPODS
  18. import GTMSessionFetcher
  19. #else
  20. import GTMSessionFetcherCore
  21. #endif
  22. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  23. protocol AuthBackendRPCIssuer {
  24. /// Asynchronously send a HTTP request.
  25. /// - Parameter request: The request to be made.
  26. /// - Parameter body: Request body.
  27. /// - Parameter contentType: Content type of the body.
  28. /// - Parameter completionHandler: Handles HTTP response. Invoked asynchronously
  29. /// on the auth global work queue in the future.
  30. func asyncCallToURL<T: AuthRPCRequest>(with request: T,
  31. body: Data?,
  32. contentType: String) async -> (Data?, Error?)
  33. }
  34. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  35. class AuthBackendRPCIssuerImplementation: AuthBackendRPCIssuer {
  36. let fetcherService: GTMSessionFetcherService
  37. init() {
  38. fetcherService = GTMSessionFetcherService()
  39. fetcherService.userAgent = AuthBackend.authUserAgent()
  40. fetcherService.callbackQueue = kAuthGlobalWorkQueue
  41. // Avoid reusing the session to prevent
  42. // https://github.com/firebase/firebase-ios-sdk/issues/1261
  43. fetcherService.reuseSession = false
  44. }
  45. func asyncCallToURL<T: AuthRPCRequest>(with request: T,
  46. body: Data?,
  47. contentType: String) async -> (Data?, Error?) {
  48. let requestConfiguration = request.requestConfiguration()
  49. let request = await AuthBackend.request(withURL: request.requestURL(),
  50. contentType: contentType,
  51. requestConfiguration: requestConfiguration)
  52. let fetcher = fetcherService.fetcher(with: request)
  53. if let _ = requestConfiguration.emulatorHostAndPort {
  54. fetcher.allowLocalhostRequest = true
  55. fetcher.allowedInsecureSchemes = ["http"]
  56. }
  57. fetcher.bodyData = body
  58. return await withUnsafeContinuation { continuation in
  59. fetcher.beginFetch { data, error in
  60. continuation.resume(returning: (data, error))
  61. }
  62. }
  63. }
  64. }
  65. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  66. class AuthBackend {
  67. static func authUserAgent() -> String {
  68. return "FirebaseAuth.iOS/\(FirebaseVersion()) \(GTMFetcherStandardUserAgentString(nil))"
  69. }
  70. private static var realRPCBackend = AuthBackendRPCImplementation()
  71. private static var gBackendImplementation = realRPCBackend
  72. class func setTestRPCIssuer(issuer: AuthBackendRPCIssuer) {
  73. gBackendImplementation.rpcIssuer = issuer
  74. }
  75. class func resetRPCIssuer() {
  76. gBackendImplementation.rpcIssuer = realRPCBackend.rpcIssuer
  77. }
  78. class func implementation() -> AuthBackendImplementation {
  79. return gBackendImplementation
  80. }
  81. class func call<T: AuthRPCRequest>(with request: T) async throws -> T.Response {
  82. return try await implementation().call(with: request)
  83. }
  84. class func request(withURL url: URL,
  85. contentType: String,
  86. requestConfiguration: AuthRequestConfiguration) async -> URLRequest {
  87. // Kick off tasks for the async header values.
  88. async let heartbeatsHeaderValue = requestConfiguration.heartbeatLogger?.asyncHeaderValue()
  89. async let appCheckTokenHeaderValue = requestConfiguration.appCheck?
  90. .getToken(forcingRefresh: true)
  91. var request = URLRequest(url: url)
  92. request.setValue(contentType, forHTTPHeaderField: "Content-Type")
  93. let additionalFrameworkMarker = requestConfiguration
  94. .additionalFrameworkMarker ?? "FirebaseCore-iOS"
  95. let clientVersion = "iOS/FirebaseSDK/\(FirebaseVersion())/\(additionalFrameworkMarker)"
  96. request.setValue(clientVersion, forHTTPHeaderField: "X-Client-Version")
  97. request.setValue(Bundle.main.bundleIdentifier, forHTTPHeaderField: "X-Ios-Bundle-Identifier")
  98. request.setValue(requestConfiguration.appID, forHTTPHeaderField: "X-Firebase-GMPID")
  99. request.httpMethod = requestConfiguration.httpMethod
  100. let preferredLocalizations = Bundle.main.preferredLocalizations
  101. if preferredLocalizations.count > 0 {
  102. request.setValue(preferredLocalizations.first, forHTTPHeaderField: "Accept-Language")
  103. }
  104. if let languageCode = requestConfiguration.languageCode,
  105. languageCode.count > 0 {
  106. request.setValue(languageCode, forHTTPHeaderField: "X-Firebase-Locale")
  107. }
  108. // Wait for the async header values.
  109. await request.setValue(heartbeatsHeaderValue, forHTTPHeaderField: "X-Firebase-Client")
  110. if let tokenResult = await appCheckTokenHeaderValue {
  111. if let error = tokenResult.error {
  112. AuthLog.logWarning(code: "I-AUT000018",
  113. message: "Error getting App Check token; using placeholder " +
  114. "token instead. Error: \(error)")
  115. }
  116. request.setValue(tokenResult.token, forHTTPHeaderField: "X-Firebase-AppCheck")
  117. }
  118. return request
  119. }
  120. }
  121. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  122. protocol AuthBackendImplementation {
  123. func call<T: AuthRPCRequest>(with request: T) async throws -> T.Response
  124. }
  125. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  126. private class AuthBackendRPCImplementation: AuthBackendImplementation {
  127. var rpcIssuer: AuthBackendRPCIssuer = AuthBackendRPCIssuerImplementation()
  128. /// Calls the RPC using HTTP request.
  129. /// Possible error responses:
  130. /// * See FIRAuthInternalErrorCodeRPCRequestEncodingError
  131. /// * See FIRAuthInternalErrorCodeJSONSerializationError
  132. /// * See FIRAuthInternalErrorCodeNetworkError
  133. /// * See FIRAuthInternalErrorCodeUnexpectedErrorResponse
  134. /// * See FIRAuthInternalErrorCodeUnexpectedResponse
  135. /// * See FIRAuthInternalErrorCodeRPCResponseDecodingError
  136. /// - Parameter request: The request.
  137. /// - Returns: The response.
  138. fileprivate func call<T: AuthRPCRequest>(with request: T) async throws -> T.Response {
  139. let response = try await callInternal(with: request)
  140. if let auth = request.requestConfiguration().auth,
  141. let mfaError = Self.generateMFAError(response: response, auth: auth) {
  142. throw mfaError
  143. } else if let error = Self.phoneCredentialInUse(response: response) {
  144. throw error
  145. } else {
  146. return response
  147. }
  148. }
  149. #if os(iOS)
  150. private class func generateMFAError(response: AuthRPCResponse, auth: Auth) -> Error? {
  151. if let mfaResponse = response as? AuthMFAResponse,
  152. mfaResponse.idToken == nil,
  153. let enrollments = mfaResponse.mfaInfo {
  154. var info: [MultiFactorInfo] = []
  155. for enrollment in enrollments {
  156. // check which MFA factors are enabled.
  157. if let _ = enrollment.phoneInfo {
  158. info.append(PhoneMultiFactorInfo(proto: enrollment))
  159. } else if let _ = enrollment.totpInfo {
  160. info.append(TOTPMultiFactorInfo(proto: enrollment))
  161. } else {
  162. AuthLog.logError(code: "I-AUT000021", message: "Multifactor type is not supported")
  163. }
  164. }
  165. return AuthErrorUtils.secondFactorRequiredError(
  166. pendingCredential: mfaResponse.mfaPendingCredential,
  167. hints: info,
  168. auth: auth
  169. )
  170. } else {
  171. return nil
  172. }
  173. }
  174. #else
  175. private class func generateMFAError(response: AuthRPCResponse, auth: Auth?) -> Error? {
  176. return nil
  177. }
  178. #endif
  179. #if os(iOS)
  180. // Check whether or not the successful response is actually the special case phone
  181. // auth flow that returns a temporary proof and phone number.
  182. private class func phoneCredentialInUse(response: AuthRPCResponse) -> Error? {
  183. if let phoneAuthResponse = response as? VerifyPhoneNumberResponse,
  184. let phoneNumber = phoneAuthResponse.phoneNumber,
  185. phoneNumber.count > 0,
  186. let temporaryProof = phoneAuthResponse.temporaryProof,
  187. temporaryProof.count > 0 {
  188. let credential = PhoneAuthCredential(withTemporaryProof: temporaryProof,
  189. phoneNumber: phoneNumber,
  190. providerID: PhoneAuthProvider.id)
  191. return AuthErrorUtils.credentialAlreadyInUseError(message: nil,
  192. credential: credential,
  193. email: nil)
  194. } else {
  195. return nil
  196. }
  197. }
  198. #else
  199. private class func phoneCredentialInUse(response: AuthRPCResponse) -> Error? {
  200. return nil
  201. }
  202. #endif
  203. /// Calls the RPC using HTTP request.
  204. ///
  205. /// Possible error responses:
  206. /// * See FIRAuthInternalErrorCodeRPCRequestEncodingError
  207. /// * See FIRAuthInternalErrorCodeJSONSerializationError
  208. /// * See FIRAuthInternalErrorCodeNetworkError
  209. /// * See FIRAuthInternalErrorCodeUnexpectedErrorResponse
  210. /// * See FIRAuthInternalErrorCodeUnexpectedResponse
  211. /// * See FIRAuthInternalErrorCodeRPCResponseDecodingError
  212. /// - Parameter request: The request.
  213. /// - Returns: The response.
  214. fileprivate func callInternal<T: AuthRPCRequest>(with request: T) async throws -> T.Response {
  215. var bodyData: Data?
  216. if request.containsPostBody {
  217. var postBody: [String: AnyHashable]
  218. do {
  219. // TODO: Can unencodedHTTPRequestBody ever throw?
  220. // They don't today, but there are a few fatalErrors that might better be implemented as
  221. // thrown errors.. Although perhaps the case of 'containsPostBody' returning false could
  222. // perhaps be modeled differently so that the failing unencodedHTTPRequestBody could only
  223. // be called when a body exists...
  224. postBody = try request.unencodedHTTPRequestBody()
  225. } catch {
  226. throw AuthErrorUtils.RPCRequestEncodingError(underlyingError: error)
  227. }
  228. var JSONWritingOptions: JSONSerialization.WritingOptions = .init(rawValue: 0)
  229. #if DEBUG
  230. JSONWritingOptions = JSONSerialization.WritingOptions.prettyPrinted
  231. #endif
  232. guard JSONSerialization.isValidJSONObject(postBody) else {
  233. throw AuthErrorUtils.JSONSerializationErrorForUnencodableType()
  234. }
  235. bodyData = try? JSONSerialization.data(
  236. withJSONObject: postBody,
  237. options: JSONWritingOptions
  238. )
  239. if bodyData == nil {
  240. // This is an untested case. This happens exclusively when there is an error in the
  241. // framework implementation of dataWithJSONObject:options:error:. This shouldn't normally
  242. // occur as isValidJSONObject: should return NO in any case we should encounter an error.
  243. throw AuthErrorUtils.JSONSerializationErrorForUnencodableType()
  244. }
  245. }
  246. let (data, error) = await rpcIssuer
  247. .asyncCallToURL(with: request, body: bodyData, contentType: "application/json")
  248. // If there is an error with no body data at all, then this must be a
  249. // network error.
  250. guard let data = data else {
  251. if let error = error {
  252. throw AuthErrorUtils.networkError(underlyingError: error)
  253. } else {
  254. // TODO: this was ignored before
  255. fatalError("Auth Internal error: RPC call didn't return data or an error.")
  256. }
  257. }
  258. // Try to decode the HTTP response data which may contain either a
  259. // successful response or error message.
  260. var dictionary: [String: AnyHashable]
  261. var rawDecode: Any
  262. do {
  263. rawDecode = try JSONSerialization.jsonObject(
  264. with: data, options: JSONSerialization.ReadingOptions.mutableLeaves
  265. )
  266. } catch let jsonError {
  267. if error != nil {
  268. // We have an error, but we couldn't decode the body, so we have no
  269. // additional information other than the raw response and the
  270. // original NSError (the jsonError is inferred by the error code
  271. // (AuthErrorCodeUnexpectedHTTPResponse, and is irrelevant.)
  272. throw AuthErrorUtils.unexpectedErrorResponse(data: data, underlyingError: error)
  273. } else {
  274. // This is supposed to be a "successful" response, but we couldn't
  275. // deserialize the body.
  276. throw AuthErrorUtils.unexpectedResponse(data: data, underlyingError: jsonError)
  277. }
  278. }
  279. guard let decodedDictionary = rawDecode as? [String: AnyHashable] else {
  280. if error != nil {
  281. throw AuthErrorUtils.unexpectedErrorResponse(deserializedResponse: rawDecode,
  282. underlyingError: error)
  283. } else {
  284. throw AuthErrorUtils.unexpectedResponse(deserializedResponse: rawDecode)
  285. }
  286. }
  287. dictionary = decodedDictionary
  288. let response = T.Response()
  289. // At this point we either have an error with successfully decoded
  290. // details in the body, or we have a response which must pass further
  291. // validation before we know it's truly successful. We deal with the
  292. // case where we have an error with successfully decoded error details
  293. // first:
  294. if error != nil {
  295. if let errorDictionary = dictionary["error"] as? [String: AnyHashable] {
  296. if let errorMessage = errorDictionary["message"] as? String {
  297. if let clientError = AuthBackendRPCImplementation.clientError(
  298. withServerErrorMessage: errorMessage,
  299. errorDictionary: errorDictionary,
  300. response: response,
  301. error: error
  302. ) {
  303. throw clientError
  304. }
  305. }
  306. // Not a message we know, return the message directly.
  307. throw AuthErrorUtils.unexpectedErrorResponse(
  308. deserializedResponse: errorDictionary,
  309. underlyingError: error
  310. )
  311. }
  312. // No error message at all, return the decoded response.
  313. throw AuthErrorUtils
  314. .unexpectedErrorResponse(deserializedResponse: dictionary, underlyingError: error)
  315. }
  316. // Finally, we try to populate the response object with the JSON values.
  317. do {
  318. try response.setFields(dictionary: dictionary)
  319. } catch {
  320. throw AuthErrorUtils
  321. .RPCResponseDecodingError(deserializedResponse: dictionary, underlyingError: error)
  322. }
  323. // In case returnIDPCredential of a verifyAssertion request is set to
  324. // @YES, the server may return a 200 with a response that may contain a
  325. // server error.
  326. if let verifyAssertionRequest = request as? VerifyAssertionRequest {
  327. if verifyAssertionRequest.returnIDPCredential {
  328. if let errorMessage = dictionary["errorMessage"] as? String {
  329. if let clientError = AuthBackendRPCImplementation.clientError(
  330. withServerErrorMessage: errorMessage,
  331. errorDictionary: dictionary,
  332. response: response,
  333. error: error
  334. ) {
  335. throw clientError
  336. }
  337. }
  338. }
  339. }
  340. return response
  341. }
  342. private class func clientError(withServerErrorMessage serverErrorMessage: String,
  343. errorDictionary: [String: Any],
  344. response: AuthRPCResponse,
  345. error: Error?) -> Error? {
  346. let split = serverErrorMessage.split(separator: ":")
  347. let shortErrorMessage = split.first?.trimmingCharacters(in: .whitespacesAndNewlines)
  348. let serverDetailErrorMessage = String(split.count > 1 ? split[1] : "")
  349. .trimmingCharacters(in: .whitespacesAndNewlines)
  350. switch shortErrorMessage {
  351. case "USER_NOT_FOUND": return AuthErrorUtils
  352. .userNotFoundError(message: serverDetailErrorMessage)
  353. case "MISSING_CONTINUE_URI": return AuthErrorUtils
  354. .missingContinueURIError(message: serverDetailErrorMessage)
  355. // "INVALID_IDENTIFIER" can be returned by createAuthURI RPC. Considering email addresses are
  356. // currently the only identifiers, we surface the FIRAuthErrorCodeInvalidEmail error code in
  357. // this case.
  358. case "INVALID_IDENTIFIER": return AuthErrorUtils
  359. .invalidEmailError(message: serverDetailErrorMessage)
  360. case "INVALID_ID_TOKEN": return AuthErrorUtils
  361. .invalidUserTokenError(message: serverDetailErrorMessage)
  362. case "CREDENTIAL_TOO_OLD_LOGIN_AGAIN": return AuthErrorUtils
  363. .requiresRecentLoginError(message: serverDetailErrorMessage)
  364. case "EMAIL_EXISTS": return AuthErrorUtils
  365. .emailAlreadyInUseError(email: nil)
  366. case "OPERATION_NOT_ALLOWED": return AuthErrorUtils
  367. .operationNotAllowedError(message: serverDetailErrorMessage)
  368. case "PASSWORD_LOGIN_DISABLED": return AuthErrorUtils
  369. .operationNotAllowedError(message: serverDetailErrorMessage)
  370. case "USER_DISABLED": return AuthErrorUtils
  371. .userDisabledError(message: serverDetailErrorMessage)
  372. case "INVALID_EMAIL": return AuthErrorUtils
  373. .invalidEmailError(message: serverDetailErrorMessage)
  374. case "EXPIRED_OOB_CODE": return AuthErrorUtils
  375. .expiredActionCodeError(message: serverDetailErrorMessage)
  376. case "INVALID_OOB_CODE": return AuthErrorUtils
  377. .invalidActionCodeError(message: serverDetailErrorMessage)
  378. case "INVALID_MESSAGE_PAYLOAD": return AuthErrorUtils
  379. .invalidMessagePayloadError(message: serverDetailErrorMessage)
  380. case "INVALID_SENDER": return AuthErrorUtils
  381. .invalidSenderError(message: serverDetailErrorMessage)
  382. case "INVALID_RECIPIENT_EMAIL": return AuthErrorUtils
  383. .invalidRecipientEmailError(message: serverDetailErrorMessage)
  384. case "WEAK_PASSWORD": return AuthErrorUtils
  385. .weakPasswordError(serverResponseReason: serverDetailErrorMessage)
  386. case "TOO_MANY_ATTEMPTS_TRY_LATER": return AuthErrorUtils
  387. .tooManyRequestsError(message: serverDetailErrorMessage)
  388. case "EMAIL_NOT_FOUND": return AuthErrorUtils
  389. .userNotFoundError(message: serverDetailErrorMessage)
  390. case "MISSING_EMAIL": return AuthErrorUtils
  391. .missingEmailError(message: serverDetailErrorMessage)
  392. case "MISSING_IOS_BUNDLE_ID": return AuthErrorUtils
  393. .missingIosBundleIDError(message: serverDetailErrorMessage)
  394. case "MISSING_ANDROID_PACKAGE_NAME": return AuthErrorUtils
  395. .missingAndroidPackageNameError(message: serverDetailErrorMessage)
  396. case "UNAUTHORIZED_DOMAIN": return AuthErrorUtils
  397. .unauthorizedDomainError(message: serverDetailErrorMessage)
  398. case "INVALID_CONTINUE_URI": return AuthErrorUtils
  399. .invalidContinueURIError(message: serverDetailErrorMessage)
  400. case "INVALID_PASSWORD": return AuthErrorUtils
  401. .wrongPasswordError(message: serverDetailErrorMessage)
  402. case "INVALID_IDP_RESPONSE": return AuthErrorUtils
  403. .invalidCredentialError(message: serverDetailErrorMessage)
  404. case "INVALID_PENDING_TOKEN": return AuthErrorUtils
  405. .invalidCredentialError(message: serverDetailErrorMessage)
  406. case "INVALID_LOGIN_CREDENTIALS": return AuthErrorUtils
  407. .invalidCredentialError(message: serverDetailErrorMessage)
  408. case "INVALID_CUSTOM_TOKEN": return AuthErrorUtils
  409. .invalidCustomTokenError(message: serverDetailErrorMessage)
  410. case "CREDENTIAL_MISMATCH": return AuthErrorUtils
  411. .customTokenMismatchError(message: serverDetailErrorMessage)
  412. case "INVALID_PHONE_NUMBER": return AuthErrorUtils
  413. .invalidPhoneNumberError(message: serverDetailErrorMessage)
  414. case "QUOTA_EXCEEDED": return AuthErrorUtils
  415. .quotaExceededError(message: serverDetailErrorMessage)
  416. case "APP_NOT_VERIFIED": return AuthErrorUtils
  417. .appNotVerifiedError(message: serverDetailErrorMessage)
  418. case "CAPTCHA_CHECK_FAILED": return AuthErrorUtils
  419. .captchaCheckFailedError(message: serverDetailErrorMessage)
  420. case "INVALID_APP_CREDENTIAL": return AuthErrorUtils
  421. .invalidAppCredential(message: serverDetailErrorMessage)
  422. case "MISSING_APP_CREDENTIAL": return AuthErrorUtils
  423. .missingAppCredential(message: serverDetailErrorMessage)
  424. case "INVALID_CODE": return AuthErrorUtils
  425. .invalidVerificationCodeError(message: serverDetailErrorMessage)
  426. case "INVALID_SESSION_INFO": return AuthErrorUtils
  427. .invalidVerificationIDError(message: serverDetailErrorMessage)
  428. case "SESSION_EXPIRED": return AuthErrorUtils
  429. .sessionExpiredError(message: serverDetailErrorMessage)
  430. case "ADMIN_ONLY_OPERATION": return AuthErrorUtils
  431. .error(code: AuthErrorCode.adminRestrictedOperation, message: serverDetailErrorMessage)
  432. case "BLOCKING_FUNCTION_ERROR_RESPONSE": return AuthErrorUtils
  433. .blockingCloudFunctionServerResponse(message: serverDetailErrorMessage)
  434. case "EMAIL_CHANGE_NEEDS_VERIFICATION": return AuthErrorUtils
  435. .error(code: AuthErrorCode.emailChangeNeedsVerification, message: serverDetailErrorMessage)
  436. case "INVALID_MFA_PENDING_CREDENTIAL": return AuthErrorUtils
  437. .error(code: AuthErrorCode.invalidMultiFactorSession, message: serverDetailErrorMessage)
  438. case "INVALID_PROVIDER_ID": return AuthErrorUtils
  439. .invalidProviderIDError(message: serverDetailErrorMessage)
  440. case "MFA_ENROLLMENT_NOT_FOUND": return AuthErrorUtils
  441. .error(code: AuthErrorCode.multiFactorInfoNotFound, message: serverDetailErrorMessage)
  442. case "MISSING_CLIENT_IDENTIFIER": return AuthErrorUtils
  443. .missingClientIdentifierError(message: serverDetailErrorMessage)
  444. case "MISSING_IOS_APP_TOKEN": return AuthErrorUtils
  445. .missingAppTokenError(underlyingError: nil)
  446. case "MISSING_MFA_ENROLLMENT_ID": return AuthErrorUtils
  447. .error(code: AuthErrorCode.missingMultiFactorInfo, message: serverDetailErrorMessage)
  448. case "MISSING_MFA_PENDING_CREDENTIAL": return AuthErrorUtils
  449. .error(code: AuthErrorCode.missingMultiFactorSession, message: serverDetailErrorMessage)
  450. case "MISSING_OR_INVALID_NONCE": return AuthErrorUtils
  451. .missingOrInvalidNonceError(message: serverDetailErrorMessage)
  452. case "SECOND_FACTOR_EXISTS": return AuthErrorUtils
  453. .error(code: AuthErrorCode.secondFactorAlreadyEnrolled, message: serverDetailErrorMessage)
  454. case "SECOND_FACTOR_LIMIT_EXCEEDED": return AuthErrorUtils
  455. .error(
  456. code: AuthErrorCode.maximumSecondFactorCountExceeded,
  457. message: serverDetailErrorMessage
  458. )
  459. case "TENANT_ID_MISMATCH": return AuthErrorUtils.tenantIDMismatchError()
  460. case "TOKEN_EXPIRED": return AuthErrorUtils
  461. .userTokenExpiredError(message: serverDetailErrorMessage)
  462. case "UNSUPPORTED_FIRST_FACTOR": return AuthErrorUtils
  463. .error(code: AuthErrorCode.unsupportedFirstFactor, message: serverDetailErrorMessage)
  464. case "UNSUPPORTED_TENANT_OPERATION": return AuthErrorUtils
  465. .unsupportedTenantOperationError()
  466. case "UNVERIFIED_EMAIL": return AuthErrorUtils
  467. .error(code: AuthErrorCode.unverifiedEmail, message: serverDetailErrorMessage)
  468. case "FEDERATED_USER_ID_ALREADY_LINKED":
  469. guard let verifyAssertion = response as? VerifyAssertionResponse else {
  470. return AuthErrorUtils.credentialAlreadyInUseError(
  471. message: serverDetailErrorMessage, credential: nil, email: nil
  472. )
  473. }
  474. let credential = OAuthCredential(withVerifyAssertionResponse: verifyAssertion)
  475. let email = verifyAssertion.email
  476. return AuthErrorUtils.credentialAlreadyInUseError(
  477. message: serverDetailErrorMessage, credential: credential, email: email
  478. )
  479. default:
  480. if let underlyingErrors = errorDictionary["errors"] as? [[String: String]] {
  481. for underlyingError in underlyingErrors {
  482. if let reason = underlyingError["reason"] {
  483. if reason.starts(with: "keyInvalid") {
  484. return AuthErrorUtils.invalidAPIKeyError()
  485. }
  486. if underlyingError["reason"] == "ipRefererBlocked" {
  487. return AuthErrorUtils.appNotAuthorizedError()
  488. }
  489. }
  490. }
  491. }
  492. }
  493. return nil
  494. }
  495. }