FIRAppDistribution.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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 "FIRAppDistributionRelease+Private.h"
  16. #import "FIRAppDistributionMachO+Private.h"
  17. #import "FIRAppDistributionAuthPersistence+Private.h"
  18. #import <FirebaseCore/FIRAppInternal.h>
  19. #import <FirebaseCore/FIRComponent.h>
  20. #import <FirebaseCore/FIRComponentContainer.h>
  21. #import <FirebaseCore/FIROptions.h>
  22. #import <GoogleUtilities/GULAppDelegateSwizzler.h>
  23. #import "FIRAppDistributionAppDelegateInterceptor.h"
  24. /// Empty protocol to register with FirebaseCore's component system.
  25. @protocol FIRAppDistributionInstanceProvider <NSObject>
  26. @end
  27. @interface FIRAppDistribution () <FIRLibrary, FIRAppDistributionInstanceProvider>
  28. @property(nonatomic) BOOL isTesterSignedIn;
  29. @end
  30. NSString *const FIRAppDistributionErrorDomain = @"com.firebase.appdistribution";
  31. NSString *const FIRAppDistributionErrorDetailsKey = @"details";
  32. @implementation FIRAppDistribution
  33. // The OAuth scope needed to authorize the App Distribution Tester API
  34. NSString *const kOIDScopeTesterAPI = @"https://www.googleapis.com/auth/cloud-platform";
  35. // The App Distribution Tester API endpoint used to retrieve releases
  36. NSString *const kReleasesEndpointURL =
  37. @"https://firebaseapptesters.googleapis.com/v1alpha/devices/-/testerApps/%@/releases";
  38. NSString *const kTesterAPIClientID =
  39. @"319754533822-osu3v3hcci24umq6diathdm0dipds1fb.apps.googleusercontent.com";
  40. NSString *const kIssuerURL = @"https://accounts.google.com";
  41. NSString *const kAppDistroLibraryName = @"fire-fad";
  42. NSString *const kReleasesKey = @"releases";
  43. NSString *const kLatestReleaseKey = @"latest";
  44. NSString *const kCodeHashKey = @"codeHash";
  45. NSString *const kAuthErrorMessage = @"Unable to authenticate the tester";
  46. #pragma mark - Singleton Support
  47. - (instancetype)initWithApp:(FIRApp *)app appInfo:(NSDictionary *)appInfo {
  48. self = [super init];
  49. if (self) {
  50. self.safariHostingViewController = [[UIViewController alloc] init];
  51. [GULAppDelegateSwizzler proxyOriginalDelegate];
  52. FIRAppDistributionAppDelegatorInterceptor *interceptor =
  53. [FIRAppDistributionAppDelegatorInterceptor sharedInstance];
  54. [GULAppDelegateSwizzler registerAppDelegateInterceptor:interceptor];
  55. }
  56. self.authState = [FIRAppDistributionAuthPersistence retrieveAuthState];
  57. self.isTesterSignedIn = self.authState ? YES : NO;
  58. return self;
  59. }
  60. + (void)load {
  61. NSString *version =
  62. [NSString stringWithUTF8String:(const char *const)STR_EXPAND(FIRAppDistribution_VERSION)];
  63. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self
  64. withName:kAppDistroLibraryName
  65. withVersion:version];
  66. }
  67. + (NSArray<FIRComponent *> *)componentsToRegister {
  68. FIRComponentCreationBlock creationBlock =
  69. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  70. if (!container.app.isDefaultApp) {
  71. // TODO: Remove this and log error
  72. @throw([NSException exceptionWithName:@"NotImplementedException"
  73. reason:@"This code path is not implemented yet"
  74. userInfo:nil]);
  75. return nil;
  76. }
  77. *isCacheable = YES;
  78. return [[FIRAppDistribution alloc] initWithApp:container.app
  79. appInfo:NSBundle.mainBundle.infoDictionary];
  80. };
  81. FIRComponent *component =
  82. [FIRComponent componentWithProtocol:@protocol(FIRAppDistributionInstanceProvider)
  83. instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
  84. dependencies:@[]
  85. creationBlock:creationBlock];
  86. return @[ component ];
  87. }
  88. + (instancetype)appDistribution {
  89. // The container will return the same instance since isCacheable is set
  90. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  91. // Get the instance from the `FIRApp`'s container. This will create a new instance the
  92. // first time it is called, and since `isCacheable` is set in the component creation
  93. // block, it will return the existing instance on subsequent calls.
  94. id<FIRAppDistributionInstanceProvider> instance =
  95. FIR_COMPONENT(FIRAppDistributionInstanceProvider, defaultApp.container);
  96. // In the component creation block, we return an instance of `FIRAppDistribution`. Cast it and
  97. // return it.
  98. return (FIRAppDistribution *)instance;
  99. }
  100. - (void)signInTesterWithCompletion:(void (^)(NSError *_Nullable error))completion {
  101. NSURL *issuer = [NSURL URLWithString:kIssuerURL];
  102. [OIDAuthorizationService
  103. discoverServiceConfigurationForIssuer:issuer
  104. completion:^(OIDServiceConfiguration *_Nullable configuration,
  105. NSError *_Nullable error) {
  106. [self handleOauthDiscoveryCompletion:configuration
  107. error:error
  108. appDistributionSignInCompletion:completion];
  109. }];
  110. }
  111. - (void)signOutTester {
  112. [FIRAppDistributionAuthPersistence clearAuthState];
  113. self.authState = nil;
  114. self.isTesterSignedIn = false;
  115. }
  116. - (NSError *)NSErrorForErrorCodeAndMessage:(FIRAppDistributionError)errorCode
  117. message:(NSString *)message {
  118. NSDictionary *userInfo = @{FIRAppDistributionErrorDetailsKey : message};
  119. return [NSError errorWithDomain:FIRAppDistributionErrorDomain code:errorCode userInfo:userInfo];
  120. }
  121. - (void)fetchReleases:(FIRAppDistributionUpdateCheckCompletion)completion {
  122. [self.authState performActionWithFreshTokens:^(NSString *_Nonnull accessToken,
  123. NSString *_Nonnull idToken,
  124. NSError *_Nullable error) {
  125. if (error) {
  126. // Error fetching fresh tokens
  127. // TODO: Do we need a less aggresive strategy here? maybe a retry?
  128. [self signOutTester];
  129. NSError *HTTPError = [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorAuthenticationFailure
  130. message:kAuthErrorMessage];
  131. dispatch_async(dispatch_get_main_queue(), ^{
  132. completion(nil, HTTPError);
  133. });
  134. return;
  135. }
  136. // perform your API request using the tokens
  137. NSURLSession *URLSession = [NSURLSession sharedSession];
  138. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  139. NSString *URLString =
  140. [NSString stringWithFormat:kReleasesEndpointURL, [[FIRApp defaultApp] options].googleAppID];
  141. [request setURL:[NSURL URLWithString:URLString]];
  142. [request setHTTPMethod:@"GET"];
  143. [request setValue:[NSString
  144. stringWithFormat:@"Bearer %@", accessToken]
  145. forHTTPHeaderField:@"Authorization"];
  146. NSURLSessionDataTask *listReleasesDataTask = [URLSession
  147. dataTaskWithRequest:request
  148. completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  149. NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
  150. if (error || HTTPResponse.statusCode != 200) {
  151. NSError *HTTPError = nil;
  152. if(HTTPResponse == nil && error) {
  153. // Handles network timeouts or no internet connectivity
  154. NSString *message = error.userInfo[NSLocalizedDescriptionKey] ? error.userInfo[NSLocalizedDescriptionKey] : @"";
  155. HTTPError = [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorNetworkFailure message:message];
  156. }
  157. else if(HTTPResponse.statusCode == 401) {
  158. // TODO: Maybe sign out tester?
  159. HTTPError = [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorAuthenticationFailure
  160. message:kAuthErrorMessage];
  161. } else {
  162. HTTPError = [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorUnknown
  163. message:@""];
  164. }
  165. dispatch_async(dispatch_get_main_queue(), ^{
  166. completion(nil, HTTPError);
  167. });
  168. } else {
  169. [self handleReleasesAPIResponseWithData:data completion:completion];
  170. }
  171. }];
  172. [listReleasesDataTask resume];
  173. }];
  174. }
  175. - (void)handleOauthDiscoveryCompletion:(OIDServiceConfiguration *_Nullable)configuration
  176. error:(NSError *_Nullable)error
  177. appDistributionSignInCompletion:(void (^)(NSError *_Nullable error))completion {
  178. if (!configuration) {
  179. // TODO: Handle when we cannot get configuration
  180. NSLog(@"ERROR - Cannot discover oauth config");
  181. @throw([NSException exceptionWithName:@"NotImplementedException"
  182. reason:@"This code path is not implemented yet"
  183. userInfo:nil]);
  184. return;
  185. }
  186. NSString *redirectURL = [@"dev.firebase.appdistribution."
  187. stringByAppendingString:[[[NSBundle mainBundle] bundleIdentifier]
  188. stringByAppendingString:@":/launch"]];
  189. OIDAuthorizationRequest *request = [[OIDAuthorizationRequest alloc]
  190. initWithConfiguration:configuration
  191. clientId:kTesterAPIClientID
  192. scopes:@[ OIDScopeOpenID, OIDScopeProfile, kOIDScopeTesterAPI ]
  193. redirectURL:[NSURL URLWithString:redirectURL]
  194. responseType:OIDResponseTypeCode
  195. additionalParameters:nil];
  196. [self createUIWindowForLogin];
  197. // performs authentication request
  198. [FIRAppDistributionAppDelegatorInterceptor sharedInstance].currentAuthorizationFlow =
  199. [OIDAuthState authStateByPresentingAuthorizationRequest:request
  200. presentingViewController:self.safariHostingViewController
  201. callback:^(OIDAuthState *_Nullable authState,
  202. NSError *_Nullable error) {
  203. // TODO: Handle error code for user cancellation
  204. self.authState = authState;
  205. if(authState) {
  206. [FIRAppDistributionAuthPersistence persistAuthState:authState];
  207. }
  208. self.isTesterSignedIn = self.authState ? YES : NO;
  209. completion(error);
  210. }];
  211. }
  212. - (UIWindow *)createUIWindowForLogin {
  213. // Create an empty window + viewController to host the Safari UI.
  214. UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  215. window.rootViewController = self.safariHostingViewController;
  216. // Place it at the highest level within the stack.
  217. window.windowLevel = +CGFLOAT_MAX;
  218. // Run it.
  219. [window makeKeyAndVisible];
  220. return window;
  221. }
  222. - (void)handleReleasesAPIResponseWithData:data
  223. completion:(FIRAppDistributionUpdateCheckCompletion)completion {
  224. NSError *error = nil;
  225. NSDictionary *serializedResponse = [NSJSONSerialization
  226. JSONObjectWithData:data
  227. options:0
  228. error:&error];
  229. NSArray *releaseList = [serializedResponse objectForKey:kReleasesKey];
  230. for (NSDictionary *releaseDict in releaseList) {
  231. if([[releaseDict objectForKey:kLatestReleaseKey] boolValue]) {
  232. NSString *codeHash = [releaseDict objectForKey:kCodeHashKey];
  233. NSString *executablePath = [[NSBundle mainBundle] executablePath];
  234. FIRAppDistributionMachO *machO = [[FIRAppDistributionMachO alloc] initWithPath:executablePath];
  235. if(codeHash && ![codeHash isEqualToString:machO.codeHash]) {
  236. FIRAppDistributionRelease *release = [[FIRAppDistributionRelease alloc] initWithDictionary:releaseDict];
  237. dispatch_async(dispatch_get_main_queue(), ^{
  238. completion(release, nil);
  239. });
  240. return;
  241. }
  242. break;
  243. }
  244. }
  245. dispatch_async(dispatch_get_main_queue(), ^{
  246. completion(nil, nil);
  247. });
  248. }
  249. - (void)checkForUpdateWithCompletion:(FIRAppDistributionUpdateCheckCompletion)completion {
  250. if (self.isTesterSignedIn) {
  251. [self fetchReleases:completion];
  252. } else {
  253. UIAlertController *alert = [UIAlertController
  254. alertControllerWithTitle:@"Enable in-app alerts"
  255. message:@"Sign in with your Firebase App Distribution Google account to "
  256. @"turn on in-app alerts for new test releases."
  257. preferredStyle:UIAlertControllerStyleAlert];
  258. UIAlertAction *yesButton =
  259. [UIAlertAction actionWithTitle:@"Turn on"
  260. style:UIAlertActionStyleDefault
  261. handler:^(UIAlertAction *action) {
  262. [self signInTesterWithCompletion:^(NSError *_Nullable error) {
  263. self.window.hidden = YES;
  264. self.window = nil;
  265. if (error) {
  266. completion(nil, error);
  267. return;
  268. }
  269. [self fetchReleases:completion];
  270. }];
  271. }];
  272. UIAlertAction *noButton = [UIAlertAction actionWithTitle:@"Not now"
  273. style:UIAlertActionStyleDefault
  274. handler:^(UIAlertAction *action) {
  275. // precaution to ensure window gets destroyed
  276. self.window.hidden = YES;
  277. self.window = nil;
  278. completion(nil, nil);
  279. }];
  280. [alert addAction:noButton];
  281. [alert addAction:yesButton];
  282. // Create an empty window + viewController to host the Safari UI.
  283. self.window = [self createUIWindowForLogin];
  284. [self.window.rootViewController presentViewController:alert animated:YES completion:nil];
  285. }
  286. }
  287. @end