AuthAPNSTokenManager.swift 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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(macOS) && !os(watchOS)
  15. import Foundation
  16. import UIKit
  17. // TODO: This may be needed for extension detecting support
  18. // @_implementationOnly import FirebaseCoreExtension
  19. #if SWIFT_PACKAGE
  20. @_implementationOnly import GoogleUtilities_Environment
  21. #else
  22. @_implementationOnly import GoogleUtilities
  23. #endif // SWIFT_PACKAGE
  24. @objc public protocol AuthAPNSTokenApplication {
  25. func registerForRemoteNotifications()
  26. }
  27. extension UIApplication: AuthAPNSTokenApplication {}
  28. // TODO: remove objc public here and below after Sample ported.
  29. /** @class AuthAPNSToken
  30. @brief A data structure for an APNs token.
  31. */
  32. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  33. @objc(FIRAuthAPNSTokenManager) public class AuthAPNSTokenManager: NSObject {
  34. /** @property timeout
  35. @brief The timeout for registering for remote notification.
  36. @remarks Only tests should access this property.
  37. */
  38. var timeout: TimeInterval = 5
  39. /** @fn initWithApplication:
  40. @brief Initializes the instance.
  41. @param application The @c UIApplication to request the token from.
  42. @return The initialized instance.
  43. */
  44. init(withApplication application: AuthAPNSTokenApplication) {
  45. self.application = application
  46. }
  47. /** @fn getTokenWithCallback:
  48. @brief Attempts to get the APNs token.
  49. @param callback The block to be called either immediately or in future, either when a token
  50. becomes available, or when timeout occurs, whichever happens earlier.
  51. */
  52. @objc public func getToken(callback: @escaping (AuthAPNSToken?, Error?) -> Void) {
  53. if failFastForTesting {
  54. let error = NSError(domain: "dummy domain", code: AuthErrorCode.missingAppToken.rawValue)
  55. callback(nil, error)
  56. return
  57. }
  58. if let token = tokenStore {
  59. callback(token, nil)
  60. return
  61. }
  62. if pendingCallbacks.count > 0 {
  63. pendingCallbacks.append(callback)
  64. return
  65. }
  66. pendingCallbacks = [callback]
  67. DispatchQueue.main.async {
  68. self.application.registerForRemoteNotifications()
  69. }
  70. let applicableCallbacks = pendingCallbacks
  71. let deadline = DispatchTime.now() + timeout
  72. kAuthGlobalWorkQueue.asyncAfter(deadline: deadline) {
  73. // Only cancel if the pending callbacks remain the same, i.e., not triggered yet.
  74. if applicableCallbacks.count == self.pendingCallbacks.count {
  75. self.callback(withToken: nil, error: nil)
  76. }
  77. }
  78. }
  79. /** @property token
  80. @brief The APNs token, if one is available.
  81. @remarks Setting a token with AuthAPNSTokenTypeUnknown will automatically converts it to
  82. a token with the automatically detected type.
  83. */
  84. @objc public var token: AuthAPNSToken? {
  85. get {
  86. return tokenStore
  87. }
  88. set(setToken) {
  89. guard let setToken else {
  90. tokenStore = nil
  91. return
  92. }
  93. var newToken = setToken
  94. if setToken.type == AuthAPNSTokenType.unknown {
  95. let detectedTokenType = isProductionApp() ? AuthAPNSTokenType.prod : AuthAPNSTokenType
  96. .sandbox
  97. newToken = AuthAPNSToken(withData: setToken.data, type: detectedTokenType)
  98. }
  99. tokenStore = newToken
  100. callback(withToken: newToken, error: nil)
  101. }
  102. }
  103. // Should only be written to in tests
  104. var tokenStore: AuthAPNSToken?
  105. /** @fn cancelWithError:
  106. @brief Cancels any pending `getTokenWithCallback:` request.
  107. @param error The error to return.
  108. */
  109. func cancel(withError error: Error) {
  110. callback(withToken: nil, error: error)
  111. }
  112. var failFastForTesting: Bool = false
  113. // `application` is a var to enable unit test faking.
  114. var application: AuthAPNSTokenApplication
  115. private var pendingCallbacks: [(AuthAPNSToken?, Error?) -> Void] = []
  116. private func callback(withToken token: AuthAPNSToken?, error: Error?) {
  117. let pendingCallbacks = self.pendingCallbacks
  118. self.pendingCallbacks = []
  119. for callback in pendingCallbacks {
  120. callback(token, error)
  121. }
  122. }
  123. private func isProductionApp() -> Bool {
  124. let defaultAppTypeProd = true
  125. if GULAppEnvironmentUtil.isSimulator() {
  126. AuthLog.logInfo(code: "I-AUT000006", message: "Assuming prod APNs token type on simulator.")
  127. return defaultAppTypeProd
  128. }
  129. // Apps distributed via AppStore or TestFlight use the Production APNS certificates.
  130. if GULAppEnvironmentUtil.isFromAppStore() {
  131. return defaultAppTypeProd
  132. }
  133. // TODO: resolve https://github.com/firebase/firebase-ios-sdk/issues/10921
  134. if Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt" {
  135. // Distributed via TestFlight
  136. return defaultAppTypeProd
  137. }
  138. let path = Bundle.main.bundlePath + "embedded.mobileprovision"
  139. guard let url = URL(string: path) else {
  140. AuthLog.logInfo(code: "I-AUT000007", message: "\(path) does not exist")
  141. return defaultAppTypeProd
  142. }
  143. do {
  144. let profileData = try Data(contentsOf: url)
  145. // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals
  146. // the end of a c-string and halts the ASCII parser, or with value > 127, which violates
  147. // strict 7-bit ASCII. Replace any 0s or invalid characters in the input.
  148. let byteArray = [UInt8](profileData)
  149. var outBytes: [UInt8] = []
  150. for byte in byteArray {
  151. if byte == 0 || byte > 127 {
  152. outBytes.append(46) // ASCII '.'
  153. } else {
  154. outBytes.append(byte)
  155. }
  156. }
  157. guard let embeddedProfile = String(bytes: outBytes, encoding: .utf8) else {
  158. AuthLog.logInfo(code: "I-AUT000008",
  159. message: "Error while reading embedded mobileprovision. " +
  160. "Failed to convert to String")
  161. return defaultAppTypeProd
  162. }
  163. let scanner = Scanner(string: embeddedProfile)
  164. if scanner.scanUpToString("<plist") != nil {
  165. guard let plistContents = scanner.scanUpToString("</plist>"),
  166. let data = plistContents.data(using: .utf8) else {
  167. return defaultAppTypeProd
  168. }
  169. do {
  170. let plistData = try PropertyListSerialization.propertyList(from: data, format: nil)
  171. guard let plistMap = plistData as? [String: Any] else {
  172. AuthLog.logInfo(code: "I-AUT000008",
  173. message: "Error while converting assumed plist to dictionary.")
  174. return defaultAppTypeProd
  175. }
  176. if plistMap["ProvisionedDevices"] != nil {
  177. AuthLog.logInfo(code: "I-AUT000011",
  178. message: "Provisioning profile has specifically provisioned devices, " +
  179. "most likely a Dev profile.")
  180. }
  181. guard let apsEnvironment = plistMap["Entitlements.aps-environment"] as? String else {
  182. AuthLog.logInfo(code: "I-AUT000013",
  183. message: "No aps-environment set. If testing on a device APNS is not " +
  184. "correctly configured. Please recheck your provisioning profiles.")
  185. return defaultAppTypeProd
  186. }
  187. AuthLog.logDebug(code: "I-AUT000012",
  188. message: "APNS Environment in profile: \(apsEnvironment)")
  189. if apsEnvironment == "development" {
  190. return false
  191. }
  192. } catch {
  193. AuthLog.logInfo(code: "I-AUT000008",
  194. message: "Error while converting assumed plist to dict " +
  195. "\(error.localizedDescription)")
  196. }
  197. }
  198. } catch {
  199. AuthLog.logInfo(code: "I-AUT000008",
  200. message: "Error while reading embedded mobileprovision \(error)")
  201. }
  202. return defaultAppTypeProd
  203. }
  204. }
  205. #endif