AuthAPNSTokenManager.swift 8.3 KB

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