AuthAppCredentialManager.swift 4.6 KB

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