FIRAppCheck.m 14 KB

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