AuthErrorUtils.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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 Foundation
  15. // MARK: - URL response error codes
  16. /** @var kURLResponseErrorCodeInvalidClientID
  17. @brief Error code that indicates that the client ID provided was invalid.
  18. */
  19. private let kURLResponseErrorCodeInvalidClientID = "auth/invalid-oauth-client-id"
  20. /** @var kURLResponseErrorCodeNetworkRequestFailed
  21. @brief Error code that indicates that a network request within the SFSafariViewController or
  22. WKWebView failed.
  23. */
  24. private let kURLResponseErrorCodeNetworkRequestFailed = "auth/network-request-failed"
  25. /** @var kURLResponseErrorCodeInternalError
  26. @brief Error code that indicates that an internal error occurred within the
  27. SFSafariViewController or WKWebView failed.
  28. */
  29. private let kURLResponseErrorCodeInternalError = "auth/internal-error"
  30. private let kFIRAuthErrorMessageMalformedJWT =
  31. "Failed to parse JWT. Check the userInfo dictionary for the full token."
  32. @objc(FIRAuthErrorUtils) public class AuthErrorUtils: NSObject {
  33. static let errorDomain = "FIRAuthErrorDomain"
  34. static let internalErrorDomain = "FIRAuthInternalErrorDomain"
  35. static let userInfoDeserializedResponseKey = "FIRAuthErrorUserInfoDeserializedResponseKey"
  36. static let userInfoDataKey = "FIRAuthErrorUserInfoDataKey"
  37. static let userInfoEmailKey = "FIRAuthErrorUserInfoEmailKey"
  38. static let userInfoUpdatedCredentialKey = "FIRAuthErrorUserInfoUpdatedCredentialKey"
  39. static let userInfoNameKey = "FIRAuthErrorUserInfoNameKey"
  40. static let userInfoMultiFactorResolverKey = "FIRAuthErrorUserInfoMultiFactorResolverKey"
  41. /** @var kServerErrorDetailMarker
  42. @brief This marker indicates that the server error message contains a detail error message which
  43. should be used instead of the hardcoded client error message.
  44. */
  45. private static let kServerErrorDetailMarker = " : "
  46. static func error(code: SharedErrorCode, userInfo: [String: Any]? = nil) -> Error {
  47. switch code {
  48. case let .public(publicCode):
  49. var errorUserInfo: [String: Any] = userInfo ?? [:]
  50. if errorUserInfo[NSLocalizedDescriptionKey] == nil {
  51. errorUserInfo[NSLocalizedDescriptionKey] = publicCode.errorDescription
  52. }
  53. errorUserInfo[userInfoNameKey] = publicCode.errorCodeString
  54. return NSError(
  55. domain: errorDomain,
  56. code: publicCode.rawValue,
  57. userInfo: errorUserInfo
  58. )
  59. case let .internal(internalCode):
  60. // This is an internal error. Wrap it in an internal error.
  61. let error = NSError(
  62. domain: internalErrorDomain,
  63. code: internalCode.rawValue,
  64. userInfo: userInfo
  65. )
  66. return self.error(code: .public(.internalError), underlyingError: error)
  67. }
  68. }
  69. static func error(code: SharedErrorCode, underlyingError: Error?) -> Error {
  70. var errorUserInfo: [String: Any]?
  71. if let underlyingError = underlyingError {
  72. errorUserInfo = [NSUnderlyingErrorKey: underlyingError]
  73. }
  74. return error(code: code, userInfo: errorUserInfo)
  75. }
  76. static func error(code: AuthErrorCode, underlyingError: Error?) -> Error {
  77. error(code: SharedErrorCode.public(code), underlyingError: underlyingError)
  78. }
  79. @objc public static func error(code: AuthErrorCode, userInfo: [String: Any]? = nil) -> Error {
  80. error(code: SharedErrorCode.public(code), userInfo: userInfo)
  81. }
  82. @objc public static func error(code: AuthErrorCode, message: String?) -> Error {
  83. let userInfo: [String: Any]?
  84. if let message {
  85. userInfo = [NSLocalizedDescriptionKey: message]
  86. } else {
  87. userInfo = nil
  88. }
  89. return error(code: SharedErrorCode.public(code), userInfo: userInfo)
  90. }
  91. @objc public static func userDisabledError(message: String?) -> Error {
  92. error(code: .userDisabled, message: message)
  93. }
  94. @objc public static func wrongPasswordError(message: String?) -> Error {
  95. error(code: .wrongPassword, message: message)
  96. }
  97. @objc public static func tooManyRequestsError(message: String?) -> Error {
  98. error(code: .tooManyRequests, message: message)
  99. }
  100. @objc public static func invalidCustomTokenError(message: String?) -> Error {
  101. error(code: .invalidCustomToken, message: message)
  102. }
  103. @objc public static func customTokenMismatchError(message: String?) -> Error {
  104. error(code: .customTokenMismatch, message: message)
  105. }
  106. @objc public static func invalidCredentialError(message: String?) -> Error {
  107. error(code: .invalidCredential, message: message)
  108. }
  109. @objc public static func requiresRecentLoginError(message: String?) -> Error {
  110. error(code: .requiresRecentLogin, message: message)
  111. }
  112. @objc public static func invalidUserTokenError(message: String?) -> Error {
  113. error(code: .invalidUserToken, message: message)
  114. }
  115. @objc public static func invalidEmailError(message: String?) -> Error {
  116. error(code: .invalidEmail, message: message)
  117. }
  118. @objc public static func providerAlreadyLinkedError() -> Error {
  119. error(code: .providerAlreadyLinked)
  120. }
  121. @objc public static func noSuchProviderError() -> Error {
  122. error(code: .noSuchProvider)
  123. }
  124. @objc public static func userTokenExpiredError(message: String?) -> Error {
  125. error(code: .userTokenExpired, message: message)
  126. }
  127. @objc public static func userNotFoundError(message: String?) -> Error {
  128. error(code: .userNotFound, message: message)
  129. }
  130. @objc public static func invalidAPIKeyError() -> Error {
  131. error(code: .invalidAPIKey)
  132. }
  133. @objc public static func userMismatchError() -> Error {
  134. error(code: .userMismatch)
  135. }
  136. @objc public static func operationNotAllowedError(message: String?) -> Error {
  137. error(code: .operationNotAllowed, message: message)
  138. }
  139. @objc public static func weakPasswordError(serverResponseReason reason: String?) -> Error {
  140. let userInfo: [String: Any]?
  141. if let reason, !reason.isEmpty {
  142. userInfo = [
  143. NSLocalizedFailureReasonErrorKey: reason,
  144. ]
  145. } else {
  146. userInfo = nil
  147. }
  148. return error(code: .weakPassword, userInfo: userInfo)
  149. }
  150. @objc public static func appNotAuthorizedError() -> Error {
  151. error(code: .appNotAuthorized)
  152. }
  153. @objc public static func expiredActionCodeError(message: String?) -> Error {
  154. error(code: .expiredActionCode, message: message)
  155. }
  156. @objc public static func invalidActionCodeError(message: String?) -> Error {
  157. error(code: .invalidActionCode, message: message)
  158. }
  159. @objc public static func invalidMessagePayloadError(message: String?) -> Error {
  160. error(code: .invalidMessagePayload, message: message)
  161. }
  162. @objc public static func invalidSenderError(message: String?) -> Error {
  163. error(code: .invalidSender, message: message)
  164. }
  165. @objc public static func invalidRecipientEmailError(message: String?) -> Error {
  166. error(code: .invalidRecipientEmail, message: message)
  167. }
  168. @objc public static func missingIosBundleIDError(message: String?) -> Error {
  169. error(code: .missingIosBundleID, message: message)
  170. }
  171. @objc public static func missingAndroidPackageNameError(message: String?) -> Error {
  172. error(code: .missingAndroidPackageName, message: message)
  173. }
  174. @objc public static func unauthorizedDomainError(message: String?) -> Error {
  175. error(code: .unauthorizedDomain, message: message)
  176. }
  177. @objc public static func invalidContinueURIError(message: String?) -> Error {
  178. error(code: .invalidContinueURI, message: message)
  179. }
  180. @objc public static func missingContinueURIError(message: String?) -> Error {
  181. error(code: .missingContinueURI, message: message)
  182. }
  183. @objc public static func missingEmailError(message: String?) -> Error {
  184. error(code: .missingEmail, message: message)
  185. }
  186. @objc public static func missingPhoneNumberError(message: String?) -> Error {
  187. error(code: .missingPhoneNumber, message: message)
  188. }
  189. @objc public static func invalidPhoneNumberError(message: String?) -> Error {
  190. error(code: .invalidPhoneNumber, message: message)
  191. }
  192. @objc public static func missingVerificationCodeError(message: String?) -> Error {
  193. error(code: .missingVerificationCode, message: message)
  194. }
  195. @objc public static func invalidVerificationCodeError(message: String?) -> Error {
  196. error(code: .invalidVerificationCode, message: message)
  197. }
  198. @objc public static func missingVerificationIDError(message: String?) -> Error {
  199. error(code: .missingVerificationID, message: message)
  200. }
  201. @objc public static func invalidVerificationIDError(message: String?) -> Error {
  202. error(code: .invalidVerificationID, message: message)
  203. }
  204. @objc public static func sessionExpiredError(message: String?) -> Error {
  205. error(code: .sessionExpired, message: message)
  206. }
  207. @objc public static func missingAppCredential(message: String?) -> Error {
  208. error(code: .missingAppCredential, message: message)
  209. }
  210. @objc public static func invalidAppCredential(message: String?) -> Error {
  211. error(code: .invalidAppCredential, message: message)
  212. }
  213. @objc public static func quotaExceededError(message: String?) -> Error {
  214. error(code: .quotaExceeded, message: message)
  215. }
  216. @objc public static func missingAppTokenError(underlyingError: Error?) -> Error {
  217. error(code: .missingAppToken, underlyingError: underlyingError)
  218. }
  219. @objc public static func localPlayerNotAuthenticatedError() -> Error {
  220. error(code: .localPlayerNotAuthenticated)
  221. }
  222. @objc public static func gameKitNotLinkedError() -> Error {
  223. error(code: .gameKitNotLinked)
  224. }
  225. @objc public static func RPCRequestEncodingError(underlyingError: Error) -> Error {
  226. error(code: .internal(.RPCRequestEncodingError), underlyingError: underlyingError)
  227. }
  228. @objc public static func JSONSerializationErrorForUnencodableType() -> Error {
  229. error(code: .internal(.JSONSerializationError))
  230. }
  231. @objc public static func JSONSerializationError(underlyingError: Error) -> Error {
  232. error(code: .internal(.JSONSerializationError), underlyingError: underlyingError)
  233. }
  234. @objc public static func networkError(underlyingError: Error) -> Error {
  235. error(code: .networkError, underlyingError: underlyingError)
  236. }
  237. @objc public static func emailAlreadyInUseError(email: String?) -> Error {
  238. var userInfo: [String: Any]?
  239. if let email, !email.isEmpty {
  240. userInfo = [userInfoEmailKey: email]
  241. }
  242. return error(code: .emailAlreadyInUse, userInfo: userInfo)
  243. }
  244. @objc public static func credentialAlreadyInUseError(message: String?,
  245. credential: AuthCredential?,
  246. email: String?) -> Error {
  247. var userInfo: [String: Any] = [:]
  248. if let credential {
  249. userInfo[userInfoUpdatedCredentialKey] = credential
  250. }
  251. if let email, !email.isEmpty {
  252. userInfo[userInfoEmailKey] = email
  253. }
  254. if !userInfo.isEmpty {
  255. return error(code: .credentialAlreadyInUse, userInfo: userInfo)
  256. }
  257. return error(code: .credentialAlreadyInUse, message: message)
  258. }
  259. @objc public static func webContextAlreadyPresentedError(message: String?) -> Error {
  260. error(code: .webContextAlreadyPresented, message: message)
  261. }
  262. @objc public static func webContextCancelledError(message: String?) -> Error {
  263. error(code: .webContextCancelled, message: message)
  264. }
  265. @objc public static func appVerificationUserInteractionFailure(reason: String?) -> Error {
  266. let userInfo: [String: Any]?
  267. if let reason, !reason.isEmpty {
  268. userInfo = [NSLocalizedFailureReasonErrorKey: reason]
  269. } else {
  270. userInfo = nil
  271. }
  272. return error(code: .appVerificationUserInteractionFailure, userInfo: userInfo)
  273. }
  274. @objc public static func webSignInUserInteractionFailure(reason: String?) -> Error {
  275. let userInfo: [String: Any]?
  276. if let reason, !reason.isEmpty {
  277. userInfo = [NSLocalizedFailureReasonErrorKey: reason]
  278. } else {
  279. userInfo = nil
  280. }
  281. return error(code: .webSignInUserInteractionFailure, userInfo: userInfo)
  282. }
  283. @objc public static func urlResponseError(code: String, message: String?) -> Error {
  284. let errorCode: AuthErrorCode
  285. switch code {
  286. case kURLResponseErrorCodeInvalidClientID:
  287. errorCode = .invalidClientID
  288. case kURLResponseErrorCodeNetworkRequestFailed:
  289. errorCode = .webNetworkRequestFailed
  290. case kURLResponseErrorCodeInternalError:
  291. errorCode = .webInternalError
  292. default:
  293. return AuthErrorUtils.webSignInUserInteractionFailure(reason: "[\(code)] - \(message ?? "")")
  294. }
  295. return error(code: errorCode, message: message)
  296. }
  297. @objc public static func nullUserError(message: String?) -> Error {
  298. error(code: .nullUser, message: message)
  299. }
  300. @objc public static func invalidProviderIDError(message: String?) -> Error {
  301. error(code: .invalidProviderID, message: message)
  302. }
  303. @objc public static func invalidDynamicLinkDomainError(message: String?) -> Error {
  304. error(code: .invalidDynamicLinkDomain, message: message)
  305. }
  306. @objc public static func missingOrInvalidNonceError(message: String?) -> Error {
  307. error(code: .missingOrInvalidNonce, message: message)
  308. }
  309. @objc public static func keychainError(function: String, status: OSStatus) -> Error {
  310. let reason = "\(function) (\(status))"
  311. return error(code: .keychainError, userInfo: [NSLocalizedFailureReasonErrorKey: reason])
  312. }
  313. @objc public static func tenantIDMismatchError() -> Error {
  314. error(code: .tenantIDMismatch)
  315. }
  316. @objc public static func unsupportedTenantOperationError() -> Error {
  317. error(code: .unsupportedTenantOperation)
  318. }
  319. @objc public static func notificationNotForwardedError() -> Error {
  320. error(code: .notificationNotForwarded)
  321. }
  322. @objc public static func appNotVerifiedError(message: String?) -> Error {
  323. error(code: .appNotVerified, message: message)
  324. }
  325. @objc public static func missingClientIdentifierError(message: String?) -> Error {
  326. error(code: .missingClientIdentifier, message: message)
  327. }
  328. @objc public static func captchaCheckFailedError(message: String?) -> Error {
  329. error(code: .captchaCheckFailed, message: message)
  330. }
  331. @objc public static func unexpectedResponse(data: Data?, underlyingError: Error?) -> Error {
  332. var userInfo: [String: Any] = [:]
  333. if let data {
  334. userInfo[userInfoDataKey] = data
  335. }
  336. if let underlyingError {
  337. userInfo[NSUnderlyingErrorKey] = underlyingError
  338. }
  339. return error(code: .internal(.unexpectedResponse), userInfo: userInfo)
  340. }
  341. @objc public static func unexpectedErrorResponse(data: Data?,
  342. underlyingError: Error?) -> Error {
  343. var userInfo: [String: Any] = [:]
  344. if let data {
  345. userInfo[userInfoDataKey] = data
  346. }
  347. if let underlyingError {
  348. userInfo[NSUnderlyingErrorKey] = underlyingError
  349. }
  350. return error(code: .internal(.unexpectedErrorResponse), userInfo: userInfo)
  351. }
  352. @objc public static func unexpectedErrorResponse(deserializedResponse: Any?) -> Error {
  353. var userInfo: [String: Any]?
  354. if let deserializedResponse {
  355. userInfo = [userInfoDeserializedResponseKey: deserializedResponse]
  356. }
  357. return error(code: .internal(.unexpectedErrorResponse), userInfo: userInfo)
  358. }
  359. @objc public static func unexpectedResponse(deserializedResponse: Any?) -> Error {
  360. var userInfo: [String: Any]?
  361. if let deserializedResponse {
  362. userInfo = [userInfoDeserializedResponseKey: deserializedResponse]
  363. }
  364. return error(code: .internal(.unexpectedResponse), userInfo: userInfo)
  365. }
  366. @objc public static func unexpectedResponse(deserializedResponse: Any?,
  367. underlyingError: Error?) -> Error {
  368. var userInfo: [String: Any] = [:]
  369. if let deserializedResponse {
  370. userInfo[userInfoDeserializedResponseKey] = deserializedResponse
  371. }
  372. if let underlyingError {
  373. userInfo[NSUnderlyingErrorKey] = underlyingError
  374. }
  375. return error(code: .internal(.unexpectedResponse), userInfo: userInfo)
  376. }
  377. @objc public static func unexpectedErrorResponse(deserializedResponse: Any?,
  378. underlyingError: Error?) -> Error {
  379. var userInfo: [String: Any] = [:]
  380. if let deserializedResponse {
  381. userInfo[userInfoDeserializedResponseKey] = deserializedResponse
  382. }
  383. if let underlyingError {
  384. userInfo[NSUnderlyingErrorKey] = underlyingError
  385. }
  386. return error(
  387. code: .internal(.unexpectedErrorResponse),
  388. userInfo: userInfo.isEmpty ? nil : userInfo
  389. )
  390. }
  391. @objc public static func malformedJWTError(token: String, underlyingError: Error?) -> Error {
  392. var userInfo: [String: Any] = [
  393. NSLocalizedDescriptionKey: kFIRAuthErrorMessageMalformedJWT,
  394. userInfoDataKey: token,
  395. ]
  396. if let underlyingError {
  397. userInfo[NSUnderlyingErrorKey] = underlyingError
  398. }
  399. return error(code: .malformedJWT, userInfo: userInfo)
  400. }
  401. @objc public static func RPCResponseDecodingError(deserializedResponse: Any?,
  402. underlyingError: Error?) -> Error {
  403. var userInfo: [String: Any] = [:]
  404. if let deserializedResponse {
  405. userInfo[userInfoDeserializedResponseKey] = deserializedResponse
  406. }
  407. if let underlyingError {
  408. userInfo[NSUnderlyingErrorKey] = underlyingError
  409. }
  410. return error(code: .internal(.RPCResponseDecodingError), userInfo: userInfo)
  411. }
  412. @objc public static func accountExistsWithDifferentCredentialError(email: String?,
  413. updatedCredential: AuthCredential?)
  414. -> Error {
  415. var userInfo: [String: Any] = [:]
  416. if let email {
  417. userInfo[userInfoEmailKey] = email
  418. }
  419. if let updatedCredential {
  420. userInfo[userInfoUpdatedCredentialKey] = updatedCredential
  421. }
  422. return error(code: .accountExistsWithDifferentCredential, userInfo: userInfo)
  423. }
  424. @objc public static func blockingCloudFunctionServerResponse(message: String?) -> Error {
  425. guard let message else {
  426. return error(code: .blockingCloudFunctionError, message: message)
  427. }
  428. var jsonString = message.replacingOccurrences(
  429. of: "HTTP Cloud Function returned an error:",
  430. with: ""
  431. )
  432. jsonString = jsonString.trimmingCharacters(in: .whitespaces)
  433. let jsonData = jsonString.data(using: .utf8) ?? Data()
  434. do {
  435. let jsonDict = try JSONSerialization
  436. .jsonObject(with: jsonData, options: []) as? [String: Any] ?? [:]
  437. let errorDict = jsonDict["error"] as? [String: Any] ?? [:]
  438. let errorMessage = errorDict["message"] as? String
  439. return error(code: .blockingCloudFunctionError, message: errorMessage)
  440. } catch {
  441. return JSONSerializationError(underlyingError: error)
  442. }
  443. }
  444. #if os(iOS)
  445. // TODO(ncooke3): Address the optionality of these arguments.
  446. @objc public static func secondFactorRequiredError(pendingCredential: String?,
  447. hints: [MultiFactorInfo]?,
  448. auth: Auth)
  449. -> Error {
  450. var userInfo: [String: Any] = [:]
  451. if let pendingCredential = pendingCredential, let hints = hints {
  452. let resolver = MultiFactorResolver(with: pendingCredential, hints: hints, auth: auth)
  453. userInfo[userInfoMultiFactorResolverKey] = resolver
  454. }
  455. return error(code: .secondFactorRequired, userInfo: userInfo)
  456. }
  457. #endif // os(iOS)
  458. }
  459. @objc public protocol MultiFactorResolverWrapper: NSObjectProtocol {}