AuthAPNSTokenManager.swift 8.6 KB

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