StorageTokenAuthorizer.swift 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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 FirebaseCoreExtension
  19. #if COCOAPODS
  20. @preconcurrency import GTMSessionFetcher
  21. #else
  22. @preconcurrency import GTMSessionFetcherCore
  23. #endif
  24. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  25. final class StorageTokenAuthorizer: NSObject, GTMSessionFetcherAuthorizer, Sendable {
  26. func authorizeRequest(_ request: NSMutableURLRequest?,
  27. completionHandler handler: @escaping @Sendable (Error?) -> Void) {
  28. if let request = request {
  29. Task {
  30. do {
  31. try await self._authorizeRequest(request)
  32. handler(nil)
  33. } catch {
  34. handler(error)
  35. }
  36. }
  37. }
  38. }
  39. private func _authorizeRequest(_ request: NSMutableURLRequest) async throws {
  40. // Set version header on each request
  41. let versionString = "ios/\(FirebaseVersion())"
  42. request.setValue(versionString, forHTTPHeaderField: "x-firebase-storage-version")
  43. // Set GMP ID on each request
  44. request.setValue(googleAppID, forHTTPHeaderField: "x-firebase-gmpid")
  45. if let auth {
  46. let token: String = try await withCheckedThrowingContinuation { continuation in
  47. auth.getToken(forcingRefresh: false) { token, error in
  48. if let error = error as? NSError {
  49. var errorDictionary = error.userInfo
  50. errorDictionary["ResponseErrorDomain"] = error.domain
  51. errorDictionary["ResponseErrorCode"] = error.code
  52. let wrappedError = StorageError.unauthenticated(serverError: errorDictionary) as Error
  53. continuation.resume(throwing: wrappedError)
  54. } else if let token {
  55. let firebaseToken = "Firebase \(token)"
  56. continuation.resume(returning: firebaseToken)
  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. continuation.resume(throwing: unknownError)
  69. }
  70. }
  71. }
  72. request.setValue(token, forHTTPHeaderField: "Authorization")
  73. }
  74. if let appCheck {
  75. let token = await withCheckedContinuation { continuation in
  76. appCheck.getToken(forcingRefresh: false) { tokenResult in
  77. if let error = tokenResult.error {
  78. FirebaseLogger.log(
  79. level: .debug,
  80. service: "[FirebaseStorage]",
  81. code: "I-STR000001",
  82. message: "Failed to fetch AppCheck token. Error: \(error)"
  83. )
  84. }
  85. continuation.resume(returning: tokenResult.token)
  86. }
  87. }
  88. request.setValue(token, forHTTPHeaderField: "X-Firebase-AppCheck")
  89. }
  90. }
  91. func authorizeRequest(_ request: NSMutableURLRequest?, delegate: Any, didFinish sel: Selector) {
  92. fatalError("Internal error: Should not call old authorizeRequest")
  93. }
  94. // Note that stopAuthorization, isAuthorizingRequest, and userEmail
  95. // aren't relevant with the Firebase App/Auth implementation of tokens,
  96. // and thus aren't implemented. Token refresh is handled transparently
  97. // for us, and we don't allow the auth request to be stopped.
  98. // Auth is also not required so the world doesn't stop.
  99. func stopAuthorization() {}
  100. func stopAuthorization(for request: URLRequest) {}
  101. func isAuthorizingRequest(_ request: URLRequest) -> Bool {
  102. return false
  103. }
  104. func isAuthorizedRequest(_ request: URLRequest) -> Bool {
  105. guard let authHeader = request.allHTTPHeaderFields?["Authorization"] else {
  106. return false
  107. }
  108. return authHeader.hasPrefix("Firebase")
  109. }
  110. let userEmail: String?
  111. let callbackQueue: DispatchQueue
  112. private let googleAppID: String
  113. private let auth: AuthInterop?
  114. private let appCheck: AppCheckInterop?
  115. private let serialAuthArgsQueue = DispatchQueue(label: "com.google.firebasestorage.authorizer")
  116. init(googleAppID: String,
  117. callbackQueue: DispatchQueue = DispatchQueue.main,
  118. authProvider: AuthInterop?,
  119. appCheck: AppCheckInterop?) {
  120. self.googleAppID = googleAppID
  121. self.callbackQueue = callbackQueue
  122. auth = authProvider
  123. self.appCheck = appCheck
  124. }
  125. }