FIRInstanceIDKeyPairStoreTest.m 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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 <XCTest/XCTest.h>
  17. #import "Firebase/InstanceID/FIRInstanceIDBackupExcludedPlist.h"
  18. #import "Firebase/InstanceID/FIRInstanceIDConstants.h"
  19. #import "Firebase/InstanceID/FIRInstanceIDKeyPair.h"
  20. #import "Firebase/InstanceID/FIRInstanceIDKeychain.h"
  21. #import "Firebase/InstanceID/FIRInstanceIDStore.h"
  22. #import <OCMock/OCMock.h>
  23. #import "Firebase/InstanceID/FIRInstanceIDKeyPair.h"
  24. #import "Firebase/InstanceID/FIRInstanceIDKeyPairStore.h"
  25. #import "Firebase/InstanceID/FIRInstanceIDKeyPairUtilities.h"
  26. #import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
  27. @interface FIRInstanceIDKeyPairStore (ExposedForTest)
  28. @property(nonatomic, readwrite, strong) FIRInstanceIDBackupExcludedPlist *plist;
  29. @property(nonatomic, readwrite, strong) FIRInstanceIDKeyPair *keyPair;
  30. + (NSString *)appIDKeyWithSubtype:(NSString *)subtype;
  31. + (NSString *)creationTimeKeyWithSubtype:(NSString *)subtype;
  32. - (FIRInstanceIDKeyPair *)generateAndSaveKeyWithSubtype:(NSString *)subtype
  33. creationTime:(int64_t)creationTime
  34. error:(NSError **)error;
  35. - (FIRInstanceIDKeyPair *)validCachedKeyPairWithSubtype:(NSString *)subtype error:(NSError **)error;
  36. + (NSString *)keyStoreFileName;
  37. - (void)migrateKeyPairCacheIfNeededWithHandler:(void (^)(NSError *error))handler;
  38. @end
  39. @interface FIRInstanceIDKeyPairStoreTest : XCTestCase
  40. @property(nonatomic, readwrite, strong) FIRInstanceIDKeyPairStore *keyPairStore;
  41. @end
  42. @implementation FIRInstanceIDKeyPairStoreTest
  43. - (void)setUp {
  44. [super setUp];
  45. id mockStoreClass = OCMClassMock([FIRInstanceIDKeyPairStore class]);
  46. [[[mockStoreClass stub] andReturn:@"com.google.iid-keypairmanager-test"] keyStoreFileName];
  47. // Should make sure the standard directory is created.
  48. if (![FIRInstanceIDStore hasSubDirectory:kFIRInstanceIDSubDirectoryName]) {
  49. [FIRInstanceIDStore createSubDirectory:kFIRInstanceIDSubDirectoryName];
  50. }
  51. _keyPairStore = [[FIRInstanceIDKeyPairStore alloc] init];
  52. }
  53. - (void)tearDown {
  54. NSError *error = nil;
  55. [self.keyPairStore removeKeyPairCreationTimePlistWithError:&error];
  56. XCTestExpectation *queueDrained = [self expectationWithDescription:@"drainKeychainQueue"];
  57. [self.keyPairStore deleteSavedKeyPairWithSubtype:kFIRInstanceIDKeyPairSubType
  58. handler:^(NSError *error) {
  59. [queueDrained fulfill];
  60. }];
  61. [self waitForExpectations:@[ queueDrained ] timeout:10];
  62. [super tearDown];
  63. }
  64. /**
  65. * The app identity generated should be 11 chars and start with k, l, m, n. It should
  66. * not have "=" as suffix since we do not allow wrapping.
  67. */
  68. - (void)testIdentity {
  69. NSError *error;
  70. FIRInstanceIDKeyPair *keyPair = [self.keyPairStore loadKeyPairWithError:&error];
  71. NSString *iid = FIRInstanceIDAppIdentity(keyPair);
  72. XCTAssertEqual(11, iid.length);
  73. XCTAssertFalse([iid hasSuffix:@"="]);
  74. }
  75. /**
  76. * All identities should be cleared if the associated keypair plist file is missing.
  77. * This indicates that the app is either a fresh install, or was removed and reinstalled.
  78. *
  79. * If/when iOS changes the behavior of the Keychain to also invalidate items when an app is
  80. * installed, this check will no longer be required (both the plist file and the keychain items
  81. * would be missing).
  82. */
  83. - (void)testIdentityIsInvalidatedWithMissingPlist {
  84. // Mock that the plist doesn't exist, and call the invalidation check. It should
  85. // trigger the identities to be deleted.
  86. id plistMock = OCMPartialMock(self.keyPairStore.plist);
  87. [[[plistMock stub] andReturnValue:[NSNumber numberWithBool:NO]] doesFileExist];
  88. // Mock the keypair store, to check if key pair deletes are requested
  89. id storeMock = OCMPartialMock(self.keyPairStore);
  90. // Now trigger a possible invalidation.
  91. [self.keyPairStore invalidateKeyPairsIfNeeded];
  92. // Verify that delete was called
  93. OCMVerify([storeMock deleteSavedKeyPairWithSubtype:[OCMArg any] handler:[OCMArg any]]);
  94. }
  95. - (void)testMigrationWhenPlistExist {
  96. // Mock that the plist doesn't exist, and call the invalidation check. It should
  97. // trigger the identities to be deleted.
  98. id plistMock = OCMPartialMock(self.keyPairStore.plist);
  99. [[[plistMock stub] andReturnValue:[NSNumber numberWithBool:YES]] doesFileExist];
  100. // Mock the keypair store, to check if key pair deletes are requested
  101. id storeMock = OCMPartialMock(self.keyPairStore);
  102. // Now trigger a possible invalidation.
  103. [self.keyPairStore invalidateKeyPairsIfNeeded];
  104. // Verify that delete was called
  105. OCMVerify([storeMock migrateKeyPairCacheIfNeededWithHandler:nil]);
  106. }
  107. /**
  108. * The app identity should change when deleted and regenerated.
  109. */
  110. - (void)testResetIdentity {
  111. XCTestExpectation *identityResetExpectation =
  112. [self expectationWithDescription:@"Identity should be reset"];
  113. NSError *error;
  114. FIRInstanceIDKeyPair *keyPair = [self.keyPairStore loadKeyPairWithError:&error];
  115. XCTAssertNil(error);
  116. NSString *iid1 = FIRInstanceIDAppIdentity(keyPair);
  117. [self.keyPairStore deleteSavedKeyPairWithSubtype:kFIRInstanceIDKeyPairSubType
  118. handler:^(NSError *error) {
  119. XCTAssertNil(error);
  120. [identityResetExpectation fulfill];
  121. }];
  122. [self waitForExpectationsWithTimeout:5 handler:nil];
  123. [self.keyPairStore removeKeyPairCreationTimePlistWithError:&error];
  124. XCTAssertNil(error);
  125. // regenerate instance-id
  126. FIRInstanceIDKeyPair *keyPair2 = [self.keyPairStore loadKeyPairWithError:&error];
  127. XCTAssertNil(error);
  128. NSString *iid2 = FIRInstanceIDAppIdentity(keyPair2);
  129. XCTAssertNotEqualObjects(iid1, iid2);
  130. }
  131. /**
  132. * We should always cache a valid keypair.
  133. */
  134. - (void)testCachedKeyPair {
  135. NSError *error;
  136. FIRInstanceIDKeyPair *keyPair = [self.keyPairStore loadKeyPairWithError:&error];
  137. XCTAssertNil(error);
  138. NSString *iid1 = FIRInstanceIDAppIdentity(keyPair);
  139. // sleep for some time
  140. [NSThread sleepForTimeInterval:2.0];
  141. keyPair = [self.keyPairStore loadKeyPairWithError:&error];
  142. XCTAssertNil(error);
  143. NSString *iid2 = FIRInstanceIDAppIdentity(keyPair);
  144. XCTAssertTrue([self.keyPairStore hasCachedKeyPairs]);
  145. XCTAssertEqualObjects(iid1, iid2);
  146. }
  147. - (void)testAppIdentity {
  148. NSError *error;
  149. NSString *iid1 = [self.keyPairStore appIdentityWithError:&error];
  150. // sleep for some time
  151. [NSThread sleepForTimeInterval:2.0];
  152. NSString *iid2 = [self.keyPairStore appIdentityWithError:&error];
  153. XCTAssertEqualObjects(iid1, iid2);
  154. }
  155. /**
  156. * Test KeyPair cache. After generating a new keyPair requesting it from the cache
  157. * should be successfull and return the same keyPair.
  158. */
  159. - (void)testKeyPairCache {
  160. // TODO: figure out why same query doesn't work for macOS.
  161. #if TARGET_OS_IOS || TARGET_OS_TV
  162. NSError *error;
  163. FIRInstanceIDKeyPair *keyPair1 =
  164. [self.keyPairStore generateAndSaveKeyWithSubtype:kFIRInstanceIDKeyPairSubType
  165. creationTime:FIRInstanceIDCurrentTimestampInSeconds()
  166. error:&error];
  167. XCTAssertNotNil(keyPair1);
  168. NSString *iid1 = FIRInstanceIDAppIdentity(keyPair1);
  169. [NSThread sleepForTimeInterval:2.0];
  170. FIRInstanceIDKeyPair *keyPair2 =
  171. [self.keyPairStore validCachedKeyPairWithSubtype:kFIRInstanceIDKeyPairSubType error:&error];
  172. XCTAssertNil(error);
  173. NSString *iid2 = FIRInstanceIDAppIdentity(keyPair2);
  174. XCTAssertEqualObjects(iid1, iid2);
  175. #endif
  176. }
  177. /**
  178. * Test that if the Keychain preferences does not store any KeyPair, trying to
  179. * load one from the cache should return nil.
  180. */
  181. - (void)testInvalidKeyPair {
  182. NSError *error;
  183. FIRInstanceIDKeyPair *keyPair =
  184. [self.keyPairStore validCachedKeyPairWithSubtype:kFIRInstanceIDKeyPairSubType error:&error];
  185. XCTAssertFalse([keyPair isValid]);
  186. }
  187. /**
  188. * Test deleting the keyPair from Keychain preferences.
  189. */
  190. - (void)testDeleteKeyPair {
  191. XCTestExpectation *deleteKeyPairExpectation =
  192. [self expectationWithDescription:@"Keypair should be deleted"];
  193. NSError *error;
  194. [self.keyPairStore generateAndSaveKeyWithSubtype:kFIRInstanceIDKeyPairSubType
  195. creationTime:FIRInstanceIDCurrentTimestampInSeconds()
  196. error:&error];
  197. XCTAssertNil(error);
  198. [self.keyPairStore
  199. deleteSavedKeyPairWithSubtype:kFIRInstanceIDKeyPairSubType
  200. handler:^(NSError *error) {
  201. XCTAssertNil(error);
  202. FIRInstanceIDKeyPair *keyPair2 = [self.keyPairStore
  203. validCachedKeyPairWithSubtype:kFIRInstanceIDKeyPairSubType
  204. error:&error];
  205. XCTAssertNotNil(error);
  206. XCTAssertNil(keyPair2);
  207. [deleteKeyPairExpectation fulfill];
  208. }];
  209. [self waitForExpectationsWithTimeout:1 handler:nil];
  210. }
  211. @end