FIRAppCheckAPIService.m 6.8 KB

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