AuthAPNSTokenManager.swift 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. @objc public protocol AuthAPNSTokenApplication {
  25. func registerForRemoteNotifications()
  26. }
  27. extension UIApplication: AuthAPNSTokenApplication {}
  28. // TODO: remove objc public here and below after Sample ported.
  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. @objc(FIRAuthAPNSTokenManager) public 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. /** @fn getTokenWithCallback:
  48. @brief Attempts to get the APNs token.
  49. @param callback The block to be called either immediately or in future, either when a token
  50. becomes available, or when timeout occurs, whichever happens earlier.
  51. */
  52. @objc public func getToken(callback: @escaping (AuthAPNSToken?, Error?) -> Void) {
  53. if failFastForTesting {
  54. let error = NSError(domain: "dummy domain", code: AuthErrorCode.missingAppToken.rawValue)
  55. callback(nil, error)
  56. return
  57. }
  58. if let token = tokenStore {
  59. callback(token, nil)
  60. return
  61. }
  62. if pendingCallbacks.count > 0 {
  63. pendingCallbacks.append(callback)
  64. return
  65. }
  66. pendingCallbacks = [callback]
  67. DispatchQueue.main.async {
  68. self.application.registerForRemoteNotifications()
  69. }
  70. let applicableCallbacks = pendingCallbacks
  71. let deadline = DispatchTime.now() + timeout
  72. kAuthGlobalWorkQueue.asyncAfter(deadline: deadline) {
  73. // Only cancel if the pending callbacks remain the same, i.e., not triggered yet.
  74. if applicableCallbacks.count == self.pendingCallbacks.count {
  75. self.callback(withToken: nil, error: nil)
  76. }
  77. }
  78. }
  79. /** @property token
  80. @brief The APNs token, if one is available.
  81. @remarks Setting a token with AuthAPNSTokenTypeUnknown will automatically converts it to
  82. a token with the automatically detected type.
  83. */
  84. @objc public var token: AuthAPNSToken? {
  85. get {
  86. return 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. /** @fn cancelWithError:
  106. @brief Cancels any pending `getTokenWithCallback:` request.
  107. @param error The error to return.
  108. */
  109. func cancel(withError error: Error) {
  110. callback(withToken: nil, error: error)
  111. }
  112. var failFastForTesting: Bool = false
  113. // `application` is a var to enable unit test faking.
  114. var application: AuthAPNSTokenApplication
  115. private var pendingCallbacks: [(AuthAPNSToken?, Error?) -> Void] = []
  116. private func callback(withToken token: AuthAPNSToken?, error: Error?) {
  117. let pendingCallbacks = self.pendingCallbacks
  118. self.pendingCallbacks = []
  119. for callback in pendingCallbacks {
  120. callback(token, error)
  121. }
  122. }
  123. private func isProductionApp() -> Bool {
  124. let defaultAppTypeProd = true
  125. if GULAppEnvironmentUtil.isSimulator() {
  126. AuthLog.logInfo(code: "I-AUT000006", message: "Assuming prod APNs token type on simulator.")
  127. return defaultAppTypeProd
  128. }
  129. // Apps distributed via AppStore or TestFlight use the Production APNS certificates.
  130. if GULAppEnvironmentUtil.isFromAppStore() {
  131. return defaultAppTypeProd
  132. }
  133. // TODO: resolve https://github.com/firebase/firebase-ios-sdk/issues/10921
  134. if Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt" {
  135. // Distributed via TestFlight
  136. return defaultAppTypeProd
  137. }
  138. let path = Bundle.main.bundlePath + "embedded.mobileprovision"
  139. guard let url = URL(string: path) else {
  140. AuthLog.logInfo(code: "I-AUT000007", message: "\(path) does not exist")
  141. return defaultAppTypeProd
  142. }
  143. do {
  144. let profileData = try Data(contentsOf: url)
  145. // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals the
  146. // end of a c-string and halts the ASCII parser, or with value > 127, which violates strict 7-bit
  147. // ASCII. Replace any 0s or invalid characters in the input.
  148. let byteArray = [UInt8](profileData)
  149. var outBytes: [UInt8] = []
  150. for byte in byteArray {
  151. if byte == 0 || byte > 127 {
  152. outBytes.append(46) // ASCII '.'
  153. } else {
  154. outBytes.append(byte)
  155. }
  156. }
  157. guard let embeddedProfile = String(bytes: outBytes, encoding: .utf8) else {
  158. AuthLog.logInfo(code: "I-AUT000008",
  159. message: "Error while reading embedded mobileprovision. Failed to convert to String")
  160. return defaultAppTypeProd
  161. }
  162. // TODO: This code needs iOS 13. Use split instead?
  163. // let scanner = Scanner(string: embeddedProfile)
  164. // if scanner.scanUpToString("<plist") != nil {
  165. // if let plistContents = scanner.scanUpToString("</plist>")
  166. // }
  167. } catch {
  168. AuthLog.logInfo(code: "I-AUT000008",
  169. message: "Error while reading embedded mobileprovision \(error)")
  170. return defaultAppTypeProd
  171. }
  172. // TODO: Finish this port
  173. // NSMutableData *profileData = [NSMutableData dataWithContentsOfFile:path options:0 error:&error];
  174. //
  175. // if (!profileData.length || error) {
  176. // FIRLogInfo(kFIRLoggerAuth, @"I-AUT000007", @"Error while reading embedded mobileprovision %@",
  177. // error);
  178. // return defaultAppTypeProd;
  179. // }
  180. // NSScanner *scanner = [NSScanner scannerWithString:embeddedProfile];
  181. // NSString *plistContents;
  182. // if ([scanner scanUpToString:@"<plist" intoString:nil]) {
  183. // if ([scanner scanUpToString:@"</plist>" intoString:&plistContents]) {
  184. // TODO: how does a file name get read with this append?
  185. // plistContents = [plistContents stringByAppendingString:@"</plist>"];
  186. // }
  187. // }
  188. //
  189. // if (!plistContents.length) {
  190. // return defaultAppTypeProd;
  191. // }
  192. //
  193. // NSData *data = [plistContents dataUsingEncoding:NSUTF8StringEncoding];
  194. // if (!data.length) {
  195. // FIRLogInfo(kFIRLoggerAuth, @"I-AUT000009",
  196. // @"Couldn't read plist fetched from embedded mobileprovision");
  197. // return defaultAppTypeProd;
  198. // }
  199. //
  200. // NSError *plistMapError;
  201. // id plistData = [NSPropertyListSerialization propertyListWithData:data
  202. // options:NSPropertyListImmutable
  203. // format:nil
  204. // error:&plistMapError];
  205. // if (plistMapError || ![plistData isKindOfClass:[NSDictionary class]]) {
  206. // FIRLogInfo(kFIRLoggerAuth, @"I-AUT000010", @"Error while converting assumed plist to dict %@",
  207. // plistMapError.localizedDescription);
  208. // return defaultAppTypeProd;
  209. // }
  210. // NSDictionary *plistMap = (NSDictionary *)plistData;
  211. //
  212. // if ([plistMap valueForKeyPath:@"ProvisionedDevices"]) {
  213. // FIRLogInfo(kFIRLoggerAuth, @"I-AUT000011",
  214. // @"Provisioning profile has specifically provisioned devices, "
  215. // @"most likely a Dev profile.");
  216. // }
  217. //
  218. // NSString *apsEnvironment = [plistMap valueForKeyPath:@"Entitlements.aps-environment"];
  219. // FIRLogDebug(kFIRLoggerAuth, @"I-AUT000012", @"APNS Environment in profile: %@", apsEnvironment);
  220. //
  221. // // No aps-environment in the profile.
  222. // if (!apsEnvironment.length) {
  223. // FIRLogInfo(kFIRLoggerAuth, @"I-AUT000013",
  224. // @"No aps-environment set. If testing on a device APNS is not "
  225. // @"correctly configured. Please recheck your provisioning profiles.");
  226. // return defaultAppTypeProd;
  227. // }
  228. //
  229. // if ([apsEnvironment isEqualToString:@"development"]) {
  230. // return NO;
  231. // }
  232. return defaultAppTypeProd
  233. }
  234. }
  235. #endif