FIRAppCheck.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. @property(nonatomic, nullable) FBLPromise<FIRAppCheckToken *> *ongoingRetrieveOrRefreshTokenPromise;
  57. @end
  58. @implementation FIRAppCheck
  59. #pragma mark - FIRComponents
  60. + (void)load {
  61. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self withName:@"fire-app-check"];
  62. }
  63. + (NSArray<FIRComponent *> *)componentsToRegister {
  64. FIRComponentCreationBlock creationBlock =
  65. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  66. *isCacheable = YES;
  67. return [[FIRAppCheck alloc] initWithApp:container.app];
  68. };
  69. // Use eager instantiation timing to give a chance for FAC token to be requested before it is
  70. // actually needed to avoid extra delaying dependent requests.
  71. FIRComponent *appCheckProvider =
  72. [FIRComponent componentWithProtocol:@protocol(FIRAppCheckInterop)
  73. instantiationTiming:FIRInstantiationTimingAlwaysEager
  74. dependencies:@[]
  75. creationBlock:creationBlock];
  76. return @[ appCheckProvider ];
  77. }
  78. - (nullable instancetype)initWithApp:(FIRApp *)app {
  79. id<FIRAppCheckProviderFactory> providerFactory = [FIRAppCheck providerFactory];
  80. if (providerFactory == nil) {
  81. FIRLogError(kFIRLoggerAppCheck, kFIRLoggerAppCheckMessageCodeProviderFactoryIsMissing,
  82. @"Cannot instantiate `FIRAppCheck` for app: %@ without a provider factory. "
  83. @"Please register a provider factory using "
  84. @"`AppCheck.setAppCheckProviderFactory(_ ,forAppName:)` method.",
  85. app.name);
  86. return nil;
  87. }
  88. id<FIRAppCheckProvider> appCheckProvider = [providerFactory createProviderWithApp:app];
  89. if (appCheckProvider == nil) {
  90. FIRLogError(kFIRLoggerAppCheck, kFIRLoggerAppCheckMessageCodeProviderIsMissing,
  91. @"Cannot instantiate `FIRAppCheck` for app: %@ without an app check provider. "
  92. @"Please make sure the provide factory returns a valid app check provider.",
  93. app.name);
  94. return nil;
  95. }
  96. FIRAppCheckSettings *settings =
  97. [[FIRAppCheckSettings alloc] initWithApp:app
  98. userDefault:[NSUserDefaults standardUserDefaults]
  99. mainBundle:[NSBundle mainBundle]];
  100. FIRAppCheckTokenRefresher *tokenRefresher =
  101. [[FIRAppCheckTokenRefresher alloc] initWithTokenExpirationDate:[NSDate date]
  102. tokenExpirationThreshold:kTokenExpirationThreshold
  103. settings:settings];
  104. FIRAppCheckStorage *storage = [[FIRAppCheckStorage alloc] initWithAppName:app.name
  105. appID:app.options.googleAppID
  106. accessGroup:app.options.appGroupID];
  107. return [self initWithAppName:app.name
  108. appCheckProvider:appCheckProvider
  109. storage:storage
  110. tokenRefresher:tokenRefresher
  111. notificationCenter:NSNotificationCenter.defaultCenter
  112. settings:settings];
  113. }
  114. - (instancetype)initWithAppName:(NSString *)appName
  115. appCheckProvider:(id<FIRAppCheckProvider>)appCheckProvider
  116. storage:(id<FIRAppCheckStorageProtocol>)storage
  117. tokenRefresher:(id<FIRAppCheckTokenRefresherProtocol>)tokenRefresher
  118. notificationCenter:(NSNotificationCenter *)notificationCenter
  119. settings:(id<FIRAppCheckSettingsProtocol>)settings {
  120. self = [super init];
  121. if (self) {
  122. _appName = appName;
  123. _appCheckProvider = appCheckProvider;
  124. _storage = storage;
  125. _tokenRefresher = tokenRefresher;
  126. _notificationCenter = notificationCenter;
  127. _settings = settings;
  128. __auto_type __weak weakSelf = self;
  129. tokenRefresher.tokenRefreshHandler = ^(FIRAppCheckTokenRefreshCompletion _Nonnull completion) {
  130. __auto_type strongSelf = weakSelf;
  131. [strongSelf periodicTokenRefreshWithCompletion:completion];
  132. };
  133. }
  134. return self;
  135. }
  136. #pragma mark - Public
  137. + (instancetype)appCheck {
  138. FIRApp *defaultApp = [FIRApp defaultApp];
  139. if (!defaultApp) {
  140. [NSException raise:kFIRAppCheckErrorDomain
  141. format:@"The default FirebaseApp instance must be configured before the default"
  142. @"AppCheck instance can be initialized. One way to ensure that is to "
  143. @"call `[FIRApp configure];` (`FirebaseApp.configure()` in Swift) in the App"
  144. @" Delegate's `application:didFinishLaunchingWithOptions:` "
  145. @"(`application(_:didFinishLaunchingWithOptions:)` in Swift)."];
  146. }
  147. return [self appCheckWithApp:defaultApp];
  148. }
  149. + (nullable instancetype)appCheckWithApp:(FIRApp *)firebaseApp {
  150. id<FIRAppCheckInterop> appCheck = FIR_COMPONENT(FIRAppCheckInterop, firebaseApp.container);
  151. return (FIRAppCheck *)appCheck;
  152. }
  153. + (void)setAppCheckProviderFactory:(nullable id<FIRAppCheckProviderFactory>)factory {
  154. self.providerFactory = factory;
  155. }
  156. - (void)setIsTokenAutoRefreshEnabled:(BOOL)isTokenAutoRefreshEnabled {
  157. self.settings.isTokenAutoRefreshEnabled = isTokenAutoRefreshEnabled;
  158. }
  159. - (BOOL)isTokenAutoRefreshEnabled {
  160. return self.settings.isTokenAutoRefreshEnabled;
  161. }
  162. #pragma mark - App Check Provider Ingestion
  163. + (void)setProviderFactory:(nullable id<FIRAppCheckProviderFactory>)providerFactory {
  164. @synchronized(self) {
  165. _providerFactory = providerFactory;
  166. }
  167. }
  168. + (nullable id<FIRAppCheckProviderFactory>)providerFactory {
  169. @synchronized(self) {
  170. return _providerFactory;
  171. }
  172. }
  173. #pragma mark - FIRAppCheckInterop
  174. - (void)getTokenForcingRefresh:(BOOL)forcingRefresh
  175. completion:(FIRAppCheckTokenHandlerInterop)handler {
  176. [self retrieveOrRefreshTokenForcingRefresh:forcingRefresh]
  177. .then(^id _Nullable(FIRAppCheckToken *token) {
  178. FIRAppCheckTokenResult *result = [[FIRAppCheckTokenResult alloc] initWithToken:token.token
  179. error:nil];
  180. handler(result);
  181. return result;
  182. })
  183. .catch(^(NSError *_Nonnull error) {
  184. FIRAppCheckTokenResult *result =
  185. [[FIRAppCheckTokenResult alloc] initWithToken:kDummyFACTokenValue error:error];
  186. handler(result);
  187. });
  188. }
  189. - (nonnull NSString *)tokenDidChangeNotificationName {
  190. return FIRAppCheckAppCheckTokenDidChangeNotification;
  191. }
  192. - (nonnull NSString *)notificationAppNameKey {
  193. return kFIRAppCheckAppNameNotificationKey;
  194. }
  195. - (nonnull NSString *)notificationTokenKey {
  196. return kFIRAppCheckTokenNotificationKey;
  197. }
  198. #pragma mark - FAA token cache
  199. - (FBLPromise<FIRAppCheckToken *> *)retrieveOrRefreshTokenForcingRefresh:(BOOL)forcingRefresh {
  200. return [FBLPromise do:^id _Nullable {
  201. if (self.ongoingRetrieveOrRefreshTokenPromise == nil) {
  202. // Kick off a new operation only when there is not an ongoing one.
  203. self.ongoingRetrieveOrRefreshTokenPromise =
  204. [self createRetrieveOrRefreshTokenPromiseForcingRefresh:forcingRefresh]
  205. // Release the ongoing operation promise on completion.
  206. .then(^FIRAppCheckToken *(FIRAppCheckToken *token) {
  207. self.ongoingRetrieveOrRefreshTokenPromise = nil;
  208. return token;
  209. })
  210. .recover(^NSError *(NSError *error) {
  211. self.ongoingRetrieveOrRefreshTokenPromise = nil;
  212. return error;
  213. });
  214. }
  215. return self.ongoingRetrieveOrRefreshTokenPromise;
  216. }];
  217. }
  218. - (FBLPromise<FIRAppCheckToken *> *)createRetrieveOrRefreshTokenPromiseForcingRefresh:
  219. (BOOL)forcingRefresh {
  220. return [self getCachedValidTokenForcingRefresh:forcingRefresh].recover(
  221. ^id _Nullable(NSError *_Nonnull error) {
  222. return [self refreshToken];
  223. });
  224. }
  225. - (FBLPromise<FIRAppCheckToken *> *)getCachedValidTokenForcingRefresh:(BOOL)forcingRefresh {
  226. if (forcingRefresh) {
  227. FBLPromise *rejectedPromise = [FBLPromise pendingPromise];
  228. [rejectedPromise reject:[FIRAppCheckErrorUtil cachedTokenNotFound]];
  229. return rejectedPromise;
  230. }
  231. return [self.storage getToken].then(^id(FIRAppCheckToken *_Nullable token) {
  232. if (token == nil) {
  233. return [FIRAppCheckErrorUtil cachedTokenNotFound];
  234. }
  235. BOOL isTokenExpiredOrExpiresSoon =
  236. [token.expirationDate timeIntervalSinceNow] < kTokenExpirationThreshold;
  237. if (isTokenExpiredOrExpiresSoon) {
  238. return [FIRAppCheckErrorUtil cachedTokenExpired];
  239. }
  240. return token;
  241. });
  242. }
  243. - (FBLPromise<FIRAppCheckToken *> *)refreshToken {
  244. return [FBLPromise
  245. wrapObjectOrErrorCompletion:^(FBLPromiseObjectOrErrorCompletion _Nonnull handler) {
  246. [self.appCheckProvider getTokenWithCompletion:handler];
  247. }]
  248. .then(^id _Nullable(FIRAppCheckToken *_Nullable token) {
  249. return [self.storage setToken:token];
  250. })
  251. .then(^id _Nullable(FIRAppCheckToken *_Nullable token) {
  252. // TODO: Make sure the self.tokenRefresher is updated only once. Currently the timer will be
  253. // updated twice in the case when the refresh triggered by self.tokenRefresher, but it
  254. // should be fine for now as it is a relatively cheap operation.
  255. [self.tokenRefresher updateTokenExpirationDate:token.expirationDate];
  256. [self postTokenUpdateNotificationWithToken:token];
  257. return token;
  258. });
  259. }
  260. #pragma mark - Token auto refresh
  261. - (void)periodicTokenRefreshWithCompletion:(FIRAppCheckTokenRefreshCompletion)completion {
  262. [self retrieveOrRefreshTokenForcingRefresh:NO]
  263. .then(^id _Nullable(FIRAppCheckToken *_Nullable token) {
  264. completion(YES, token.expirationDate);
  265. return nil;
  266. })
  267. .catch(^(NSError *error) {
  268. completion(NO, nil);
  269. });
  270. }
  271. #pragma mark - Token update notification
  272. - (void)postTokenUpdateNotificationWithToken:(FIRAppCheckToken *)token {
  273. [self.notificationCenter postNotificationName:FIRAppCheckAppCheckTokenDidChangeNotification
  274. object:self
  275. userInfo:@{
  276. kFIRAppCheckTokenNotificationKey : token.token,
  277. kFIRAppCheckAppNameNotificationKey : self.appName
  278. }];
  279. }
  280. @end
  281. NS_ASSUME_NONNULL_END