FIRAppCheck.m 15 KB

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