FIRAppDistribution.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 "FIRFADLogger.h"
  19. #import <FirebaseCore/FIRAppInternal.h>
  20. #import <FirebaseCore/FIRComponent.h>
  21. #import <FirebaseCore/FIRComponentContainer.h>
  22. #import <FirebaseCore/FIROptions.h>
  23. #import <GoogleUtilities/GULAppDelegateSwizzler.h>
  24. #import "FIRAppDistributionAppDelegateInterceptor.h"
  25. /// Empty protocol to register with FirebaseCore's component system.
  26. @protocol FIRAppDistributionInstanceProvider <NSObject>
  27. @end
  28. @interface FIRAppDistribution () <FIRLibrary, FIRAppDistributionInstanceProvider>
  29. @property(nonatomic) BOOL isTesterSignedIn;
  30. @end
  31. NSString *const FIRAppDistributionErrorDomain = @"com.firebase.appdistribution";
  32. NSString *const FIRAppDistributionErrorDetailsKey = @"details";
  33. @implementation FIRAppDistribution
  34. // The OAuth scope needed to authorize the App Distribution Tester API
  35. NSString *const kOIDScopeTesterAPI = @"https://www.googleapis.com/auth/cloud-platform";
  36. // The App Distribution Tester API endpoint used to retrieve releases
  37. NSString *const kReleasesEndpointURL =
  38. @"https://firebaseapptesters.googleapis.com/v1alpha/devices/-/testerApps/%@/releases";
  39. NSString *const kTesterAPIClientID =
  40. @"319754533822-osu3v3hcci24umq6diathdm0dipds1fb.apps.googleusercontent.com";
  41. NSString *const kIssuerURL = @"https://accounts.google.com";
  42. NSString *const kAppDistroLibraryName = @"fire-fad";
  43. NSString *const kReleasesKey = @"releases";
  44. NSString *const kLatestReleaseKey = @"latest";
  45. NSString *const kCodeHashKey = @"codeHash";
  46. NSString *const kAuthErrorMessage = @"Unable to authenticate the tester";
  47. NSString *const kAuthCancelledErrorMessage = @"Tester cancelled sign-in";
  48. @synthesize isTesterSignedIn = _isTesterSignedIn;
  49. - (BOOL)isTesterSignedIn {
  50. FIRFADInfoLog(@"Checking if tester is signed in");
  51. return [self tryInitializeAuthState];
  52. }
  53. #pragma mark - Singleton Support
  54. - (instancetype)initWithApp:(FIRApp *)app appInfo:(NSDictionary *)appInfo {
  55. FIRFADInfoLog(@"Initializing Firebase App Distribution");
  56. self = [super init];
  57. if (self) {
  58. self.safariHostingViewController = [[UIViewController alloc] init];
  59. [GULAppDelegateSwizzler proxyOriginalDelegate];
  60. FIRAppDistributionAppDelegatorInterceptor *interceptor =
  61. [FIRAppDistributionAppDelegatorInterceptor sharedInstance];
  62. [GULAppDelegateSwizzler registerAppDelegateInterceptor:interceptor];
  63. }
  64. self.authPersistence = [[FIRAppDistributionAuthPersistence alloc]
  65. initWithAppId:[[FIRApp defaultApp] options].googleAppID];
  66. return self;
  67. }
  68. + (void)load {
  69. NSString *version =
  70. [NSString stringWithUTF8String:(const char *const)STR_EXPAND(FIRAppDistribution_VERSION)];
  71. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self
  72. withName:kAppDistroLibraryName
  73. withVersion:version];
  74. }
  75. + (NSArray<FIRComponent *> *)componentsToRegister {
  76. FIRComponentCreationBlock creationBlock =
  77. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  78. if (!container.app.isDefaultApp) {
  79. // TODO: Remove this and log error
  80. @throw([NSException exceptionWithName:@"NotImplementedException"
  81. reason:@"This code path is not implemented yet"
  82. userInfo:nil]);
  83. return nil;
  84. }
  85. *isCacheable = YES;
  86. return [[FIRAppDistribution alloc] initWithApp:container.app
  87. appInfo:NSBundle.mainBundle.infoDictionary];
  88. };
  89. FIRComponent *component =
  90. [FIRComponent componentWithProtocol:@protocol(FIRAppDistributionInstanceProvider)
  91. instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
  92. dependencies:@[]
  93. creationBlock:creationBlock];
  94. return @[ component ];
  95. }
  96. + (instancetype)appDistribution {
  97. // The container will return the same instance since isCacheable is set
  98. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  99. // Get the instance from the `FIRApp`'s container. This will create a new instance the
  100. // first time it is called, and since `isCacheable` is set in the component creation
  101. // block, it will return the existing instance on subsequent calls.
  102. id<FIRAppDistributionInstanceProvider> instance =
  103. FIR_COMPONENT(FIRAppDistributionInstanceProvider, defaultApp.container);
  104. // In the component creation block, we return an instance of `FIRAppDistribution`. Cast it and
  105. // return it.
  106. return (FIRAppDistribution *)instance;
  107. }
  108. - (void)signInTesterWithCompletion:(void (^)(NSError *_Nullable error))completion {
  109. FIRFADInfoLog(@"App Distribution tester sign in");
  110. if ([self tryInitializeAuthState]) {
  111. FIRFADInfoLog(@"Tester already signed in.");
  112. completion(nil);
  113. return;
  114. }
  115. NSURL *issuer = [NSURL URLWithString:kIssuerURL];
  116. [OIDAuthorizationService
  117. discoverServiceConfigurationForIssuer:issuer
  118. completion:^(OIDServiceConfiguration *_Nullable configuration,
  119. NSError *_Nullable error) {
  120. [self handleOauthDiscoveryCompletion:configuration
  121. error:error
  122. appDistributionSignInCompletion:completion];
  123. }];
  124. }
  125. - (void)signOutTester {
  126. FIRFADInfoLog(@"Tester sign out");
  127. NSError *error;
  128. BOOL didClearAuthState = [self.authPersistence clearAuthState:&error];
  129. if (!didClearAuthState) {
  130. FIRFADErrorLog(@"Error clearing token from keychain: %@", [error localizedDescription]);
  131. [self logUnderlyingKeychainError:error];
  132. } else {
  133. FIRFADInfoLog(@"Successfully cleared auth state from keychain");
  134. }
  135. self.authState = nil;
  136. self.isTesterSignedIn = false;
  137. }
  138. - (NSError *)NSErrorForErrorCodeAndMessage:(FIRAppDistributionError)errorCode
  139. message:(NSString *)message {
  140. NSDictionary *userInfo = @{FIRAppDistributionErrorDetailsKey : message};
  141. return [NSError errorWithDomain:FIRAppDistributionErrorDomain code:errorCode userInfo:userInfo];
  142. }
  143. @synthesize apiClientID = _apiClientID;
  144. - (NSString *)apiClientID {
  145. if (!_apiClientID) {
  146. return kTesterAPIClientID;
  147. }
  148. return _apiClientID;
  149. }
  150. - (void)setApiClientID:(NSString *)clientID {
  151. _apiClientID = clientID;
  152. }
  153. - (void)fetchReleases:(FIRAppDistributionUpdateCheckCompletion)completion {
  154. [self.authState performActionWithFreshTokens:^(NSString *_Nonnull accessToken,
  155. NSString *_Nonnull idToken,
  156. NSError *_Nullable error) {
  157. if (error) {
  158. FIRFADErrorLog(@"Error getting fresh auth tokens. Will sign out tester. Error: %@",
  159. [error localizedDescription]);
  160. // TODO: Do we need a less aggresive strategy here? maybe a retry?
  161. [self signOutTester];
  162. NSError *HTTPError =
  163. [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorAuthenticationFailure
  164. message:kAuthErrorMessage];
  165. dispatch_async(dispatch_get_main_queue(), ^{
  166. completion(nil, HTTPError);
  167. });
  168. return;
  169. }
  170. // perform your API request using the tokens
  171. NSURLSession *URLSession = [NSURLSession sharedSession];
  172. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  173. NSString *URLString =
  174. [NSString stringWithFormat:kReleasesEndpointURL, [[FIRApp defaultApp] options].googleAppID];
  175. FIRFADInfoLog(@"Requesting releases for app id - %@",
  176. [[FIRApp defaultApp] options].googleAppID);
  177. [request setURL:[NSURL URLWithString:URLString]];
  178. [request setHTTPMethod:@"GET"];
  179. [request setValue:[NSString stringWithFormat:@"Bearer %@", accessToken]
  180. forHTTPHeaderField:@"Authorization"];
  181. NSURLSessionDataTask *listReleasesDataTask = [URLSession
  182. dataTaskWithRequest:request
  183. completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  184. NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
  185. if (error || HTTPResponse.statusCode != 200) {
  186. NSError *HTTPError = nil;
  187. if (HTTPResponse == nil && error) {
  188. // Handles network timeouts or no internet connectivity
  189. NSString *message = error.userInfo[NSLocalizedDescriptionKey]
  190. ? error.userInfo[NSLocalizedDescriptionKey]
  191. : @"";
  192. HTTPError =
  193. [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorNetworkFailure
  194. message:message];
  195. } else if (HTTPResponse.statusCode == 401) {
  196. // TODO: Maybe sign out tester?
  197. HTTPError =
  198. [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorAuthenticationFailure
  199. message:kAuthErrorMessage];
  200. } else {
  201. HTTPError = [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorUnknown
  202. message:@""];
  203. }
  204. FIRFADErrorLog(@"App Tester API service error - %@",
  205. [HTTPError localizedDescription]);
  206. dispatch_async(dispatch_get_main_queue(), ^{
  207. completion(nil, HTTPError);
  208. });
  209. } else {
  210. [self handleReleasesAPIResponseWithData:data completion:completion];
  211. }
  212. }];
  213. [listReleasesDataTask resume];
  214. }];
  215. }
  216. - (void)handleOauthDiscoveryCompletion:(OIDServiceConfiguration *_Nullable)configuration
  217. error:(NSError *_Nullable)error
  218. appDistributionSignInCompletion:(void (^)(NSError *_Nullable error))completion {
  219. if (!configuration) {
  220. // TODO: Handle when we cannot get configuration
  221. FIRFADErrorLog(@"Cannot discover oauth config");
  222. NSError *error =
  223. [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorAuthenticationFailure
  224. message:kAuthErrorMessage];
  225. completion(error);
  226. return;
  227. }
  228. NSString *redirectURL = [@"dev.firebase.appdistribution."
  229. stringByAppendingString:[[[NSBundle mainBundle] bundleIdentifier]
  230. stringByAppendingString:@":/launch"]];
  231. OIDAuthorizationRequest *request = [[OIDAuthorizationRequest alloc]
  232. initWithConfiguration:configuration
  233. clientId:[self apiClientID]
  234. scopes:@[ OIDScopeOpenID, OIDScopeProfile, kOIDScopeTesterAPI ]
  235. redirectURL:[NSURL URLWithString:redirectURL]
  236. responseType:OIDResponseTypeCode
  237. additionalParameters:nil];
  238. [self setupUIWindowForLogin];
  239. void (^processAuthState)(OIDAuthState *_Nullable authState, NSError *_Nullable error) =
  240. ^void(OIDAuthState *_Nullable authState, NSError *_Nullable error) {
  241. [self cleanupUIWindow];
  242. if (error) {
  243. NSError *signInError = nil;
  244. if (error.code == OIDErrorCodeUserCanceledAuthorizationFlow) {
  245. // User cancelled auth flow
  246. FIRFADInfoLog(@"Tester cancelled sign in flow");
  247. signInError =
  248. [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorAuthenticationCancelled
  249. message:kAuthCancelledErrorMessage];
  250. } else {
  251. // Error in the auth flow
  252. FIRFADErrorLog(@"Tester sign in error - %@", [error localizedDescription]);
  253. signInError =
  254. [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorAuthenticationFailure
  255. message:kAuthErrorMessage];
  256. }
  257. completion(signInError);
  258. return;
  259. } else if (!authState) {
  260. FIRFADErrorLog(@"Tester sign in error - authState is nil");
  261. } else {
  262. FIRFADInfoLog(@"Tester sign successful");
  263. }
  264. self.authState = authState;
  265. // Capture errors in persistence but do not bubble them
  266. // up
  267. NSError *authPersistenceError;
  268. if (authState) {
  269. [self.authPersistence persistAuthState:authState error:&authPersistenceError];
  270. }
  271. // FIRLogger
  272. if (authPersistenceError) {
  273. FIRFADErrorLog(@"Error persisting auth token to keychain: %@",
  274. [authPersistenceError localizedDescription]);
  275. [self logUnderlyingKeychainError:authPersistenceError];
  276. } else {
  277. FIRFADInfoLog(@"Successfully persisted auth token in the keychain");
  278. }
  279. self.isTesterSignedIn = self.authState ? YES : NO;
  280. completion(nil);
  281. };
  282. // performs authentication request
  283. [FIRAppDistributionAppDelegatorInterceptor sharedInstance].currentAuthorizationFlow =
  284. [OIDAuthState authStateByPresentingAuthorizationRequest:request
  285. presentingViewController:self.safariHostingViewController
  286. callback:processAuthState];
  287. }
  288. - (BOOL)tryInitializeAuthState {
  289. FIRFADInfoLog(@"Initializing auth state");
  290. if (self.authState) {
  291. FIRFADInfoLog(@"Auth state already initialized.");
  292. return true;
  293. }
  294. NSError *authRetrievalError;
  295. self.authState = [self.authPersistence retrieveAuthState:&authRetrievalError];
  296. if (!self.authState) {
  297. if (authRetrievalError) {
  298. FIRFADErrorLog(@"Error retrieving tester auth token");
  299. [self logUnderlyingKeychainError:authRetrievalError];
  300. } else {
  301. // If authState and error is nil, auth state is not persisted in the keychain.
  302. FIRFADInfoLog(@"AuthState not persisted in the keychain");
  303. }
  304. return false;
  305. }
  306. FIRFADInfoLog(@"Successfully retrieved auth token from keychain on initialization");
  307. return true;
  308. }
  309. - (void)setupUIWindowForLogin {
  310. if (self.window) {
  311. return;
  312. }
  313. // Create an empty window + viewController to host the Safari UI.
  314. self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  315. self.window.rootViewController = self.safariHostingViewController;
  316. // Place it at the highest level within the stack.
  317. self.window.windowLevel = +CGFLOAT_MAX;
  318. // Run it.
  319. [self.window makeKeyAndVisible];
  320. }
  321. - (void)cleanupUIWindow {
  322. if (self.window) {
  323. self.window.hidden = YES;
  324. self.window = nil;
  325. }
  326. }
  327. - (void)logUnderlyingKeychainError:(NSError *)error {
  328. NSError *underlyingError = [error.userInfo objectForKey:NSUnderlyingErrorKey];
  329. if (underlyingError) {
  330. FIRFADErrorLog(@"Keychain error - %@", [underlyingError localizedDescription]);
  331. }
  332. }
  333. - (void)handleReleasesAPIResponseWithData:data
  334. completion:(FIRAppDistributionUpdateCheckCompletion)completion {
  335. NSError *error = nil;
  336. NSDictionary *serializedResponse = [NSJSONSerialization JSONObjectWithData:data
  337. options:0
  338. error:&error];
  339. if (error) {
  340. FIRFADErrorLog(@"Tester API - Error serializing json response");
  341. NSString *message =
  342. error.userInfo[NSLocalizedDescriptionKey] ? error.userInfo[NSLocalizedDescriptionKey] : @"";
  343. NSError *error = [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorUnknown
  344. message:message];
  345. dispatch_async(dispatch_get_main_queue(), ^{
  346. completion(nil, error);
  347. });
  348. return;
  349. }
  350. NSArray *releaseList = [serializedResponse objectForKey:kReleasesKey];
  351. for (NSDictionary *releaseDict in releaseList) {
  352. if ([[releaseDict objectForKey:kLatestReleaseKey] boolValue]) {
  353. FIRFADInfoLog(@"Tester API - found latest release in response. Checking if code hash match");
  354. NSString *codeHash = [releaseDict objectForKey:kCodeHashKey];
  355. NSString *executablePath = [[NSBundle mainBundle] executablePath];
  356. FIRAppDistributionMachO *machO =
  357. [[FIRAppDistributionMachO alloc] initWithPath:executablePath];
  358. FIRFADInfoLog(@"Code hash for the app on device - %@", machO.codeHash);
  359. FIRFADInfoLog(@"Code hash for the release from the service response - %@", codeHash);
  360. if (codeHash && ![codeHash isEqualToString:machO.codeHash]) {
  361. FIRAppDistributionRelease *release =
  362. [[FIRAppDistributionRelease alloc] initWithDictionary:releaseDict];
  363. dispatch_async(dispatch_get_main_queue(), ^{
  364. FIRFADInfoLog(@"Found new release");
  365. completion(release, nil);
  366. });
  367. return;
  368. }
  369. break;
  370. }
  371. }
  372. FIRFADInfoLog(@"Tester API - No new release found");
  373. dispatch_async(dispatch_get_main_queue(), ^{
  374. completion(nil, nil);
  375. });
  376. }
  377. - (void)checkForUpdateWithCompletion:(FIRAppDistributionUpdateCheckCompletion)completion {
  378. if (self.isTesterSignedIn) {
  379. [self fetchReleases:completion];
  380. } else {
  381. UIAlertController *alert = [UIAlertController
  382. alertControllerWithTitle:@"Enable in-app alerts"
  383. message:@"Sign in with your Firebase App Distribution Google account to "
  384. @"turn on in-app alerts for new test releases."
  385. preferredStyle:UIAlertControllerStyleAlert];
  386. UIAlertAction *yesButton =
  387. [UIAlertAction actionWithTitle:@"Turn on"
  388. style:UIAlertActionStyleDefault
  389. handler:^(UIAlertAction *action) {
  390. [self signInTesterWithCompletion:^(NSError *_Nullable error) {
  391. if (error) {
  392. completion(nil, error);
  393. return;
  394. }
  395. [self fetchReleases:completion];
  396. }];
  397. }];
  398. UIAlertAction *noButton = [UIAlertAction actionWithTitle:@"Not now"
  399. style:UIAlertActionStyleDefault
  400. handler:^(UIAlertAction *action) {
  401. // precaution to ensure window gets destroyed
  402. [self cleanupUIWindow];
  403. completion(nil, nil);
  404. }];
  405. [alert addAction:noButton];
  406. [alert addAction:yesButton];
  407. // Create an empty window + viewController to host the Safari UI.
  408. [self setupUIWindowForLogin];
  409. [self.window.rootViewController presentViewController:alert animated:YES completion:nil];
  410. }
  411. }
  412. @end