StorageTokenAuthorizer.swift 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. // Copyright 2022 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 Foundation
  15. @preconcurrency import FirebaseAppCheckInterop /* TODO: sendable */
  16. import FirebaseAuthInterop
  17. import FirebaseCore
  18. internal import FirebaseCoreInternal
  19. internal import FirebaseCoreExtension
  20. #if COCOAPODS
  21. @preconcurrency import GTMSessionFetcher
  22. #else
  23. @preconcurrency import GTMSessionFetcherCore
  24. #endif
  25. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  26. final class StorageTokenAuthorizer: NSObject, GTMSessionFetcherAuthorizer, Sendable {
  27. func authorizeRequest(_ incomingRequest: NSMutableURLRequest?,
  28. completionHandler handler: @escaping @Sendable (Error?) -> Void) {
  29. guard let _request = incomingRequest else {
  30. handler(nil)
  31. return
  32. }
  33. let request = FIRNonisolatedUnsafe(initialState: _request)
  34. // Set version header on each request
  35. let versionString = "ios/\(FirebaseVersion())"
  36. request.withNonisolatedUnsafeState { state in
  37. state.setValue(versionString, forHTTPHeaderField: "x-firebase-storage-version")
  38. // Set GMP ID on each request
  39. state.setValue(googleAppID, forHTTPHeaderField: "x-firebase-gmpid")
  40. }
  41. // If there's no Auth to authorize the request, pass it back with just header changes.
  42. guard let auth = auth else {
  43. handler(nil)
  44. return
  45. }
  46. auth.getToken(forcingRefresh: false) { token, error in
  47. let firebaseToken: String
  48. if let token {
  49. firebaseToken = "Firebase \(token)"
  50. } else if let error = error as? NSError {
  51. var errorDictionary = error.userInfo
  52. errorDictionary["ResponseErrorDomain"] = error.domain
  53. errorDictionary["ResponseErrorCode"] = error.code
  54. let wrappedError = StorageError.unauthenticated(serverError: errorDictionary) as Error
  55. handler(wrappedError)
  56. return
  57. } else {
  58. let underlyingError: [String: Any]
  59. if let error = error {
  60. underlyingError = [NSUnderlyingErrorKey: error]
  61. } else {
  62. underlyingError = [:]
  63. }
  64. let unknownError = StorageError.unknown(
  65. message: "Auth token fetch returned no token or error: \(token ?? "nil")",
  66. serverError: underlyingError
  67. ) as Error
  68. handler(unknownError)
  69. return
  70. }
  71. request.withNonisolatedUnsafeState { state in
  72. state.setValue(firebaseToken, forHTTPHeaderField: "Authorization")
  73. }
  74. guard let appCheck = self.appCheck else {
  75. handler(nil)
  76. return
  77. }
  78. appCheck.getToken(forcingRefresh: false) { tokenResult in
  79. if let error = tokenResult.error {
  80. FirebaseLogger.log(
  81. level: .debug,
  82. service: "[FirebaseStorage]",
  83. code: "I-STR000001",
  84. message: "Failed to fetch AppCheck token. Error: \(error)"
  85. )
  86. // Don't bubble the error up to the authorizer if we successfully
  87. // got an auth token earlier.
  88. }
  89. request.withNonisolatedUnsafeState { state in
  90. state.setValue(token, forHTTPHeaderField: "X-Firebase-AppCheck")
  91. }
  92. handler(nil)
  93. }
  94. }
  95. }
  96. private func _authorizeRequest(_ request: NSMutableURLRequest) async throws {
  97. // Set version header on each request
  98. let versionString = "ios/\(FirebaseVersion())"
  99. request.setValue(versionString, forHTTPHeaderField: "x-firebase-storage-version")
  100. // Set GMP ID on each request
  101. request.setValue(googleAppID, forHTTPHeaderField: "x-firebase-gmpid")
  102. if let auth {
  103. let token: String = try await withCheckedThrowingContinuation { continuation in
  104. auth.getToken(forcingRefresh: false) { token, error in
  105. if let error = error as? NSError {
  106. var errorDictionary = error.userInfo
  107. errorDictionary["ResponseErrorDomain"] = error.domain
  108. errorDictionary["ResponseErrorCode"] = error.code
  109. let wrappedError = StorageError.unauthenticated(serverError: errorDictionary) as Error
  110. continuation.resume(throwing: wrappedError)
  111. } else if let token {
  112. let firebaseToken = "Firebase \(token)"
  113. continuation.resume(returning: firebaseToken)
  114. } else {
  115. let underlyingError: [String: Any]
  116. if let error = error {
  117. underlyingError = [NSUnderlyingErrorKey: error]
  118. } else {
  119. underlyingError = [:]
  120. }
  121. let unknownError = StorageError.unknown(
  122. message: "Auth token fetch returned no token or error: \(token ?? "nil")",
  123. serverError: underlyingError
  124. ) as Error
  125. continuation.resume(throwing: unknownError)
  126. }
  127. }
  128. }
  129. request.setValue(token, forHTTPHeaderField: "Authorization")
  130. }
  131. if let appCheck {
  132. let token = await withCheckedContinuation { continuation in
  133. appCheck.getToken(forcingRefresh: false) { tokenResult in
  134. if let error = tokenResult.error {
  135. FirebaseLogger.log(
  136. level: .debug,
  137. service: "[FirebaseStorage]",
  138. code: "I-STR000001",
  139. message: "Failed to fetch AppCheck token. Error: \(error)"
  140. )
  141. }
  142. continuation.resume(returning: tokenResult.token)
  143. }
  144. }
  145. request.setValue(token, forHTTPHeaderField: "X-Firebase-AppCheck")
  146. }
  147. }
  148. func authorizeRequest(_ request: NSMutableURLRequest?, delegate: Any, didFinish sel: Selector) {
  149. fatalError("Internal error: Should not call old authorizeRequest")
  150. }
  151. // Note that stopAuthorization, isAuthorizingRequest, and userEmail
  152. // aren't relevant with the Firebase App/Auth implementation of tokens,
  153. // and thus aren't implemented. Token refresh is handled transparently
  154. // for us, and we don't allow the auth request to be stopped.
  155. // Auth is also not required so the world doesn't stop.
  156. func stopAuthorization() {}
  157. func stopAuthorization(for request: URLRequest) {}
  158. func isAuthorizingRequest(_ request: URLRequest) -> Bool {
  159. return false
  160. }
  161. func isAuthorizedRequest(_ request: URLRequest) -> Bool {
  162. guard let authHeader = request.allHTTPHeaderFields?["Authorization"] else {
  163. return false
  164. }
  165. return authHeader.hasPrefix("Firebase")
  166. }
  167. // Used for protocol conformance only.
  168. let userEmail: String? = nil
  169. let callbackQueue: DispatchQueue
  170. private let googleAppID: String
  171. private let auth: AuthInterop?
  172. private let appCheck: AppCheckInterop?
  173. private let serialAuthArgsQueue = DispatchQueue(label: "com.google.firebasestorage.authorizer")
  174. init(googleAppID: String,
  175. callbackQueue: DispatchQueue = DispatchQueue.main,
  176. authProvider: AuthInterop?,
  177. appCheck: AppCheckInterop?) {
  178. self.googleAppID = googleAppID
  179. self.callbackQueue = callbackQueue
  180. auth = authProvider
  181. self.appCheck = appCheck
  182. }
  183. }