GULKeychainStorage.m 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import <GoogleUtilities/GULKeychainStorage.h>
  17. #import <Security/Security.h>
  18. #if __has_include(<FBLPromises/FBLPromises.h>)
  19. #import <FBLPromises/FBLPromises.h>
  20. #else
  21. #import "FBLPromises.h"
  22. #endif
  23. #import <GoogleUtilities/GULKeychainUtils.h>
  24. #import <GoogleUtilities/GULSecureCoding.h>
  25. @interface GULKeychainStorage ()
  26. @property(nonatomic, readonly) dispatch_queue_t keychainQueue;
  27. @property(nonatomic, readonly) dispatch_queue_t inMemoryCacheQueue;
  28. @property(nonatomic, readonly) NSString *service;
  29. @property(nonatomic, readonly) NSCache<NSString *, id<NSSecureCoding>> *inMemoryCache;
  30. @end
  31. @implementation GULKeychainStorage
  32. - (instancetype)initWithService:(NSString *)service {
  33. NSCache *cache = [[NSCache alloc] init];
  34. // Cache up to 5 installations.
  35. cache.countLimit = 5;
  36. return [self initWithService:service cache:cache];
  37. }
  38. - (instancetype)initWithService:(NSString *)service cache:(NSCache *)cache {
  39. self = [super init];
  40. if (self) {
  41. _keychainQueue =
  42. dispatch_queue_create("com.gul.KeychainStorage.Keychain", DISPATCH_QUEUE_SERIAL);
  43. _inMemoryCacheQueue =
  44. dispatch_queue_create("com.gul.KeychainStorage.InMemoryCache", DISPATCH_QUEUE_SERIAL);
  45. _service = [service copy];
  46. _inMemoryCache = cache;
  47. }
  48. return self;
  49. }
  50. #pragma mark - Public
  51. - (FBLPromise<id<NSSecureCoding>> *)getObjectForKey:(NSString *)key
  52. objectClass:(Class)objectClass
  53. accessGroup:(nullable NSString *)accessGroup {
  54. return [FBLPromise onQueue:self.inMemoryCacheQueue
  55. do:^id _Nullable {
  56. // Return cached object or fail otherwise.
  57. id object = [self.inMemoryCache objectForKey:key];
  58. return object
  59. ?: [[NSError alloc]
  60. initWithDomain:FBLPromiseErrorDomain
  61. code:FBLPromiseErrorCodeValidationFailure
  62. userInfo:nil];
  63. }]
  64. .recover(^id _Nullable(NSError *error) {
  65. // Look for the object in the keychain.
  66. return [self getObjectFromKeychainForKey:key
  67. objectClass:objectClass
  68. accessGroup:accessGroup];
  69. });
  70. }
  71. - (FBLPromise<NSNull *> *)setObject:(id<NSSecureCoding>)object
  72. forKey:(NSString *)key
  73. accessGroup:(nullable NSString *)accessGroup {
  74. return [FBLPromise onQueue:self.inMemoryCacheQueue
  75. do:^id _Nullable {
  76. // Save to the in-memory cache first.
  77. [self.inMemoryCache setObject:object forKey:[key copy]];
  78. return [NSNull null];
  79. }]
  80. .thenOn(self.keychainQueue, ^id(id result) {
  81. // Then store the object to the keychain.
  82. NSDictionary *query = [self keychainQueryWithKey:key accessGroup:accessGroup];
  83. NSError *error;
  84. NSData *encodedObject = [GULSecureCoding archivedDataWithRootObject:object error:&error];
  85. if (!encodedObject) {
  86. return error;
  87. }
  88. if (![GULKeychainUtils setItem:encodedObject withQuery:query error:&error]) {
  89. return error;
  90. }
  91. return [NSNull null];
  92. });
  93. }
  94. - (FBLPromise<NSNull *> *)removeObjectForKey:(NSString *)key
  95. accessGroup:(nullable NSString *)accessGroup {
  96. return [FBLPromise onQueue:self.inMemoryCacheQueue
  97. do:^id _Nullable {
  98. [self.inMemoryCache removeObjectForKey:key];
  99. return nil;
  100. }]
  101. .thenOn(self.keychainQueue, ^id(id result) {
  102. NSDictionary *query = [self keychainQueryWithKey:key accessGroup:accessGroup];
  103. NSError *error;
  104. if (![GULKeychainUtils removeItemWithQuery:query error:&error]) {
  105. return error;
  106. }
  107. return [NSNull null];
  108. });
  109. }
  110. #pragma mark - Private
  111. - (FBLPromise<id<NSSecureCoding>> *)getObjectFromKeychainForKey:(NSString *)key
  112. objectClass:(Class)objectClass
  113. accessGroup:(nullable NSString *)accessGroup {
  114. // Look for the object in the keychain.
  115. return [FBLPromise
  116. onQueue:self.keychainQueue
  117. do:^id {
  118. NSDictionary *query = [self keychainQueryWithKey:key accessGroup:accessGroup];
  119. NSError *error;
  120. NSData *encodedObject = [GULKeychainUtils getItemWithQuery:query error:&error];
  121. if (error) {
  122. return error;
  123. }
  124. if (!encodedObject) {
  125. return nil;
  126. }
  127. id object = [GULSecureCoding unarchivedObjectOfClass:objectClass
  128. fromData:encodedObject
  129. error:&error];
  130. if (error) {
  131. return error;
  132. }
  133. return object;
  134. }]
  135. .thenOn(self.inMemoryCacheQueue,
  136. ^id<NSSecureCoding> _Nullable(id<NSSecureCoding> _Nullable object) {
  137. // Save object to the in-memory cache if exists and return the object.
  138. if (object) {
  139. [self.inMemoryCache setObject:object forKey:[key copy]];
  140. }
  141. return object;
  142. });
  143. }
  144. - (void)resetInMemoryCache {
  145. [self.inMemoryCache removeAllObjects];
  146. }
  147. #pragma mark - Keychain
  148. - (NSMutableDictionary<NSString *, id> *)keychainQueryWithKey:(NSString *)key
  149. accessGroup:(nullable NSString *)accessGroup {
  150. NSMutableDictionary<NSString *, id> *query = [NSMutableDictionary dictionary];
  151. query[(__bridge NSString *)kSecClass] = (__bridge NSString *)kSecClassGenericPassword;
  152. query[(__bridge NSString *)kSecAttrService] = self.service;
  153. query[(__bridge NSString *)kSecAttrAccount] = key;
  154. if (accessGroup) {
  155. query[(__bridge NSString *)kSecAttrAccessGroup] = accessGroup;
  156. }
  157. #if TARGET_OS_OSX
  158. if (self.keychainRef) {
  159. query[(__bridge NSString *)kSecUseKeychain] = (__bridge id)(self.keychainRef);
  160. query[(__bridge NSString *)kSecMatchSearchList] = @[ (__bridge id)(self.keychainRef) ];
  161. }
  162. #endif // TARGET_OSX
  163. return query;
  164. }
  165. @end