SecureTokenService.swift 9.6 KB

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