StorageTokenAuthorizer.swift 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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. import FirebaseAppCheckInterop
  16. import FirebaseAuthInterop
  17. import FirebaseCore
  18. @_implementationOnly import FirebaseCoreExtension
  19. #if COCOAPODS
  20. import GTMSessionFetcher
  21. #else
  22. import GTMSessionFetcherCore
  23. #endif
  24. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  25. class StorageTokenAuthorizer: NSObject, GTMSessionFetcherAuthorizer {
  26. func authorizeRequest(_ request: NSMutableURLRequest?,
  27. completionHandler handler: @escaping (Error?) -> Void) {
  28. // Set version header on each request
  29. let versionString = "ios/\(FirebaseVersion())"
  30. request?.setValue(versionString, forHTTPHeaderField: "x-firebase-storage-version")
  31. // Set GMP ID on each request
  32. request?.setValue(googleAppID, forHTTPHeaderField: "x-firebase-gmpid")
  33. var tokenError: NSError?
  34. let callbackQueue = fetcherService.callbackQueue ?? DispatchQueue.main
  35. let fetchTokenGroup = DispatchGroup()
  36. if let auth {
  37. fetchTokenGroup.enter()
  38. auth.getToken(forcingRefresh: false) { token, error in
  39. if let error = error as? NSError {
  40. var errorDictionary = error.userInfo
  41. errorDictionary["ResponseErrorDomain"] = error.domain
  42. errorDictionary["ResponseErrorCode"] = error.code
  43. tokenError = StorageError.unauthenticated(serverError: errorDictionary) as NSError
  44. } else if let token {
  45. let firebaseToken = "Firebase \(token)"
  46. request?.setValue(firebaseToken, forHTTPHeaderField: "Authorization")
  47. }
  48. fetchTokenGroup.leave()
  49. }
  50. }
  51. if let appCheck {
  52. fetchTokenGroup.enter()
  53. appCheck.getToken(forcingRefresh: false) { tokenResult in
  54. request?.setValue(tokenResult.token, forHTTPHeaderField: "X-Firebase-AppCheck")
  55. if let error = tokenResult.error {
  56. FirebaseLogger.log(
  57. level: .debug,
  58. service: "[FirebaseStorage]",
  59. code: "I-STR000001",
  60. message: "Failed to fetch AppCheck token. Error: \(error)"
  61. )
  62. }
  63. fetchTokenGroup.leave()
  64. }
  65. }
  66. fetchTokenGroup.notify(queue: callbackQueue) {
  67. handler(tokenError)
  68. }
  69. }
  70. func authorizeRequest(_ request: NSMutableURLRequest?, delegate: Any, didFinish sel: Selector) {
  71. fatalError("Internal error: Should not call old authorizeRequest")
  72. }
  73. // Note that stopAuthorization, isAuthorizingRequest, and userEmail
  74. // aren't relevant with the Firebase App/Auth implementation of tokens,
  75. // and thus aren't implemented. Token refresh is handled transparently
  76. // for us, and we don't allow the auth request to be stopped.
  77. // Auth is also not required so the world doesn't stop.
  78. func stopAuthorization() {}
  79. func stopAuthorization(for request: URLRequest) {}
  80. func isAuthorizingRequest(_ request: URLRequest) -> Bool {
  81. return false
  82. }
  83. func isAuthorizedRequest(_ request: URLRequest) -> Bool {
  84. guard let authHeader = request.allHTTPHeaderFields?["Authorization"] else {
  85. return false
  86. }
  87. return authHeader.hasPrefix("Firebase")
  88. }
  89. var userEmail: String?
  90. let fetcherService: GTMSessionFetcherService
  91. private let googleAppID: String
  92. private let auth: AuthInterop?
  93. private let appCheck: AppCheckInterop?
  94. private let serialAuthArgsQueue = DispatchQueue(label: "com.google.firebasestorage.authorizer")
  95. init(googleAppID: String,
  96. fetcherService: GTMSessionFetcherService,
  97. authProvider: AuthInterop?,
  98. appCheck: AppCheckInterop?) {
  99. self.googleAppID = googleAppID
  100. self.fetcherService = fetcherService
  101. auth = authProvider
  102. self.appCheck = appCheck
  103. }
  104. }