FIRAppCheck.m 16 KB

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