FIRAppCheck.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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 <AppCheckCore/AppCheckCore.h>
  18. #import <FirebaseAppCheckInterop/FirebaseAppCheckInterop.h>
  19. #import <GoogleUtilities/GULUserDefaults.h>
  20. #import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckErrors.h"
  21. #import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckProvider.h"
  22. #import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckProviderFactory.h"
  23. #import "FirebaseAppCheck/Sources/Core/Errors/FIRAppCheckErrorUtil.h"
  24. #import "FirebaseAppCheck/Sources/Core/FIRAppCheck+Internal.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/FIRInternalAppCheckProvider.h"
  30. NS_ASSUME_NONNULL_BEGIN
  31. /// A notification with the specified name is sent to the default notification center
  32. /// (`NotificationCenter.default`) each time a Firebase app check token is refreshed.
  33. /// The user info dictionary contains `kFIRAppCheckTokenNotificationKey` and
  34. /// `kFIRAppCheckAppNameNotificationKey` keys.
  35. const NSNotificationName FIRAppCheckAppCheckTokenDidChangeNotification =
  36. @"FIRAppCheckAppCheckTokenDidChangeNotification";
  37. /// `userInfo` key for the `AppCheckToken` in `appCheckTokenRefreshNotification`.
  38. NSString *const kFIRAppCheckTokenNotificationKey = @"FIRAppCheckTokenNotificationKey";
  39. /// `userInfo` key for the `FirebaseApp.name` in `appCheckTokenRefreshNotification`.
  40. NSString *const kFIRAppCheckAppNameNotificationKey = @"FIRAppCheckAppNameNotificationKey";
  41. static id<FIRAppCheckProviderFactory> _providerFactory;
  42. @interface FIRAppCheck () <FIRAppCheckInterop, GACAppCheckTokenDelegate>
  43. @property(class, nullable) id<FIRAppCheckProviderFactory> providerFactory;
  44. @property(nonatomic, readonly) NSString *appName;
  45. @property(nonatomic, readonly) NSNotificationCenter *notificationCenter;
  46. @property(nonatomic, readonly) FIRAppCheckSettings *settings;
  47. @property(nonatomic, readonly) GACAppCheck *appCheckCore;
  48. @end
  49. @implementation FIRAppCheck
  50. #pragma mark - Internal
  51. - (nullable instancetype)initWithApp:(FIRApp *)app {
  52. // Set the App Check Core logging level to the current equivalent Firebase logging level.
  53. GACAppCheckLogger.logLevel = FIRGetGACAppCheckLogLevel();
  54. id<FIRAppCheckProviderFactory> providerFactory = [FIRAppCheck providerFactory];
  55. if (providerFactory == nil) {
  56. FIRLogError(kFIRLoggerAppCheck, kFIRLoggerAppCheckMessageCodeProviderFactoryIsMissing,
  57. @"Cannot instantiate `FIRAppCheck` for app: %@ without a provider factory. "
  58. @"Please register a provider factory using "
  59. @"`AppCheck.setAppCheckProviderFactory(_ ,forAppName:)` method.",
  60. app.name);
  61. return nil;
  62. }
  63. id<FIRAppCheckProvider> appCheckProvider = [providerFactory createProviderWithApp:app];
  64. if (appCheckProvider == nil) {
  65. FIRLogError(kFIRLoggerAppCheck, kFIRLoggerAppCheckMessageCodeProviderIsMissing,
  66. @"Cannot instantiate `FIRAppCheck` for app: %@ without an app check provider. "
  67. @"Please make sure the provider factory returns a valid app check provider.",
  68. app.name);
  69. return nil;
  70. }
  71. NSString *serviceName = [self serviceNameForApp:app];
  72. NSString *resourceName = [self resourceNameForApp:app];
  73. id<GACAppCheckProvider> appCheckCoreProvider =
  74. [[FIRInternalAppCheckProvider alloc] initWithAppCheckProvider:appCheckProvider];
  75. FIRAppCheckSettings *settings =
  76. [[FIRAppCheckSettings alloc] initWithApp:app
  77. userDefault:[GULUserDefaults standardUserDefaults]
  78. mainBundle:[NSBundle mainBundle]];
  79. GACAppCheck *appCheckCore = [[GACAppCheck alloc] initWithServiceName:serviceName
  80. resourceName:resourceName
  81. appCheckProvider:appCheckCoreProvider
  82. settings:settings
  83. tokenDelegate:self
  84. keychainAccessGroup:app.options.appGroupID];
  85. return [self initWithAppName:app.name
  86. appCheckCore:appCheckCore
  87. appCheckProvider:appCheckProvider
  88. notificationCenter:NSNotificationCenter.defaultCenter
  89. settings:settings];
  90. }
  91. - (instancetype)initWithAppName:(NSString *)appName
  92. appCheckCore:(GACAppCheck *)appCheckCore
  93. appCheckProvider:(id<FIRAppCheckProvider>)appCheckProvider
  94. notificationCenter:(NSNotificationCenter *)notificationCenter
  95. settings:(FIRAppCheckSettings *)settings {
  96. self = [super init];
  97. if (self) {
  98. _appName = appName;
  99. _appCheckCore = appCheckCore;
  100. _notificationCenter = notificationCenter;
  101. _settings = settings;
  102. }
  103. return self;
  104. }
  105. #pragma mark - Public
  106. + (instancetype)appCheck {
  107. FIRApp *defaultApp = [FIRApp defaultApp];
  108. if (!defaultApp) {
  109. [NSException raise:FIRAppCheckErrorDomain
  110. format:@"The default FirebaseApp instance must be configured before the default"
  111. @"AppCheck instance can be initialized. One way to ensure this is to "
  112. @"call `FirebaseApp.configure()` in the App Delegate's "
  113. @"`application(_:didFinishLaunchingWithOptions:)` (or the `@main` struct's "
  114. @"initializer in SwiftUI)."];
  115. }
  116. return [self appCheckWithApp:defaultApp];
  117. }
  118. + (nullable instancetype)appCheckWithApp:(FIRApp *)firebaseApp {
  119. id<FIRAppCheckInterop> appCheck = FIR_COMPONENT(FIRAppCheckInterop, firebaseApp.container);
  120. return (FIRAppCheck *)appCheck;
  121. }
  122. - (void)tokenForcingRefresh:(BOOL)forcingRefresh
  123. completion:(void (^)(FIRAppCheckToken *_Nullable token,
  124. NSError *_Nullable error))handler {
  125. [self.appCheckCore
  126. tokenForcingRefresh:forcingRefresh
  127. completion:^(GACAppCheckTokenResult *result) {
  128. if (result.error) {
  129. handler(nil, [FIRAppCheckErrorUtil publicDomainErrorWithError:result.error]);
  130. return;
  131. }
  132. handler([[FIRAppCheckToken alloc] initWithInternalToken:result.token], nil);
  133. }];
  134. }
  135. - (void)limitedUseTokenWithCompletion:(void (^)(FIRAppCheckToken *_Nullable token,
  136. NSError *_Nullable error))handler {
  137. [self.appCheckCore limitedUseTokenWithCompletion:^(GACAppCheckTokenResult *result) {
  138. if (result.error) {
  139. handler(nil, [FIRAppCheckErrorUtil publicDomainErrorWithError:result.error]);
  140. return;
  141. }
  142. handler([[FIRAppCheckToken alloc] initWithInternalToken:result.token], nil);
  143. }];
  144. }
  145. + (void)setAppCheckProviderFactory:(nullable id<FIRAppCheckProviderFactory>)factory {
  146. self.providerFactory = factory;
  147. }
  148. - (void)setIsTokenAutoRefreshEnabled:(BOOL)isTokenAutoRefreshEnabled {
  149. self.settings.isTokenAutoRefreshEnabled = isTokenAutoRefreshEnabled;
  150. }
  151. - (BOOL)isTokenAutoRefreshEnabled {
  152. return self.settings.isTokenAutoRefreshEnabled;
  153. }
  154. #pragma mark - App Check Provider Ingestion
  155. + (void)setProviderFactory:(nullable id<FIRAppCheckProviderFactory>)providerFactory {
  156. @synchronized(self) {
  157. _providerFactory = providerFactory;
  158. }
  159. }
  160. + (nullable id<FIRAppCheckProviderFactory>)providerFactory {
  161. @synchronized(self) {
  162. return _providerFactory;
  163. }
  164. }
  165. #pragma mark - FIRAppCheckInterop
  166. - (void)getTokenForcingRefresh:(BOOL)forcingRefresh
  167. completion:(FIRAppCheckTokenHandlerInterop)handler {
  168. [self.appCheckCore
  169. tokenForcingRefresh:forcingRefresh
  170. completion:^(GACAppCheckTokenResult *internalResult) {
  171. FIRAppCheckToken *token =
  172. [[FIRAppCheckToken alloc] initWithInternalToken:internalResult.token];
  173. FIRAppCheckTokenResult *tokenResult =
  174. [[FIRAppCheckTokenResult alloc] initWithToken:token.token
  175. error:internalResult.error];
  176. handler(tokenResult);
  177. }];
  178. }
  179. - (void)getLimitedUseTokenWithCompletion:(FIRAppCheckTokenHandlerInterop)handler {
  180. [self.appCheckCore limitedUseTokenWithCompletion:^(GACAppCheckTokenResult *internalResult) {
  181. FIRAppCheckToken *token = [[FIRAppCheckToken alloc] initWithInternalToken:internalResult.token];
  182. FIRAppCheckTokenResult *tokenResult =
  183. [[FIRAppCheckTokenResult alloc] initWithToken:token.token error:internalResult.error];
  184. handler(tokenResult);
  185. }];
  186. }
  187. - (nonnull NSString *)tokenDidChangeNotificationName {
  188. return FIRAppCheckAppCheckTokenDidChangeNotification;
  189. }
  190. - (nonnull NSString *)notificationAppNameKey {
  191. return kFIRAppCheckAppNameNotificationKey;
  192. }
  193. - (nonnull NSString *)notificationTokenKey {
  194. return kFIRAppCheckTokenNotificationKey;
  195. }
  196. #pragma mark - GACAppCheckTokenDelegate
  197. - (void)tokenDidUpdate:(nonnull GACAppCheckToken *)token
  198. serviceName:(nonnull NSString *)serviceName {
  199. FIRAppCheckToken *appCheckToken = [[FIRAppCheckToken alloc] initWithInternalToken:token];
  200. [self postTokenUpdateNotificationWithToken:appCheckToken];
  201. }
  202. #pragma mark - Token update notification
  203. - (void)postTokenUpdateNotificationWithToken:(FIRAppCheckToken *)token {
  204. [self.notificationCenter postNotificationName:FIRAppCheckAppCheckTokenDidChangeNotification
  205. object:self
  206. userInfo:@{
  207. kFIRAppCheckTokenNotificationKey : token.token,
  208. kFIRAppCheckAppNameNotificationKey : self.appName
  209. }];
  210. }
  211. #pragma mark - Helpers
  212. - (NSString *)serviceNameForApp:(FIRApp *)app {
  213. return [NSString stringWithFormat:@"FirebaseApp:%@", app.name];
  214. }
  215. - (NSString *)resourceNameForApp:(FIRApp *)app {
  216. return [NSString
  217. stringWithFormat:@"projects/%@/apps/%@", app.options.projectID, app.options.googleAppID];
  218. }
  219. @end
  220. NS_ASSUME_NONNULL_END