FIRAppCheck.m 15 KB

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