SecureTokenService.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. // Copyright 2023 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 FirebaseCoreInternal
  15. import Foundation
  16. private let kFiveMinutes = 5 * 60.0
  17. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  18. actor SecureTokenServiceInternal {
  19. /// Fetch a fresh ephemeral access token for the ID associated with this instance. The token
  20. /// received in the callback should be considered short lived and not cached.
  21. ///
  22. /// Invoked asynchronously on the auth global work queue in the future.
  23. /// - Parameter forceRefresh: Forces the token to be refreshed.
  24. /// - Returns : A tuple with the token and flag of whether it was updated.
  25. func fetchAccessToken(forcingRefresh forceRefresh: Bool,
  26. service: SecureTokenService,
  27. backend: AuthBackend) async throws -> (String?, Bool) {
  28. if !forceRefresh, hasValidAccessToken(service: service) {
  29. return (service.accessToken, false)
  30. } else {
  31. AuthLog.logDebug(code: "I-AUT000017", message: "Fetching new token from backend.")
  32. return try await requestAccessToken(retryIfExpired: true, service: service, backend: backend)
  33. }
  34. }
  35. /// Makes a request to STS for an access token.
  36. ///
  37. /// This handles both the case that the token has not been granted yet and that it just needs
  38. /// needs to be refreshed.
  39. ///
  40. /// - Returns: Token and Bool indicating if update occurred.
  41. private func requestAccessToken(retryIfExpired: Bool,
  42. service: SecureTokenService,
  43. backend: AuthBackend) async throws -> (String?, Bool) {
  44. // TODO: This was a crash in ObjC SDK, should it callback with an error?
  45. guard let refreshToken = service.refreshToken,
  46. let requestConfiguration = service.requestConfiguration else {
  47. fatalError("refreshToken and requestConfiguration should not be nil")
  48. }
  49. let request = SecureTokenRequest.refreshRequest(refreshToken: refreshToken,
  50. requestConfiguration: requestConfiguration)
  51. let response = try await backend.call(with: request)
  52. var tokenUpdated = false
  53. if let newAccessToken = response.accessToken,
  54. newAccessToken.count > 0,
  55. newAccessToken != service.accessToken {
  56. if let tokenResult = try? AuthTokenResult.tokenResult(token: newAccessToken) {
  57. // There is an edge case where the request for a new access token may be made right
  58. // before the app goes inactive, resulting in the callback being invoked much later
  59. // with an expired access token. This does not fully solve the issue, as if the
  60. // callback is invoked less than an hour after the request is made, a token is not
  61. // re-requested here but the approximateExpirationDate will still be off since that
  62. // is computed at the time the token is received.
  63. if retryIfExpired {
  64. let expirationDate = tokenResult.expirationDate
  65. if expirationDate.timeIntervalSinceNow <= kFiveMinutes {
  66. // We only retry once, to avoid an infinite loop in the case that an end-user has
  67. // their local time skewed by over an hour.
  68. return try await requestAccessToken(
  69. retryIfExpired: false,
  70. service: service,
  71. backend: backend
  72. )
  73. }
  74. }
  75. }
  76. service.accessToken = newAccessToken
  77. service.accessTokenExpirationDate = response.approximateExpirationDate
  78. tokenUpdated = true
  79. AuthLog.logDebug(
  80. code: "I-AUT000017",
  81. message: "Updated access token. Estimated expiration date: " +
  82. "\(String(describing: service.accessTokenExpirationDate)), current date: \(Date())"
  83. )
  84. }
  85. if let newRefreshToken = response.refreshToken,
  86. newRefreshToken != service.refreshToken {
  87. service.refreshToken = newRefreshToken
  88. tokenUpdated = true
  89. }
  90. return (response.accessToken, tokenUpdated)
  91. }
  92. private func hasValidAccessToken(service: SecureTokenService) -> Bool {
  93. if let accessTokenExpirationDate = service.accessTokenExpirationDate,
  94. accessTokenExpirationDate.timeIntervalSinceNow > kFiveMinutes {
  95. AuthLog.logDebug(code: "I-AUT000017",
  96. message: "Has valid access token. Estimated expiration date:" +
  97. "\(accessTokenExpirationDate), current date: \(Date())")
  98. return true
  99. }
  100. AuthLog.logDebug(
  101. code: "I-AUT000017",
  102. message: "Does not have valid access token. Estimated expiration date:" +
  103. "\(String(describing: service.accessTokenExpirationDate)), current date: \(Date())"
  104. )
  105. return false
  106. }
  107. }
  108. /// A class represents a credential that proves the identity of the app.
  109. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  110. @objc(FIRSecureTokenService) // objc Needed for decoding old versions
  111. final class SecureTokenService: NSObject, NSSecureCoding, Sendable {
  112. /// Internal actor to enforce serialization
  113. private let internalService: SecureTokenServiceInternal
  114. /// The configuration for making requests to server.
  115. var requestConfiguration: AuthRequestConfiguration? {
  116. get { _requestConfiguration.withLock { $0 } }
  117. set { _requestConfiguration.withLock { $0 = newValue } }
  118. }
  119. let _requestConfiguration: UnfairLock<AuthRequestConfiguration?>
  120. /// The cached access token.
  121. ///
  122. /// This method is specifically for providing the access token to internal clients during
  123. /// deserialization and sign-in events, and should not be used to retrieve the access token by
  124. /// anyone else.
  125. ///
  126. /// - Note: The atomic wrapper can be removed when the SDK is fully
  127. /// synchronized with structured concurrency.
  128. var accessToken: String {
  129. get { _accessToken.withLock { $0 } }
  130. set { _accessToken.withLock { $0 = newValue } }
  131. }
  132. private let _accessToken: UnfairLock<String>
  133. /// The refresh token for the user, or `nil` if the user has yet completed sign-in flow.
  134. ///
  135. /// This property needs to be set manually after the instance is decoded from archive.
  136. var refreshToken: String? {
  137. get { _refreshToken.withLock { $0 } }
  138. set { _refreshToken.withLock { $0 = newValue } }
  139. }
  140. private let _refreshToken: UnfairLock<String?>
  141. /// The expiration date of the cached access token.
  142. var accessTokenExpirationDate: Date? {
  143. get { _accessTokenExpirationDate.withLock { $0 } }
  144. set { _accessTokenExpirationDate.withLock { $0 = newValue } }
  145. }
  146. private let _accessTokenExpirationDate: UnfairLock<Date?>
  147. /// Creates a `SecureTokenService` with access and refresh tokens.
  148. /// - Parameter requestConfiguration: The configuration for making requests to server.
  149. /// - Parameter accessToken: The STS access token.
  150. /// - Parameter accessTokenExpirationDate: The approximate expiration date of the access token.
  151. /// - Parameter refreshToken: The STS refresh token.
  152. init(withRequestConfiguration requestConfiguration: AuthRequestConfiguration?,
  153. accessToken: String,
  154. accessTokenExpirationDate: Date?,
  155. refreshToken: String) {
  156. internalService = SecureTokenServiceInternal()
  157. _requestConfiguration = UnfairLock(requestConfiguration)
  158. _accessToken = UnfairLock(accessToken)
  159. _accessTokenExpirationDate = UnfairLock(accessTokenExpirationDate)
  160. _refreshToken = UnfairLock(refreshToken)
  161. }
  162. /// Fetch a fresh ephemeral access token for the ID associated with this instance. The token
  163. /// received in the callback should be considered short lived and not cached.
  164. ///
  165. /// Invoked asynchronously on the auth global work queue in the future.
  166. /// - Parameter forceRefresh: Forces the token to be refreshed.
  167. /// - Returns : A tuple with the token and flag of whether it was updated.
  168. func fetchAccessToken(forcingRefresh forceRefresh: Bool,
  169. backend: AuthBackend) async throws -> (String?, Bool) {
  170. return try await internalService
  171. .fetchAccessToken(forcingRefresh: forceRefresh, service: self, backend: backend)
  172. }
  173. // MARK: NSSecureCoding
  174. // Secure coding keys
  175. private let kAPIKeyCodingKey = "APIKey"
  176. private static let kRefreshTokenKey = "refreshToken"
  177. private static let kAccessTokenKey = "accessToken"
  178. private static let kAccessTokenExpirationDateKey = "accessTokenExpirationDate"
  179. static let supportsSecureCoding = true
  180. required convenience init?(coder: NSCoder) {
  181. guard let refreshToken = coder.decodeObject(of: [NSString.self],
  182. forKey: Self.kRefreshTokenKey) as? String,
  183. let accessToken = coder.decodeObject(of: [NSString.self],
  184. forKey: Self.kAccessTokenKey) as? String else {
  185. return nil
  186. }
  187. let accessTokenExpirationDate = coder.decodeObject(
  188. of: [NSDate.self], forKey: Self.kAccessTokenExpirationDateKey
  189. ) as? Date
  190. // requestConfiguration is filled in after User is set by Auth.protectedDataInitialization.
  191. self.init(withRequestConfiguration: nil,
  192. accessToken: accessToken,
  193. accessTokenExpirationDate: accessTokenExpirationDate,
  194. refreshToken: refreshToken)
  195. }
  196. func encode(with coder: NSCoder) {
  197. // The API key is encoded even it is not used in decoding to be compatible with previous
  198. // versions of the library.
  199. coder.encode(requestConfiguration?.apiKey, forKey: kAPIKeyCodingKey)
  200. // Authorization code is not encoded because it is not long-lived.
  201. coder.encode(refreshToken, forKey: SecureTokenService.kRefreshTokenKey)
  202. coder.encode(accessToken, forKey: SecureTokenService.kAccessTokenKey)
  203. coder.encode(
  204. accessTokenExpirationDate,
  205. forKey: SecureTokenService.kAccessTokenExpirationDateKey
  206. )
  207. }
  208. }