FIRAppDistribution.m 19 KB

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