FIRAppCheck.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. /*
  2. * Copyright 2020 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheck.h"
  17. #if __has_include(<FBLPromises/FBLPromises.h>)
  18. #import <FBLPromises/FBLPromises.h>
  19. #else
  20. #import "FBLPromises.h"
  21. #endif
  22. #import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckProvider.h"
  23. #import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckProviderFactory.h"
  24. #import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckToken.h"
  25. #import "FirebaseAppCheck/Sources/Core/Errors/FIRAppCheckErrorUtil.h"
  26. #import "FirebaseAppCheck/Sources/Core/FIRAppCheckLogger.h"
  27. #import "FirebaseAppCheck/Sources/Core/FIRAppCheckSettings.h"
  28. #import "FirebaseAppCheck/Sources/Core/FIRAppCheckTokenResult.h"
  29. #import "FirebaseAppCheck/Sources/Core/Storage/FIRAppCheckStorage.h"
  30. #import "FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefresher.h"
  31. #import "FirebaseAppCheck/Sources/Interop/FIRAppCheckInterop.h"
  32. #import "FirebaseAppCheck/Sources/Interop/FIRAppCheckTokenResultInterop.h"
  33. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  34. NS_ASSUME_NONNULL_BEGIN
  35. /// A notification with the specified name is sent to the default notification center
  36. /// (`NotificationCenter.default`) each time a Firebase app check token is refreshed.
  37. /// The user info dictionary contains `kFIRAppCheckTokenNotificationKey` and
  38. /// `kFIRAppCheckAppNameNotificationKey` keys.
  39. const NSNotificationName FIRAppCheckAppCheckTokenDidChangeNotification =
  40. @"FIRAppCheckAppCheckTokenDidChangeNotification";
  41. /// `userInfo` key for the `AppCheckToken` in `appCheckTokenRefreshNotification`.
  42. NSString *const kFIRAppCheckTokenNotificationKey = @"FIRAppCheckTokenNotificationKey";
  43. /// `userInfo` key for the `FirebaseApp.name` in `appCheckTokenRefreshNotification`.
  44. NSString *const kFIRAppCheckAppNameNotificationKey = @"FIRAppCheckAppNameNotificationKey";
  45. static id<FIRAppCheckProviderFactory> _providerFactory;
  46. static const NSTimeInterval kTokenExpirationThreshold = 5 * 60; // 5 min.
  47. static NSString *const kDummyFACTokenValue = @"eyJlcnJvciI6IlVOS05PV05fRVJST1IifQ==";
  48. @interface FIRAppCheck () <FIRLibrary, FIRAppCheckInterop>
  49. @property(class, nullable) id<FIRAppCheckProviderFactory> providerFactory;
  50. @property(nonatomic, readonly) NSString *appName;
  51. @property(nonatomic, readonly) id<FIRAppCheckProvider> appCheckProvider;
  52. @property(nonatomic, readonly) id<FIRAppCheckStorageProtocol> storage;
  53. @property(nonatomic, readonly) NSNotificationCenter *notificationCenter;
  54. @property(nonatomic, readonly) id<FIRAppCheckSettingsProtocol> settings;
  55. @property(nonatomic, readonly, nullable) id<FIRAppCheckTokenRefresherProtocol> tokenRefresher;
  56. @end
  57. @implementation FIRAppCheck
  58. #pragma mark - FIRComponents
  59. + (void)load {
  60. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self withName:@"fire-app-check"];
  61. }
  62. + (NSArray<FIRComponent *> *)componentsToRegister {
  63. FIRComponentCreationBlock creationBlock =
  64. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  65. *isCacheable = YES;
  66. return [[FIRAppCheck alloc] initWithApp:container.app];
  67. };
  68. // Use eager instantiation timing to give a chance for FAC token to be requested before it is
  69. // actually needed to avoid extra delaying dependent requests.
  70. FIRComponent *appCheckProvider =
  71. [FIRComponent componentWithProtocol:@protocol(FIRAppCheckInterop)
  72. instantiationTiming:FIRInstantiationTimingAlwaysEager
  73. dependencies:@[]
  74. creationBlock:creationBlock];
  75. return @[ appCheckProvider ];
  76. }
  77. - (nullable instancetype)initWithApp:(FIRApp *)app {
  78. id<FIRAppCheckProviderFactory> providerFactory = [FIRAppCheck providerFactory];
  79. if (providerFactory == nil) {
  80. FIRLogError(kFIRLoggerAppCheck, kFIRLoggerAppCheckMessageCodeUnknown,
  81. @"Cannot instantiate `FIRAppCheck` for app: %@ without a provider factory. "
  82. @"Please register a provider factory using "
  83. @"`AppCheck.setAppCheckProviderFactory(_ ,forAppName:)` method.",
  84. app.name);
  85. return nil;
  86. }
  87. id<FIRAppCheckProvider> appCheckProvider = [providerFactory createProviderWithApp:app];
  88. if (appCheckProvider == nil) {
  89. FIRLogError(kFIRLoggerAppCheck, kFIRLoggerAppCheckMessageCodeUnknown,
  90. @"Cannot instantiate `FIRAppCheck` for app: %@ without an app check provider. "
  91. @"Please make sure the provide factory returns a valid app check provider.",
  92. app.name);
  93. return nil;
  94. }
  95. FIRAppCheckSettings *settings =
  96. [[FIRAppCheckSettings alloc] initWithApp:app
  97. userDefault:[NSUserDefaults standardUserDefaults]
  98. mainBundle:[NSBundle mainBundle]];
  99. FIRAppCheckTokenRefresher *tokenRefresher =
  100. [[FIRAppCheckTokenRefresher alloc] initWithTokenExpirationDate:[NSDate date]
  101. tokenExpirationThreshold:kTokenExpirationThreshold
  102. settings:settings];
  103. FIRAppCheckStorage *storage = [[FIRAppCheckStorage alloc] initWithAppName:app.name
  104. appID:app.options.googleAppID
  105. accessGroup:app.options.appGroupID];
  106. return [self initWithAppName:app.name
  107. appCheckProvider:appCheckProvider
  108. storage:storage
  109. tokenRefresher:tokenRefresher
  110. notificationCenter:NSNotificationCenter.defaultCenter
  111. settings:settings];
  112. }
  113. - (instancetype)initWithAppName:(NSString *)appName
  114. appCheckProvider:(id<FIRAppCheckProvider>)appCheckProvider
  115. storage:(id<FIRAppCheckStorageProtocol>)storage
  116. tokenRefresher:(id<FIRAppCheckTokenRefresherProtocol>)tokenRefresher
  117. notificationCenter:(NSNotificationCenter *)notificationCenter
  118. settings:(id<FIRAppCheckSettingsProtocol>)settings {
  119. self = [super init];
  120. if (self) {
  121. _appName = appName;
  122. _appCheckProvider = appCheckProvider;
  123. _storage = storage;
  124. _tokenRefresher = tokenRefresher;
  125. _notificationCenter = notificationCenter;
  126. _settings = settings;
  127. __auto_type __weak weakSelf = self;
  128. tokenRefresher.tokenRefreshHandler = ^(FIRAppCheckTokenRefreshCompletion _Nonnull completion) {
  129. __auto_type strongSelf = weakSelf;
  130. [strongSelf periodicTokenRefreshWithCompletion:completion];
  131. };
  132. }
  133. return self;
  134. }
  135. #pragma mark - Public
  136. + (instancetype)appCheck {
  137. FIRApp *defaultApp = [FIRApp defaultApp];
  138. if (!defaultApp) {
  139. [NSException raise:kFIRAppCheckErrorDomain
  140. format:@"The default FirebaseApp instance must be configured before the default"
  141. @"AppCheck instance can be initialized. One way to ensure that is to "
  142. @"call `[FIRApp configure];` (`FirebaseApp.configure()` in Swift) in the App"
  143. @" Delegate's `application:didFinishLaunchingWithOptions:` "
  144. @"(`application(_:didFinishLaunchingWithOptions:)` in Swift)."];
  145. }
  146. return [self appCheckWithApp:defaultApp];
  147. }
  148. + (nullable instancetype)appCheckWithApp:(FIRApp *)firebaseApp {
  149. id<FIRAppCheckInterop> appCheck = FIR_COMPONENT(FIRAppCheckInterop, firebaseApp.container);
  150. return (FIRAppCheck *)appCheck;
  151. }
  152. + (void)setAppCheckProviderFactory:(nullable id<FIRAppCheckProviderFactory>)factory {
  153. self.providerFactory = factory;
  154. }
  155. - (void)setIsTokenAutoRefreshEnabled:(BOOL)isTokenAutoRefreshEnabled {
  156. self.settings.isTokenAutoRefreshEnabled = isTokenAutoRefreshEnabled;
  157. }
  158. - (BOOL)isTokenAutoRefreshEnabled {
  159. return self.settings.isTokenAutoRefreshEnabled;
  160. }
  161. #pragma mark - App Check Provider Ingestion
  162. + (void)setProviderFactory:(nullable id<FIRAppCheckProviderFactory>)providerFactory {
  163. @synchronized(self) {
  164. _providerFactory = providerFactory;
  165. }
  166. }
  167. + (nullable id<FIRAppCheckProviderFactory>)providerFactory {
  168. @synchronized(self) {
  169. return _providerFactory;
  170. }
  171. }
  172. #pragma mark - FIRAppCheckInterop
  173. - (void)getTokenForcingRefresh:(BOOL)forcingRefresh
  174. completion:(FIRAppCheckTokenHandlerInterop)handler {
  175. [self retrieveOrRefreshTokenForcingRefresh:forcingRefresh]
  176. .then(^id _Nullable(FIRAppCheckToken *token) {
  177. FIRAppCheckTokenResult *result = [[FIRAppCheckTokenResult alloc] initWithToken:token.token
  178. error:nil];
  179. handler(result);
  180. return result;
  181. })
  182. .catch(^(NSError *_Nonnull error) {
  183. FIRAppCheckTokenResult *result =
  184. [[FIRAppCheckTokenResult alloc] initWithToken:kDummyFACTokenValue error:error];
  185. handler(result);
  186. });
  187. }
  188. - (nonnull NSString *)tokenDidChangeNotificationName {
  189. return FIRAppCheckAppCheckTokenDidChangeNotification;
  190. }
  191. - (nonnull NSString *)notificationAppNameKey {
  192. return kFIRAppCheckAppNameNotificationKey;
  193. }
  194. - (nonnull NSString *)notificationTokenKey {
  195. return kFIRAppCheckTokenNotificationKey;
  196. }
  197. #pragma mark - FAA token cache
  198. - (FBLPromise<FIRAppCheckToken *> *)retrieveOrRefreshTokenForcingRefresh:(BOOL)forcingRefresh {
  199. return [self getCachedValidTokenForcingRefresh:forcingRefresh].recover(
  200. ^id _Nullable(NSError *_Nonnull error) {
  201. return [self refreshToken];
  202. });
  203. }
  204. - (FBLPromise<FIRAppCheckToken *> *)getCachedValidTokenForcingRefresh:(BOOL)forcingRefresh {
  205. if (forcingRefresh) {
  206. FBLPromise *rejectedPromise = [FBLPromise pendingPromise];
  207. [rejectedPromise reject:[FIRAppCheckErrorUtil cachedTokenNotFound]];
  208. return rejectedPromise;
  209. }
  210. return [self.storage getToken].then(^id(FIRAppCheckToken *_Nullable token) {
  211. if (token == nil) {
  212. return [FIRAppCheckErrorUtil cachedTokenNotFound];
  213. }
  214. BOOL isTokenExpiredOrExpiresSoon =
  215. [token.expirationDate timeIntervalSinceNow] < kTokenExpirationThreshold;
  216. if (isTokenExpiredOrExpiresSoon) {
  217. return [FIRAppCheckErrorUtil cachedTokenExpired];
  218. }
  219. return token;
  220. });
  221. }
  222. - (FBLPromise<FIRAppCheckToken *> *)refreshToken {
  223. return [FBLPromise
  224. wrapObjectOrErrorCompletion:^(FBLPromiseObjectOrErrorCompletion _Nonnull handler) {
  225. [self.appCheckProvider getTokenWithCompletion:handler];
  226. }]
  227. .then(^id _Nullable(FIRAppCheckToken *_Nullable token) {
  228. return [self.storage setToken:token];
  229. })
  230. .then(^id _Nullable(FIRAppCheckToken *_Nullable token) {
  231. // TODO: Make sure the self.tokenRefresher is updated only once. Currently the timer will be
  232. // updated twice in the case when the refresh triggered by self.tokenRefresher, but it
  233. // should be fine for now as it is a relatively cheap operation.
  234. [self.tokenRefresher updateTokenExpirationDate:token.expirationDate];
  235. [self postTokenUpdateNotificationWithToken:token];
  236. return token;
  237. });
  238. }
  239. #pragma mark - Token auto refresh
  240. - (void)periodicTokenRefreshWithCompletion:(FIRAppCheckTokenRefreshCompletion)completion {
  241. [self retrieveOrRefreshTokenForcingRefresh:NO]
  242. .then(^id _Nullable(FIRAppCheckToken *_Nullable token) {
  243. completion(YES, token.expirationDate);
  244. return nil;
  245. })
  246. .catch(^(NSError *error) {
  247. completion(NO, nil);
  248. });
  249. }
  250. #pragma mark - Token update notification
  251. - (void)postTokenUpdateNotificationWithToken:(FIRAppCheckToken *)token {
  252. [self.notificationCenter postNotificationName:FIRAppCheckAppCheckTokenDidChangeNotification
  253. object:self
  254. userInfo:@{
  255. kFIRAppCheckTokenNotificationKey : token.token,
  256. kFIRAppCheckAppNameNotificationKey : self.appName
  257. }];
  258. }
  259. @end
  260. NS_ASSUME_NONNULL_END