AuthAPNSTokenManager.swift 8.2 KB

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