FIRAppCheck.m 11 KB

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