AuthBackend.swift 21 KB

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