AuthAPNSTokenManager.swift 8.3 KB

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