FIRAppDistribution.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. // Copyright 2020 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import "FIRAppDistribution+Private.h"
  15. #import "FIRAppDistributionAuthPersistence+Private.h"
  16. #import "FIRAppDistributionMachO+Private.h"
  17. #import "FIRAppDistributionRelease+Private.h"
  18. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  19. #import "FIRAppDistributionAppDelegateInterceptor.h"
  20. #import "GoogleUtilities/AppDelegateSwizzler/Private/GULAppDelegateSwizzler.h"
  21. /// Empty protocol to register with FirebaseCore's component system.
  22. @protocol FIRAppDistributionInstanceProvider <NSObject>
  23. @end
  24. @interface FIRAppDistribution () <FIRLibrary, FIRAppDistributionInstanceProvider>
  25. @property(nonatomic) BOOL isTesterSignedIn;
  26. @end
  27. @implementation FIRAppDistribution
  28. // The OAuth scope needed to authorize the App Distribution Tester API
  29. NSString *const kOIDScopeTesterAPI = @"https://www.googleapis.com/auth/cloud-platform";
  30. // The App Distribution Tester API endpoint used to retrieve releases
  31. NSString *const kReleasesEndpointURL =
  32. @"https://firebaseapptesters.googleapis.com/v1alpha/devices/-/testerApps/%@/releases";
  33. NSString *const kTesterAPIClientID =
  34. @"319754533822-osu3v3hcci24umq6diathdm0dipds1fb.apps.googleusercontent.com";
  35. NSString *const kIssuerURL = @"https://accounts.google.com";
  36. NSString *const kAppDistroLibraryName = @"fire-fad";
  37. #pragma mark - Singleton Support
  38. - (instancetype)initWithApp:(FIRApp *)app appInfo:(NSDictionary *)appInfo {
  39. self = [super init];
  40. if (self) {
  41. self.safariHostingViewController = [[UIViewController alloc] init];
  42. [GULAppDelegateSwizzler proxyOriginalDelegate];
  43. FIRAppDistributionAppDelegatorInterceptor *interceptor =
  44. [FIRAppDistributionAppDelegatorInterceptor sharedInstance];
  45. [GULAppDelegateSwizzler registerAppDelegateInterceptor:interceptor];
  46. }
  47. NSError *authRetrievalError;
  48. self.authState = [FIRAppDistributionAuthPersistence retrieveAuthState:&authRetrievalError];
  49. // TODO (schnecle): replace NSLog statement with FIRLogger log statement
  50. if (authRetrievalError) {
  51. NSLog(@"Error retrieving token from keychain: %@", [authRetrievalError localizedDescription]);
  52. }
  53. self.isTesterSignedIn = self.authState ? YES : NO;
  54. return self;
  55. }
  56. + (void)load {
  57. NSString *version =
  58. [NSString stringWithUTF8String:(const char *const)STR_EXPAND(FIRAppDistribution_VERSION)];
  59. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self
  60. withName:kAppDistroLibraryName
  61. withVersion:version];
  62. }
  63. + (NSArray<FIRComponent *> *)componentsToRegister {
  64. FIRComponentCreationBlock creationBlock =
  65. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  66. if (!container.app.isDefaultApp) {
  67. // TODO: Implement error handling
  68. @throw([NSException exceptionWithName:@"NotImplementedException"
  69. reason:@"This code path is not implemented yet"
  70. userInfo:nil]);
  71. return nil;
  72. }
  73. *isCacheable = YES;
  74. return [[FIRAppDistribution alloc] initWithApp:container.app
  75. appInfo:NSBundle.mainBundle.infoDictionary];
  76. };
  77. FIRComponent *component =
  78. [FIRComponent componentWithProtocol:@protocol(FIRAppDistributionInstanceProvider)
  79. instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
  80. dependencies:@[]
  81. creationBlock:creationBlock];
  82. return @[ component ];
  83. }
  84. + (instancetype)appDistribution {
  85. // The container will return the same instance since isCacheable is set
  86. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  87. // Get the instance from the `FIRApp`'s container. This will create a new instance the
  88. // first time it is called, and since `isCacheable` is set in the component creation
  89. // block, it will return the existing instance on subsequent calls.
  90. id<FIRAppDistributionInstanceProvider> instance =
  91. FIR_COMPONENT(FIRAppDistributionInstanceProvider, defaultApp.container);
  92. // In the component creation block, we return an instance of `FIRAppDistribution`. Cast it and
  93. // return it.
  94. return (FIRAppDistribution *)instance;
  95. }
  96. - (void)signInTesterWithCompletion:(void (^)(NSError *_Nullable error))completion {
  97. NSURL *issuer = [NSURL URLWithString:kIssuerURL];
  98. [OIDAuthorizationService
  99. discoverServiceConfigurationForIssuer:issuer
  100. completion:^(OIDServiceConfiguration *_Nullable configuration,
  101. NSError *_Nullable error) {
  102. [self handleOauthDiscoveryCompletion:configuration
  103. error:error
  104. appDistributionSignInCompletion:completion];
  105. }];
  106. }
  107. - (void)signOutTester {
  108. NSError *error;
  109. BOOL didClearAuthState = [FIRAppDistributionAuthPersistence clearAuthState:&error];
  110. // TODO (schnecle): Add in FIRLogger to report when we have failed to clear auth state
  111. if (!didClearAuthState) {
  112. NSLog(@"Error clearing token from keychain: %@", [error localizedDescription]);
  113. }
  114. self.authState = nil;
  115. self.isTesterSignedIn = false;
  116. }
  117. - (void)fetchReleases:(FIRAppDistributionUpdateCheckCompletion)completion {
  118. [self.authState performActionWithFreshTokens:^(NSString *_Nonnull accessToken,
  119. NSString *_Nonnull idToken,
  120. NSError *_Nullable error) {
  121. if (error) {
  122. // TODO (schnecle): Add in FIRLogger log statement
  123. NSLog(@"Error fetching fresh tokens: %@", [error localizedDescription]);
  124. [self signOutTester];
  125. return;
  126. }
  127. // perform your API request using the tokens
  128. NSURLSession *URLSession = [NSURLSession sharedSession];
  129. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  130. NSString *URLString =
  131. [NSString stringWithFormat:kReleasesEndpointURL, [[FIRApp defaultApp] options].googleAppID];
  132. [request setURL:[NSURL URLWithString:URLString]];
  133. [request setHTTPMethod:@"GET"];
  134. [request setValue:[NSString stringWithFormat:@"Bearer %@", accessToken]
  135. forHTTPHeaderField:@"Authorization"];
  136. NSURLSessionDataTask *listReleasesDataTask = [URLSession
  137. dataTaskWithRequest:request
  138. completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  139. if (error) {
  140. // TODO: Reformat error into error code
  141. completion(nil, error);
  142. return;
  143. }
  144. NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
  145. if (HTTPResponse.statusCode == 200) {
  146. [self handleReleasesAPIResponseWithData:data completion:completion];
  147. } else {
  148. // TODO: Handle non-200 http response
  149. NSLog(@"ERROR - Non 200 service response - %@", HTTPResponse);
  150. @throw([NSException exceptionWithName:@"NotImplementedException"
  151. reason:@"This code path is not implemented yet"
  152. userInfo:nil]);
  153. }
  154. }];
  155. [listReleasesDataTask resume];
  156. }];
  157. }
  158. - (void)handleOauthDiscoveryCompletion:(OIDServiceConfiguration *_Nullable)configuration
  159. error:(NSError *_Nullable)error
  160. appDistributionSignInCompletion:(void (^)(NSError *_Nullable error))completion {
  161. if (!configuration) {
  162. // TODO: Handle when we cannot get configuration
  163. NSLog(@"ERROR - Cannot discover oauth config");
  164. @throw([NSException exceptionWithName:@"NotImplementedException"
  165. reason:@"This code path is not implemented yet"
  166. userInfo:nil]);
  167. return;
  168. }
  169. NSString *redirectURL = [@"dev.firebase.appdistribution."
  170. stringByAppendingString:[[[NSBundle mainBundle] bundleIdentifier]
  171. stringByAppendingString:@":/launch"]];
  172. OIDAuthorizationRequest *request = [[OIDAuthorizationRequest alloc]
  173. initWithConfiguration:configuration
  174. clientId:kTesterAPIClientID
  175. scopes:@[ OIDScopeOpenID, OIDScopeProfile, kOIDScopeTesterAPI ]
  176. redirectURL:[NSURL URLWithString:redirectURL]
  177. responseType:OIDResponseTypeCode
  178. additionalParameters:nil];
  179. [self setupUIWindowForLogin];
  180. void (^processAuthState)(OIDAuthState *_Nullable authState, NSError *_Nullable error) = ^void(
  181. OIDAuthState *_Nullable authState, NSError *_Nullable error) {
  182. self.authState = authState;
  183. // Capture errors in persistence but do not bubble them
  184. // up
  185. NSError *authPersistenceError;
  186. if (authState) {
  187. [FIRAppDistributionAuthPersistence persistAuthState:authState error:&authPersistenceError];
  188. }
  189. // TODO (schnecle): Log errors in persistence using
  190. // FIRLogger
  191. if (authPersistenceError) {
  192. NSLog(@"Error persisting token to keychain: %@", [error localizedDescription]);
  193. }
  194. self.isTesterSignedIn = self.authState ? YES : NO;
  195. completion(error);
  196. };
  197. // performs authentication request
  198. [FIRAppDistributionAppDelegatorInterceptor sharedInstance].currentAuthorizationFlow =
  199. [OIDAuthState authStateByPresentingAuthorizationRequest:request
  200. presentingViewController:self.safariHostingViewController
  201. callback:processAuthState];
  202. }
  203. - (void)setupUIWindowForLogin {
  204. if (self.window) {
  205. return;
  206. }
  207. // Create an empty window + viewController to host the Safari UI.
  208. self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  209. self.window.rootViewController = self.safariHostingViewController;
  210. // Place it at the highest level within the stack.
  211. self.window.windowLevel = +CGFLOAT_MAX;
  212. // Run it.
  213. [self.window makeKeyAndVisible];
  214. }
  215. - (void)cleanupUIWindow {
  216. if (self.window) {
  217. self.window.hidden = YES;
  218. self.window = nil;
  219. }
  220. }
  221. - (void)handleReleasesAPIResponseWithData:data
  222. completion:(FIRAppDistributionUpdateCheckCompletion)completion {
  223. NSError *error = nil;
  224. NSDictionary *object = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  225. NSArray *releaseList = [object objectForKey:@"releases"];
  226. for (NSDictionary *releaseDict in releaseList) {
  227. if (![[releaseDict objectForKey:@"latest"] boolValue]) continue;
  228. NSString *codeHash = [releaseDict objectForKey:@"codeHash"];
  229. FIRAppDistributionMachO *machO =
  230. [[FIRAppDistributionMachO alloc] initWithPath:[[NSBundle mainBundle] executablePath]];
  231. if (![codeHash isEqualToString:machO.codeHash]) {
  232. FIRAppDistributionRelease *release =
  233. [[FIRAppDistributionRelease alloc] initWithDictionary:releaseDict];
  234. dispatch_async(dispatch_get_main_queue(), ^{
  235. completion(release, nil);
  236. });
  237. }
  238. }
  239. }
  240. - (void)checkForUpdateWithCompletion:(FIRAppDistributionUpdateCheckCompletion)completion {
  241. if (self.isTesterSignedIn) {
  242. [self fetchReleases:completion];
  243. } else {
  244. UIAlertController *alert = [UIAlertController
  245. alertControllerWithTitle:@"Enable in-app alerts"
  246. message:@"Sign in with your Firebase App Distribution Google account to "
  247. @"turn on in-app alerts for new test releases."
  248. preferredStyle:UIAlertControllerStyleAlert];
  249. UIAlertAction *yesButton =
  250. [UIAlertAction actionWithTitle:@"Turn on"
  251. style:UIAlertActionStyleDefault
  252. handler:^(UIAlertAction *action) {
  253. [self signInTesterWithCompletion:^(NSError *_Nullable error) {
  254. if (error) {
  255. completion(nil, error);
  256. return;
  257. }
  258. [self fetchReleases:completion];
  259. }];
  260. }];
  261. UIAlertAction *noButton = [UIAlertAction actionWithTitle:@"Not now"
  262. style:UIAlertActionStyleDefault
  263. handler:^(UIAlertAction *action) {
  264. // precaution to ensure window gets destroyed
  265. [self cleanupUIWindow];
  266. completion(nil, nil);
  267. }];
  268. [alert addAction:noButton];
  269. [alert addAction:yesButton];
  270. // Create an empty window + viewController to host the Safari UI.
  271. [self setupUIWindowForLogin];
  272. [self.window.rootViewController presentViewController:alert animated:YES completion:nil];
  273. }
  274. }
  275. @end