GACAppCheckAPIService.m 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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 "AppCheckCore/Sources/Core/APIService/GACAppCheckAPIService.h"
  17. #if __has_include(<FBLPromises/FBLPromises.h>)
  18. #import <FBLPromises/FBLPromises.h>
  19. #else
  20. #import "FBLPromises.h"
  21. #endif
  22. #import "AppCheckCore/Sources/Core/APIService/GACAppCheckToken+APIResponse.h"
  23. #import "AppCheckCore/Sources/Core/Errors/GACAppCheckErrorUtil.h"
  24. #import "AppCheckCore/Sources/Core/GACAppCheckLogger+Internal.h"
  25. #import "AppCheckCore/Sources/Public/AppCheckCore/GACAppCheckErrors.h"
  26. #import "AppCheckCore/Sources/Public/AppCheckCore/GACAppCheckLogger.h"
  27. #import <GoogleUtilities/GULURLSessionDataResponse.h>
  28. #import <GoogleUtilities/NSURLSession+GULPromises.h>
  29. NS_ASSUME_NONNULL_BEGIN
  30. static NSString *const kAPIKeyHeaderKey = @"X-Goog-Api-Key";
  31. static NSString *const kBundleIdKey = @"X-Ios-Bundle-Identifier";
  32. static NSString *const kDefaultBaseURL = @"https://firebaseappcheck.googleapis.com/v1";
  33. @interface GACAppCheckAPIService ()
  34. @property(nonatomic, readonly) NSURLSession *URLSession;
  35. @property(nonatomic, readonly, nullable) NSString *APIKey;
  36. @property(nonatomic, readonly) NSArray<GACAppCheckAPIRequestHook> *requestHooks;
  37. @end
  38. @implementation GACAppCheckAPIService
  39. // Synthesize properties declared in a protocol.
  40. @synthesize baseURL = _baseURL;
  41. - (instancetype)initWithURLSession:(NSURLSession *)session
  42. baseURL:(nullable NSString *)baseURL
  43. APIKey:(nullable NSString *)APIKey
  44. requestHooks:(nullable NSArray<GACAppCheckAPIRequestHook> *)requestHooks {
  45. self = [super init];
  46. if (self) {
  47. _URLSession = session;
  48. _APIKey = APIKey;
  49. _requestHooks = requestHooks ? [requestHooks copy] : @[];
  50. _baseURL = baseURL ?: kDefaultBaseURL;
  51. }
  52. return self;
  53. }
  54. - (FBLPromise<GULURLSessionDataResponse *> *)
  55. sendRequestWithURL:(NSURL *)requestURL
  56. HTTPMethod:(NSString *)HTTPMethod
  57. body:(nullable NSData *)body
  58. additionalHeaders:(nullable NSDictionary<NSString *, NSString *> *)additionalHeaders {
  59. return [self requestWithURL:requestURL
  60. HTTPMethod:HTTPMethod
  61. body:body
  62. additionalHeaders:additionalHeaders]
  63. .then(^id _Nullable(NSURLRequest *_Nullable request) {
  64. return [self sendURLRequest:request];
  65. })
  66. .then(^id _Nullable(GULURLSessionDataResponse *_Nullable response) {
  67. return [self validateHTTPResponseStatusCode:response];
  68. });
  69. }
  70. - (FBLPromise<NSURLRequest *> *)requestWithURL:(NSURL *)requestURL
  71. HTTPMethod:(NSString *)HTTPMethod
  72. body:(NSData *)body
  73. additionalHeaders:(nullable NSDictionary<NSString *, NSString *> *)
  74. additionalHeaders {
  75. return [FBLPromise
  76. onQueue:[self defaultQueue]
  77. do:^id _Nullable {
  78. __block NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL];
  79. request.HTTPMethod = HTTPMethod;
  80. request.HTTPBody = body;
  81. if (self.APIKey) {
  82. [request setValue:self.APIKey forHTTPHeaderField:kAPIKeyHeaderKey];
  83. }
  84. [request setValue:[[NSBundle mainBundle] bundleIdentifier]
  85. forHTTPHeaderField:kBundleIdKey];
  86. [additionalHeaders
  87. enumerateKeysAndObjectsUsingBlock:^(NSString *_Nonnull key, NSString *_Nonnull obj,
  88. BOOL *_Nonnull stop) {
  89. [request setValue:obj forHTTPHeaderField:key];
  90. }];
  91. for (GACAppCheckAPIRequestHook requestHook in self.requestHooks) {
  92. requestHook(request);
  93. }
  94. return [request copy];
  95. }];
  96. }
  97. - (FBLPromise<GULURLSessionDataResponse *> *)sendURLRequest:(NSURLRequest *)request {
  98. return [self.URLSession gul_dataTaskPromiseWithRequest:request]
  99. .recover(^id(NSError *networkError) {
  100. // Wrap raw network error into App Check domain error.
  101. return [GACAppCheckErrorUtil APIErrorWithNetworkError:networkError];
  102. })
  103. .then(^id _Nullable(GULURLSessionDataResponse *response) {
  104. return [self validateHTTPResponseStatusCode:response];
  105. });
  106. }
  107. - (FBLPromise<GULURLSessionDataResponse *> *)validateHTTPResponseStatusCode:
  108. (GULURLSessionDataResponse *)response {
  109. NSInteger statusCode = response.HTTPResponse.statusCode;
  110. return [FBLPromise do:^id _Nullable {
  111. if (statusCode < 200 || statusCode >= 300) {
  112. NSString *logMessage = [NSString
  113. stringWithFormat:@"Unexpected API response: %@, body: %@.", response.HTTPResponse,
  114. [[NSString alloc] initWithData:response.HTTPBody
  115. encoding:NSUTF8StringEncoding]];
  116. GACAppCheckLogDebug(GACLoggerAppCheckMessageCodeUnexpectedHTTPCode, logMessage);
  117. return [GACAppCheckErrorUtil APIErrorWithHTTPResponse:response.HTTPResponse
  118. data:response.HTTPBody];
  119. }
  120. return response;
  121. }];
  122. }
  123. - (FBLPromise<GACAppCheckToken *> *)appCheckTokenWithAPIResponse:
  124. (GULURLSessionDataResponse *)response {
  125. return [FBLPromise onQueue:[self defaultQueue]
  126. do:^id _Nullable {
  127. NSError *error;
  128. GACAppCheckToken *token = [[GACAppCheckToken alloc]
  129. initWithTokenExchangeResponse:response.HTTPBody
  130. requestDate:[NSDate date]
  131. error:&error];
  132. return token ?: error;
  133. }];
  134. }
  135. - (dispatch_queue_t)defaultQueue {
  136. return dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0);
  137. }
  138. @end
  139. NS_ASSUME_NONNULL_END