FIRAppCheck.m 14 KB

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