AuthAppCredentialManager.swift 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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. #if !os(macOS)
  15. import Foundation
  16. /** @class FIRAuthAppCredentialManager
  17. @brief A class to manage app credentials backed by iOS Keychain.
  18. */
  19. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  20. class AuthAppCredentialManager: NSObject {
  21. let kKeychainDataKey = "app_credentials"
  22. let kFullCredentialKey = "full_credential"
  23. let kPendingReceiptsKey = "pending_receipts"
  24. /** @property credential
  25. @brief The full credential (which has a secret) to be used by the app, if one is available.
  26. */
  27. var credential: AuthAppCredential?
  28. /** @property maximumNumberOfPendingReceipts
  29. @brief The maximum (but not necessarily the minimum) number of pending receipts to be kept.
  30. @remarks Only tests should access this property.
  31. */
  32. let maximumNumberOfPendingReceipts = 32
  33. init(withKeychain keychain: AuthKeychainServices) {
  34. keychainServices = keychain
  35. if let encodedData = try? keychain.data(forKey: kKeychainDataKey),
  36. let unarchiver = try? NSKeyedUnarchiver(forReadingFrom: encodedData) {
  37. if let credential = unarchiver.decodeObject(of: AuthAppCredential.self,
  38. forKey: kFullCredentialKey) {
  39. self.credential = credential
  40. }
  41. if let pendingReceipts = unarchiver.decodeObject(
  42. of: [NSString.self, NSArray.self],
  43. forKey: kPendingReceiptsKey
  44. ) as? [String] {
  45. self.pendingReceipts = pendingReceipts
  46. }
  47. }
  48. }
  49. func didStartVerificationInternal(withReceipt receipt: String,
  50. timeout: TimeInterval,
  51. callback: @escaping (AuthAppCredential) -> Void) {
  52. pendingReceipts = pendingReceipts.filter { $0 != receipt }
  53. if pendingReceipts.count >= maximumNumberOfPendingReceipts {
  54. pendingReceipts.remove(at: 0)
  55. }
  56. pendingReceipts.append(receipt)
  57. callbacksByReceipt[receipt] = callback
  58. saveData()
  59. kAuthGlobalWorkQueue.asyncAfter(deadline: .now() + timeout) {
  60. self.callbackWithReceipt(receipt)
  61. }
  62. }
  63. func didStartVerification(withReceipt receipt: String,
  64. timeout: TimeInterval) async -> AuthAppCredential {
  65. return await withCheckedContinuation { continuation in
  66. self.didStartVerificationInternal(withReceipt: receipt, timeout: timeout) { credential in
  67. continuation.resume(returning: credential)
  68. }
  69. }
  70. }
  71. func canFinishVerification(withReceipt receipt: String, secret: String) -> Bool {
  72. guard pendingReceipts.contains(receipt) else {
  73. return false
  74. }
  75. pendingReceipts = pendingReceipts.filter { $0 != receipt }
  76. credential = AuthAppCredential(receipt: receipt, secret: secret)
  77. saveData()
  78. callbackWithReceipt(receipt)
  79. return true
  80. }
  81. func clearCredential() {
  82. credential = nil
  83. saveData()
  84. }
  85. // MARK: Internal methods
  86. private func saveData() {
  87. let archiver = NSKeyedArchiver(requiringSecureCoding: true)
  88. archiver.encode(credential, forKey: kFullCredentialKey)
  89. archiver.encode(pendingReceipts, forKey: kPendingReceiptsKey)
  90. archiver.finishEncoding()
  91. try? keychainServices.setData(archiver.encodedData, forKey: kKeychainDataKey)
  92. }
  93. private func callbackWithReceipt(_ receipt: String) {
  94. guard let callback = callbacksByReceipt[receipt] else {
  95. return
  96. }
  97. callbacksByReceipt.removeValue(forKey: receipt)
  98. if let fakeCredential {
  99. callback(fakeCredential)
  100. } else if let credential {
  101. callback(credential)
  102. } else {
  103. callback(AuthAppCredential(receipt: receipt, secret: nil))
  104. }
  105. }
  106. /** @var _keychainServices
  107. @brief The keychain for app credentials to load from and to save to.
  108. */
  109. private let keychainServices: AuthKeychainServices
  110. /** @var pendingReceipts
  111. @brief A list of pending receipts sorted in the order they were recorded.
  112. */
  113. private var pendingReceipts: [String] = []
  114. /** @var callbacksByReceipt
  115. @brief A map from pending receipts to callbacks.
  116. */
  117. private var callbacksByReceipt: [String: (AuthAppCredential) -> Void] = [:]
  118. // Only for testing.
  119. var fakeCredential: AuthAppCredential?
  120. }
  121. #endif