AuthAPNSTokenManager.swift 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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 {
  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 (Result<AuthAPNSToken, Error>) -> Void) {
  46. if let token = tokenStore {
  47. callback(.success(token))
  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(.failure(AuthErrorUtils.missingAppTokenError(underlyingError: nil)))
  64. }
  65. }
  66. }
  67. func getToken() async throws -> AuthAPNSToken {
  68. return try await withCheckedThrowingContinuation { continuation in
  69. self.getTokenInternal { result in
  70. switch result {
  71. case let .success(token):
  72. continuation.resume(returning: token)
  73. case let .failure(error):
  74. continuation.resume(throwing: error)
  75. }
  76. }
  77. }
  78. }
  79. /// The APNs token, if one is available.
  80. ///
  81. /// Setting a token with AuthAPNSTokenTypeUnknown will automatically converts it to
  82. /// a token with the automatically detected type.
  83. var token: AuthAPNSToken? {
  84. get {
  85. tokenStore
  86. }
  87. set(setToken) {
  88. guard let setToken else {
  89. tokenStore = nil
  90. return
  91. }
  92. var newToken = setToken
  93. if setToken.type == AuthAPNSTokenType.unknown {
  94. let detectedTokenType = isProductionApp() ? AuthAPNSTokenType.prod : AuthAPNSTokenType
  95. .sandbox
  96. newToken = AuthAPNSToken(withData: setToken.data, type: detectedTokenType)
  97. }
  98. tokenStore = newToken
  99. callback(.success(newToken))
  100. }
  101. }
  102. /// Should only be written to in tests
  103. var tokenStore: AuthAPNSToken?
  104. /// Cancels any pending `getTokenWithCallback:` request.
  105. /// - Parameter error: The error to return .
  106. func cancel(withError error: Error) {
  107. callback(.failure(error))
  108. }
  109. /// Enable unit test faking.
  110. var application: AuthAPNSTokenApplication
  111. private var pendingCallbacks: [(Result<AuthAPNSToken, Error>) -> Void] = []
  112. private func callback(_ result: Result<AuthAPNSToken, Error>) {
  113. let pendingCallbacks = self.pendingCallbacks
  114. self.pendingCallbacks = []
  115. for callback in pendingCallbacks {
  116. callback(result)
  117. }
  118. }
  119. private func isProductionApp() -> Bool {
  120. let defaultAppTypeProd = true
  121. if GULAppEnvironmentUtil.isSimulator() {
  122. AuthLog.logInfo(code: "I-AUT000006", message: "Assuming prod APNs token type on simulator.")
  123. return defaultAppTypeProd
  124. }
  125. // Apps distributed via AppStore or TestFlight use the Production APNS certificates.
  126. if GULAppEnvironmentUtil.isFromAppStore() {
  127. return defaultAppTypeProd
  128. }
  129. // TODO: resolve https://github.com/firebase/firebase-ios-sdk/issues/10921
  130. // to support TestFlight
  131. let path = Bundle.main.bundlePath + "/" + "embedded.mobileprovision"
  132. do {
  133. let profileData = try NSData(contentsOfFile: path) as Data
  134. // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals
  135. // the end of a c-string and halts the ASCII parser, or with value > 127, which violates
  136. // strict 7-bit ASCII. Replace any 0s or invalid characters in the input.
  137. let byteArray = [UInt8](profileData)
  138. var outBytes: [UInt8] = []
  139. for byte in byteArray {
  140. if byte == 0 || byte > 127 {
  141. outBytes.append(46) // ASCII '.'
  142. } else {
  143. outBytes.append(byte)
  144. }
  145. }
  146. guard let embeddedProfile = String(bytes: outBytes, encoding: .utf8) else {
  147. AuthLog.logInfo(code: "I-AUT000008",
  148. message: "Error while reading embedded mobileprovision. " +
  149. "Failed to convert to String")
  150. return defaultAppTypeProd
  151. }
  152. let scanner = Scanner(string: embeddedProfile)
  153. if scanner.scanUpToString("<plist") != nil {
  154. guard let plistContents = scanner.scanUpToString("</plist>")?.appending("</plist>"),
  155. let data = plistContents.data(using: .utf8) else {
  156. return defaultAppTypeProd
  157. }
  158. do {
  159. let plistData = try PropertyListSerialization.propertyList(from: data, format: nil)
  160. guard let plistMap = plistData as? [String: Any] else {
  161. AuthLog.logInfo(code: "I-AUT000008",
  162. message: "Error while converting assumed plist to dictionary.")
  163. return defaultAppTypeProd
  164. }
  165. if plistMap["ProvisionedDevices"] != nil {
  166. AuthLog.logInfo(code: "I-AUT000011",
  167. message: "Provisioning profile has specifically provisioned devices, " +
  168. "most likely a Dev profile.")
  169. }
  170. guard let entitlements = plistMap["Entitlements"] as? [String: Any],
  171. let apsEnvironment = entitlements["aps-environment"] as? String else {
  172. AuthLog.logInfo(code: "I-AUT000013",
  173. message: "No aps-environment set. If testing on a device APNS is not " +
  174. "correctly configured. Please recheck your provisioning profiles.")
  175. return defaultAppTypeProd
  176. }
  177. AuthLog.logDebug(code: "I-AUT000012",
  178. message: "APNS Environment in profile: \(apsEnvironment)")
  179. if apsEnvironment == "development" {
  180. return false
  181. }
  182. } catch {
  183. AuthLog.logInfo(code: "I-AUT000008",
  184. message: "Error while converting assumed plist to dict " +
  185. "\(error.localizedDescription)")
  186. }
  187. }
  188. } catch {
  189. AuthLog.logInfo(code: "I-AUT000008",
  190. message: "Error while reading embedded mobileprovision \(error)")
  191. }
  192. return defaultAppTypeProd
  193. }
  194. }
  195. #endif