AuthRecaptchaVerifier.swift 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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 startMfaSignin
  53. case startMfaEnrollment
  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. class func setShared(_ instance: AuthRecaptchaVerifier, auth: Auth?) {
  75. _shared = instance
  76. _ = shared(auth: auth)
  77. }
  78. func siteKey() -> String? {
  79. if let tenantID = auth?.tenantID {
  80. if let config = tenantConfigs[tenantID] {
  81. return config.siteKey
  82. }
  83. return nil
  84. }
  85. return agentConfig?.siteKey
  86. }
  87. func enablementStatus(forProvider provider: AuthRecaptchaProvider)
  88. -> AuthRecaptchaEnablementStatus {
  89. if let tenantID = auth?.tenantID,
  90. let tenantConfig = tenantConfigs[tenantID],
  91. let status = tenantConfig.enablementStatus[provider] {
  92. return status
  93. } else if let agentConfig = agentConfig,
  94. let status = agentConfig.enablementStatus[provider] {
  95. return status
  96. } else {
  97. return AuthRecaptchaEnablementStatus.off
  98. }
  99. }
  100. func verify(forceRefresh: Bool, action: AuthRecaptchaAction) async throws -> String {
  101. try await retrieveRecaptchaConfig(forceRefresh: forceRefresh)
  102. guard let siteKey = siteKey() else {
  103. throw AuthErrorUtils.recaptchaSiteKeyMissing()
  104. }
  105. let actionString = action.stringValue
  106. #if !(COCOAPODS || SWIFT_PACKAGE)
  107. // No recaptcha on internal build system.
  108. return actionString
  109. #else
  110. return try await withCheckedThrowingContinuation { continuation in
  111. FIRRecaptchaGetToken(siteKey, actionString,
  112. "NO_RECAPTCHA") { (token: String, error: Error?,
  113. linked: Bool, actionCreated: Bool) in
  114. guard linked else {
  115. continuation.resume(throwing: AuthErrorUtils.recaptchaSDKNotLinkedError())
  116. return
  117. }
  118. guard actionCreated else {
  119. continuation.resume(throwing: AuthErrorUtils.recaptchaActionCreationFailed())
  120. return
  121. }
  122. if let error {
  123. continuation.resume(throwing: error)
  124. return
  125. } else {
  126. if token == "NO_RECAPTCHA" {
  127. AuthLog.logInfo(code: "I-AUT000031",
  128. message: "reCAPTCHA token retrieval failed. NO_RECAPTCHA sent as the fake code.")
  129. } else {
  130. AuthLog.logInfo(
  131. code: "I-AUT000030",
  132. message: "reCAPTCHA token retrieval succeeded."
  133. )
  134. }
  135. continuation.resume(returning: token)
  136. }
  137. }
  138. }
  139. #endif // !(COCOAPODS || SWIFT_PACKAGE)
  140. }
  141. func retrieveRecaptchaConfig(forceRefresh: Bool) async throws {
  142. if !forceRefresh {
  143. if let tenantID = auth?.tenantID {
  144. if tenantConfigs[tenantID] != nil {
  145. return
  146. }
  147. } else if agentConfig != nil {
  148. return
  149. }
  150. }
  151. guard let requestConfiguration = auth?.requestConfiguration else {
  152. throw AuthErrorUtils.error(code: .recaptchaNotEnabled,
  153. message: "No requestConfiguration for Auth instance")
  154. }
  155. let request = GetRecaptchaConfigRequest(requestConfiguration: requestConfiguration)
  156. let response = try await AuthBackend.call(with: request)
  157. AuthLog.logInfo(code: "I-AUT000029", message: "reCAPTCHA config retrieval succeeded.")
  158. try await parseRecaptchaConfigFromResponse(response: response)
  159. }
  160. func parseRecaptchaConfigFromResponse(response: GetRecaptchaConfigResponse) async throws {
  161. var enablementStatus: [AuthRecaptchaProvider: AuthRecaptchaEnablementStatus] = [:]
  162. var isRecaptchaEnabled = false
  163. if let enforcementState = response.enforcementState {
  164. for state in enforcementState {
  165. guard let providerString = state["provider"],
  166. let enforcementString = state["enforcementState"],
  167. let provider = AuthRecaptchaProvider(rawValue: providerString),
  168. let enforcement = AuthRecaptchaEnablementStatus(rawValue: enforcementString) else {
  169. continue // Skip to the next state in the loop
  170. }
  171. enablementStatus[provider] = enforcement
  172. if enforcement != .off {
  173. isRecaptchaEnabled = true
  174. }
  175. }
  176. }
  177. var siteKey = ""
  178. // Response's site key is of the format projects/<project-id>/keys/<site-key>'
  179. if isRecaptchaEnabled {
  180. if let recaptchaKey = response.recaptchaKey {
  181. let keys = recaptchaKey.components(separatedBy: "/")
  182. if keys.count != 4 {
  183. throw AuthErrorUtils.error(code: .recaptchaNotEnabled, message: "Invalid siteKey")
  184. }
  185. siteKey = keys[3]
  186. }
  187. }
  188. let config = AuthRecaptchaConfig(siteKey: siteKey, enablementStatus: enablementStatus)
  189. if let tenantID = auth?.tenantID {
  190. tenantConfigs[tenantID] = config
  191. } else {
  192. agentConfig = config
  193. }
  194. }
  195. func injectRecaptchaFields(request: any AuthRPCRequest,
  196. provider: AuthRecaptchaProvider,
  197. action: AuthRecaptchaAction) async throws {
  198. try await retrieveRecaptchaConfig(forceRefresh: false)
  199. if enablementStatus(forProvider: provider) != .off {
  200. let token = try await verify(forceRefresh: false, action: action)
  201. request.injectRecaptchaFields(recaptchaResponse: token, recaptchaVersion: kRecaptchaVersion)
  202. } else {
  203. request.injectRecaptchaFields(recaptchaResponse: nil, recaptchaVersion: kRecaptchaVersion)
  204. }
  205. }
  206. }
  207. #endif