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/Sources/Private/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-log-type";
  31. static NSString *const kHeartbeatStorageTag = @"fire-app-check";
  32. static NSString *const kUserAgentKey = @"X-firebase-client";
  33. static NSString *const kDefaultBaseURL = @"https://firebaseappcheck.googleapis.com/v1beta";
  34. @interface FIRAppCheckAPIService ()
  35. @property(nonatomic, readonly) NSURLSession *URLSession;
  36. @property(nonatomic, readonly) NSString *APIKey;
  37. @property(nonatomic, readonly) NSString *projectID;
  38. @property(nonatomic, readonly) NSString *appID;
  39. @end
  40. @implementation FIRAppCheckAPIService
  41. // Synthesize properties declared in a protocol.
  42. @synthesize baseURL = _baseURL;
  43. - (instancetype)initWithURLSession:(NSURLSession *)session
  44. APIKey:(NSString *)APIKey
  45. projectID:(NSString *)projectID
  46. appID:(NSString *)appID {
  47. return [self initWithURLSession:session
  48. APIKey:APIKey
  49. projectID:projectID
  50. appID:appID
  51. baseURL:kDefaultBaseURL];
  52. }
  53. - (instancetype)initWithURLSession:(NSURLSession *)session
  54. APIKey:(NSString *)APIKey
  55. projectID:(NSString *)projectID
  56. appID:(NSString *)appID
  57. baseURL:(NSString *)baseURL {
  58. self = [super init];
  59. if (self) {
  60. _URLSession = session;
  61. _APIKey = APIKey;
  62. _projectID = projectID;
  63. _appID = appID;
  64. _baseURL = baseURL;
  65. }
  66. return self;
  67. }
  68. - (FBLPromise<GULURLSessionDataResponse *> *)
  69. sendRequestWithURL:(NSURL *)requestURL
  70. HTTPMethod:(NSString *)HTTPMethod
  71. body:(nullable NSData *)body
  72. additionalHeaders:(nullable NSDictionary<NSString *, NSString *> *)additionalHeaders {
  73. return [self requestWithURL:requestURL
  74. HTTPMethod:HTTPMethod
  75. body:body
  76. additionalHeaders:additionalHeaders]
  77. .then(^id _Nullable(NSURLRequest *_Nullable request) {
  78. return [self sendURLRequest:request];
  79. })
  80. .then(^id _Nullable(GULURLSessionDataResponse *_Nullable response) {
  81. return [self validateHTTPResponseStatusCode:response];
  82. });
  83. }
  84. - (FBLPromise<NSURLRequest *> *)requestWithURL:(NSURL *)requestURL
  85. HTTPMethod:(NSString *)HTTPMethod
  86. body:(NSData *)body
  87. additionalHeaders:(nullable NSDictionary<NSString *, NSString *> *)
  88. additionalHeaders {
  89. return [FBLPromise
  90. onQueue:[self defaultQueue]
  91. do:^id _Nullable {
  92. __block NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL];
  93. request.HTTPMethod = HTTPMethod;
  94. request.HTTPBody = body;
  95. [request setValue:self.APIKey forHTTPHeaderField:kAPIKeyHeaderKey];
  96. [request setValue:[FIRApp firebaseUserAgent] forHTTPHeaderField:kUserAgentKey];
  97. [request setValue:@([FIRHeartbeatInfo heartbeatCodeForTag:kHeartbeatStorageTag])
  98. .stringValue
  99. forHTTPHeaderField:kHeartbeatKey];
  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