AuthRecaptchaVerifier.swift 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. #if os(iOS)
  15. import Foundation
  16. #if SWIFT_PACKAGE
  17. import FirebaseAuthInternal
  18. #endif
  19. import RecaptchaInterop
  20. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  21. class AuthRecaptchaConfig {
  22. var siteKey: String?
  23. let enablementStatus: [AuthRecaptchaProvider: AuthRecaptchaEnablementStatus]
  24. init(siteKey: String? = nil,
  25. enablementStatus: [AuthRecaptchaProvider: AuthRecaptchaEnablementStatus]) {
  26. self.siteKey = siteKey
  27. self.enablementStatus = enablementStatus
  28. }
  29. }
  30. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  31. enum AuthRecaptchaEnablementStatus: String, CaseIterable {
  32. case enforce = "ENFORCE"
  33. case audit = "AUDIT"
  34. case off = "OFF"
  35. // Convenience property for mapping values
  36. var stringValue: String { rawValue }
  37. }
  38. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  39. enum AuthRecaptchaProvider: String, CaseIterable {
  40. case password = "EMAIL_PASSWORD_PROVIDER"
  41. case phone = "PHONE_PROVIDER"
  42. // Convenience property for mapping values
  43. var stringValue: String { rawValue }
  44. }
  45. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  46. enum AuthRecaptchaAction: String {
  47. case defaultAction
  48. case signInWithPassword
  49. case getOobCode
  50. case signUpPassword
  51. case sendVerificationCode
  52. case mfaSmsSignIn
  53. case mfaSmsEnrollment
  54. // Convenience property for mapping values
  55. var stringValue: String { rawValue }
  56. }
  57. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  58. class AuthRecaptchaVerifier {
  59. private(set) weak var auth: Auth?
  60. private(set) var agentConfig: AuthRecaptchaConfig?
  61. private(set) var tenantConfigs: [String: AuthRecaptchaConfig] = [:]
  62. private(set) var recaptchaClient: RCARecaptchaClientProtocol?
  63. private static var _shared = AuthRecaptchaVerifier()
  64. private let kRecaptchaVersion = "RECAPTCHA_ENTERPRISE"
  65. init() {}
  66. class func shared(auth: Auth?) -> AuthRecaptchaVerifier {
  67. if _shared.auth != auth {
  68. _shared.agentConfig = nil
  69. _shared.tenantConfigs = [:]
  70. _shared.auth = auth
  71. }
  72. return _shared
  73. }
  74. /// This function is only for testing.
  75. class func setShared(_ instance: AuthRecaptchaVerifier, auth: Auth?) {
  76. _shared = instance
  77. _ = shared(auth: auth)
  78. }
  79. func siteKey() -> String? {
  80. if let tenantID = auth?.tenantID {
  81. if let config = tenantConfigs[tenantID] {
  82. return config.siteKey
  83. }
  84. return nil
  85. }
  86. return agentConfig?.siteKey
  87. }
  88. func enablementStatus(forProvider provider: AuthRecaptchaProvider)
  89. -> AuthRecaptchaEnablementStatus {
  90. if let tenantID = auth?.tenantID,
  91. let tenantConfig = tenantConfigs[tenantID],
  92. let status = tenantConfig.enablementStatus[provider] {
  93. return status
  94. } else if let agentConfig = agentConfig,
  95. let status = agentConfig.enablementStatus[provider] {
  96. return status
  97. } else {
  98. return AuthRecaptchaEnablementStatus.off
  99. }
  100. }
  101. func verify(forceRefresh: Bool, action: AuthRecaptchaAction) async throws -> String {
  102. try await retrieveRecaptchaConfig(forceRefresh: forceRefresh)
  103. guard let siteKey = siteKey() else {
  104. throw AuthErrorUtils.recaptchaSiteKeyMissing()
  105. }
  106. let actionString = action.stringValue
  107. #if !(COCOAPODS || SWIFT_PACKAGE)
  108. // No recaptcha on internal build system.
  109. return actionString
  110. #else
  111. return try await withCheckedThrowingContinuation { continuation in
  112. FIRRecaptchaGetToken(siteKey, actionString,
  113. "NO_RECAPTCHA") { (token: String, error: Error?,
  114. linked: Bool, actionCreated: Bool) in
  115. guard linked else {
  116. continuation.resume(throwing: AuthErrorUtils.recaptchaSDKNotLinkedError())
  117. return
  118. }
  119. guard actionCreated else {
  120. continuation.resume(throwing: AuthErrorUtils.recaptchaActionCreationFailed())
  121. return
  122. }
  123. if let error {
  124. continuation.resume(throwing: error)
  125. return
  126. } else {
  127. if token == "NO_RECAPTCHA" {
  128. AuthLog.logInfo(code: "I-AUT000031",
  129. message: "reCAPTCHA token retrieval failed. NO_RECAPTCHA sent as the fake code.")
  130. } else {
  131. AuthLog.logInfo(
  132. code: "I-AUT000030",
  133. message: "reCAPTCHA token retrieval succeeded."
  134. )
  135. }
  136. continuation.resume(returning: token)
  137. }
  138. }
  139. }
  140. #endif // !(COCOAPODS || SWIFT_PACKAGE)
  141. }
  142. func retrieveRecaptchaConfig(forceRefresh: Bool) async throws {
  143. if !forceRefresh {
  144. if let tenantID = auth?.tenantID {
  145. if tenantConfigs[tenantID] != nil {
  146. return
  147. }
  148. } else if agentConfig != nil {
  149. return
  150. }
  151. }
  152. guard let auth = auth else {
  153. throw AuthErrorUtils.error(code: .recaptchaNotEnabled,
  154. message: "No requestConfiguration for Auth instance")
  155. }
  156. let request = GetRecaptchaConfigRequest(requestConfiguration: auth.requestConfiguration)
  157. let response = try await auth.backend.call(with: request)
  158. AuthLog.logInfo(code: "I-AUT000029", message: "reCAPTCHA config retrieval succeeded.")
  159. try await parseRecaptchaConfigFromResponse(response: response)
  160. }
  161. func parseRecaptchaConfigFromResponse(response: GetRecaptchaConfigResponse) async throws {
  162. var enablementStatus: [AuthRecaptchaProvider: AuthRecaptchaEnablementStatus] = [:]
  163. var isRecaptchaEnabled = false
  164. if let enforcementState = response.enforcementState {
  165. for state in enforcementState {
  166. guard let providerString = state["provider"],
  167. let enforcementString = state["enforcementState"],
  168. let provider = AuthRecaptchaProvider(rawValue: providerString),
  169. let enforcement = AuthRecaptchaEnablementStatus(rawValue: enforcementString) else {
  170. continue // Skip to the next state in the loop
  171. }
  172. enablementStatus[provider] = enforcement
  173. if enforcement != .off {
  174. isRecaptchaEnabled = true
  175. }
  176. }
  177. }
  178. var siteKey = ""
  179. // Response's site key is of the format projects/<project-id>/keys/<site-key>'
  180. if isRecaptchaEnabled {
  181. if let recaptchaKey = response.recaptchaKey {
  182. let keys = recaptchaKey.components(separatedBy: "/")
  183. if keys.count != 4 {
  184. throw AuthErrorUtils.error(code: .recaptchaNotEnabled, message: "Invalid siteKey")
  185. }
  186. siteKey = keys[3]
  187. }
  188. }
  189. let config = AuthRecaptchaConfig(siteKey: siteKey, enablementStatus: enablementStatus)
  190. if let tenantID = auth?.tenantID {
  191. tenantConfigs[tenantID] = config
  192. } else {
  193. agentConfig = config
  194. }
  195. }
  196. func injectRecaptchaFields(request: any AuthRPCRequest,
  197. provider: AuthRecaptchaProvider,
  198. action: AuthRecaptchaAction) async throws {
  199. try await retrieveRecaptchaConfig(forceRefresh: false)
  200. if enablementStatus(forProvider: provider) != .off {
  201. let token = try await verify(forceRefresh: false, action: action)
  202. request.injectRecaptchaFields(recaptchaResponse: token, recaptchaVersion: kRecaptchaVersion)
  203. } else {
  204. request.injectRecaptchaFields(recaptchaResponse: nil, recaptchaVersion: kRecaptchaVersion)
  205. }
  206. }
  207. }
  208. #endif