FIRInstanceIDAuthKeyChainTest.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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 <OCMock/OCMock.h>
  18. #import "Firebase/InstanceID/FIRInstanceIDAuthKeyChain.h"
  19. #import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.h"
  20. #import "Firebase/InstanceID/FIRInstanceIDTokenInfo.h"
  21. static NSString *const kFIRInstanceIDTestKeychainId = @"com.google.iid-tests";
  22. static NSString *const kFakeCheckinPlistName = @"com.google.test.IIDStoreTestCheckin";
  23. static NSString *const kApplicationSupportSubDirectoryName = @"FirebaseInstanceIDCheckinTest";
  24. static NSString *const kAuthorizedEntity = @"test-audience";
  25. static NSString *const kScope = @"test-scope";
  26. static NSString *const kAuthID = @"test-auth-id";
  27. static NSString *const kSecret = @"test-secret";
  28. static NSString *const kToken1 =
  29. @"dOr37DpYQ9M:APA91bE5aQ2expDEmoSNDDrZqS6drAz2V-GHJHEsa-qVdlHXVSlWpUsK-Ta6Oe1QsVSLovL7_"
  30. @"rbm8GNnP7XPfwjtDQrjxYS1BdtxHdVVnQKuxlF3Z0QOwL380l1e1Fz91PX5b77XKj0FIyqzX1z0uJc0-pM6YcaPGg";
  31. static NSString *const kToken2 = @"c8oEXUYIl3s:APA91bHtJMs_dZ2lXYXIcwsC47abYIuWhEJ_CshY2PJRjVuI_"
  32. @"H659iYUwfmNNghnZVkCmeUdKDSrK8xqVb0PVHxyAW391Ynp2NchMB87kJWb3BS0z"
  33. @"ud6Ej_xDES_oc353eFRvt0E6NXefDmrUCpBY8y89_1eVFFfiA";
  34. static NSString *const kFirebaseAppID = @"abcdefg:ios:QrjxYS1BdtxHdVVnQKuxlF3Z0QO";
  35. static NSString *const kBundleID1 = @"com.google.fcm.dev";
  36. static NSString *const kBundleID2 = @"com.google.abtesting.dev";
  37. @interface FIRInstanceIDAuthKeychain (ExposedForTest)
  38. @property(nonatomic, copy)
  39. NSMutableDictionary<NSString *, NSMutableDictionary<NSString *, NSArray<NSData *> *> *>
  40. *cachedKeychainData;
  41. - (NSMutableDictionary *)keychainQueryForService:(NSString *)service account:(NSString *)account;
  42. @end
  43. @interface FIRInstanceIDAuthKeyChainTest : XCTestCase
  44. @end
  45. @implementation FIRInstanceIDAuthKeyChainTest
  46. - (void)setUp {
  47. [super setUp];
  48. }
  49. - (void)tearDown {
  50. [super tearDown];
  51. }
  52. - (void)testKeyChainNoCorruptionWithUniqueAccount {
  53. XCTestExpectation *noCurruptionExpectation =
  54. [self expectationWithDescription:@"No corruption between different accounts."];
  55. // Create a keychain with a service and a unique account
  56. NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  57. NSString *account1 = kBundleID1;
  58. NSData *tokenInfoData1 = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  59. scope:kScope
  60. token:kToken1];
  61. FIRInstanceIDAuthKeychain *keychain =
  62. [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
  63. __weak FIRInstanceIDAuthKeychain *weakKeychain = keychain;
  64. [keychain setData:tokenInfoData1
  65. forService:service
  66. accessibility:NULL
  67. account:account1
  68. handler:^(NSError *error) {
  69. XCTAssertNil(error);
  70. // Create another keychain with the same service but different account.
  71. NSString *account2 = kBundleID2;
  72. NSData *tokenInfoData2 = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  73. scope:kScope
  74. token:kToken2];
  75. [weakKeychain
  76. setData:tokenInfoData2
  77. forService:service
  78. accessibility:NULL
  79. account:account2
  80. handler:^(NSError *error) {
  81. XCTAssertNil(error);
  82. // Now query the token and compare, they should not corrupt
  83. // each other.
  84. NSData *data1 = [weakKeychain dataForService:service account:account1];
  85. FIRInstanceIDTokenInfo *tokenInfo1 =
  86. [NSKeyedUnarchiver unarchiveObjectWithData:data1];
  87. XCTAssertEqualObjects(kToken1, tokenInfo1.token);
  88. NSData *data2 = [weakKeychain dataForService:service account:account2];
  89. FIRInstanceIDTokenInfo *tokenInfo2 =
  90. [NSKeyedUnarchiver unarchiveObjectWithData:data2];
  91. XCTAssertEqualObjects(kToken2, tokenInfo2.token);
  92. // Also check the cache data.
  93. XCTAssertEqual(weakKeychain.cachedKeychainData.count, 1);
  94. XCTAssertEqual(weakKeychain.cachedKeychainData[service].count, 2);
  95. XCTAssertEqualObjects(
  96. weakKeychain.cachedKeychainData[service][account1].firstObject,
  97. tokenInfoData1);
  98. XCTAssertEqualObjects(
  99. weakKeychain.cachedKeychainData[service][account2].firstObject,
  100. tokenInfoData2);
  101. // Check wildcard query
  102. NSArray *results = [weakKeychain itemsMatchingService:service
  103. account:@"*"];
  104. XCTAssertEqual(results.count, 2);
  105. // Clean up keychain at the end
  106. [weakKeychain removeItemsMatchingService:service
  107. account:@"*"
  108. handler:^(NSError *_Nonnull error) {
  109. XCTAssertNil(error);
  110. [noCurruptionExpectation fulfill];
  111. }];
  112. }];
  113. }];
  114. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  115. }
  116. - (void)testKeyChainNoCorruptionWithUniqueService {
  117. XCTestExpectation *noCurruptionExpectation =
  118. [self expectationWithDescription:@"No corruption between different services."];
  119. // Create a keychain with a service and a unique account
  120. NSString *service1 = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  121. NSString *account = kBundleID1;
  122. NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  123. scope:kScope
  124. token:kToken1];
  125. FIRInstanceIDAuthKeychain *keychain =
  126. [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
  127. __weak FIRInstanceIDAuthKeychain *weakKeychain = keychain;
  128. [keychain setData:tokenData
  129. forService:service1
  130. accessibility:NULL
  131. account:account
  132. handler:^(NSError *error) {
  133. XCTAssertNil(error);
  134. // Store a checkin info using the same keychain account, but different service.
  135. NSString *service2 = @"com.google.iid.checkin";
  136. FIRInstanceIDCheckinPreferences *preferences =
  137. [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kAuthID
  138. secretToken:kSecret];
  139. NSString *checkinKeychainContent = [preferences checkinKeychainContent];
  140. NSData *checkinData = [checkinKeychainContent dataUsingEncoding:NSUTF8StringEncoding];
  141. [weakKeychain
  142. setData:checkinData
  143. forService:service2
  144. accessibility:NULL
  145. account:account
  146. handler:^(NSError *error) {
  147. XCTAssertNil(error);
  148. // Now query the token and compare, they should not corrupt
  149. // each other.
  150. NSData *data1 = [weakKeychain dataForService:service1 account:account];
  151. FIRInstanceIDTokenInfo *tokenInfo1 =
  152. [NSKeyedUnarchiver unarchiveObjectWithData:data1];
  153. XCTAssertEqualObjects(kToken1, tokenInfo1.token);
  154. NSData *data2 = [weakKeychain dataForService:service2 account:account];
  155. NSString *checkinKeychainContent =
  156. [[NSString alloc] initWithData:data2 encoding:NSUTF8StringEncoding];
  157. FIRInstanceIDCheckinPreferences *checkinPreferences =
  158. [FIRInstanceIDCheckinPreferences
  159. preferencesFromKeychainContents:checkinKeychainContent];
  160. XCTAssertEqualObjects(checkinPreferences.secretToken, kSecret);
  161. XCTAssertEqualObjects(checkinPreferences.deviceID, kAuthID);
  162. NSArray *results = [weakKeychain itemsMatchingService:@"*"
  163. account:account];
  164. XCTAssertEqual(results.count, 2);
  165. // Also check the cache data.
  166. XCTAssertEqual(weakKeychain.cachedKeychainData.count, 2);
  167. XCTAssertEqualObjects(
  168. weakKeychain.cachedKeychainData[service1][account].firstObject,
  169. tokenData);
  170. XCTAssertEqualObjects(
  171. weakKeychain.cachedKeychainData[service2][account].firstObject,
  172. checkinData);
  173. // Clean up keychain at the end
  174. [weakKeychain removeItemsMatchingService:@"*"
  175. account:@"*"
  176. handler:^(NSError *_Nonnull error) {
  177. XCTAssertNil(error);
  178. [noCurruptionExpectation fulfill];
  179. }];
  180. }];
  181. }];
  182. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  183. }
  184. - (void)testQueryCachedKeychainItems {
  185. XCTestExpectation *addItemToKeychainExpectation =
  186. [self expectationWithDescription:@"Test added item should be cached properly"];
  187. // A wildcard query should return empty data when there's nothing in keychain
  188. FIRInstanceIDAuthKeychain *keychain =
  189. [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
  190. id keychainMock = OCMPartialMock(keychain);
  191. NSArray *result = [keychain itemsMatchingService:@"*" account:@"*"];
  192. XCTAssertEqual(result.count, 0);
  193. // Create a keychain item
  194. NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  195. NSString *account = kBundleID1;
  196. NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  197. scope:kScope
  198. token:kToken1];
  199. __weak FIRInstanceIDAuthKeychain *weakKeychain = keychain;
  200. __weak id weakKeychainMock = keychainMock;
  201. [keychain setData:tokenData
  202. forService:service
  203. accessibility:NULL
  204. account:account
  205. handler:^(NSError *error) {
  206. XCTAssertNil(error);
  207. // Now if we clean the cache
  208. [weakKeychain.cachedKeychainData removeAllObjects];
  209. // Then query the item should fetch from keychain.
  210. NSData *data = [weakKeychain dataForService:service account:account];
  211. XCTAssertEqualObjects(data, tokenData);
  212. // Verify we fetch from keychain by calling to get the query
  213. OCMVerify([weakKeychainMock keychainQueryForService:service account:account]);
  214. // Cache should now have the query item
  215. XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
  216. tokenData);
  217. // Wildcard query should simply return the results without cache it
  218. data = [weakKeychain dataForService:@"*" account:account];
  219. XCTAssertEqualObjects(data, tokenData);
  220. // Cache should not have wildcard query entry
  221. XCTAssertNil(weakKeychain.cachedKeychainData[@"*"]);
  222. // Assume keychain has empty service entry
  223. [weakKeychain.cachedKeychainData setObject:[@{} mutableCopy] forKey:service];
  224. // Query the item
  225. data = [weakKeychain dataForService:service account:account];
  226. XCTAssertEqualObjects(data, tokenData);
  227. // Cache should have the query item.
  228. XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
  229. tokenData);
  230. // Clean up keychain at the end
  231. [weakKeychain removeItemsMatchingService:@"*"
  232. account:@"*"
  233. handler:^(NSError *_Nonnull error) {
  234. XCTAssertNil(error);
  235. [addItemToKeychainExpectation fulfill];
  236. }];
  237. }];
  238. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  239. }
  240. - (void)testCachedKeychainOverwrite {
  241. XCTestExpectation *overwriteCachedKeychainExpectation =
  242. [self expectationWithDescription:@"Test the cached keychain item is overwrite properly"];
  243. FIRInstanceIDAuthKeychain *keychain =
  244. [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
  245. // Set the cache a different data under the same service but different account
  246. NSData *data = [[NSData alloc] init];
  247. NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  248. [keychain.cachedKeychainData setObject:[@{kBundleID2 : data} mutableCopy] forKey:service];
  249. // Create a keychain item
  250. NSString *account = kBundleID1;
  251. NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  252. scope:kScope
  253. token:kToken1];
  254. __weak FIRInstanceIDAuthKeychain *weakKeychain = keychain;
  255. [keychain setData:tokenData
  256. forService:service
  257. accessibility:NULL
  258. account:account
  259. handler:^(NSError *error) {
  260. XCTAssertNil(error);
  261. // Query the item should fetch from keychain because no entry under the same
  262. // service and account.
  263. NSData *data = [weakKeychain dataForService:service account:account];
  264. XCTAssertEqualObjects(data, tokenData);
  265. // Cache should now have the query item
  266. XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
  267. tokenData);
  268. // Clean up keychain at the end
  269. [weakKeychain removeItemsMatchingService:@"*"
  270. account:@"*"
  271. handler:^(NSError *_Nonnull error) {
  272. XCTAssertNil(error);
  273. [overwriteCachedKeychainExpectation fulfill];
  274. }];
  275. }];
  276. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  277. }
  278. - (void)testSetKeychainItemShouldDeleteOldEntry {
  279. XCTestExpectation *overwriteCachedKeychainExpectation = [self
  280. expectationWithDescription:@"Test keychain entry should be deleted before adding a new one"];
  281. FIRInstanceIDAuthKeychain *keychain =
  282. [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
  283. // Assume keychain had a old entry under the same service and account.
  284. // Now if we set the cache a different data under the same service
  285. NSData *oldData = [[NSData alloc] init];
  286. NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  287. NSString *account = kBundleID1;
  288. [keychain.cachedKeychainData setObject:[@{account : oldData} mutableCopy] forKey:service];
  289. // add a new keychain item
  290. NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  291. scope:kScope
  292. token:kToken1];
  293. __weak FIRInstanceIDAuthKeychain *weakKeychain = keychain;
  294. [keychain setData:tokenData
  295. forService:service
  296. accessibility:NULL
  297. account:account
  298. handler:^(NSError *error) {
  299. XCTAssertNil(error);
  300. // Cache should now have the updated item
  301. XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
  302. tokenData);
  303. // Clean up keychain at the end
  304. [weakKeychain removeItemsMatchingService:@"*"
  305. account:@"*"
  306. handler:^(NSError *_Nonnull error) {
  307. XCTAssertNil(error);
  308. [overwriteCachedKeychainExpectation fulfill];
  309. }];
  310. }];
  311. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  312. }
  313. - (void)testInvalidQuery {
  314. XCTestExpectation *invalidKeychainQueryExpectation =
  315. [self expectationWithDescription:@"Test invalid keychain query"];
  316. FIRInstanceIDAuthKeychain *keychain =
  317. [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
  318. NSData *data = [[NSData alloc] init];
  319. [keychain setData:data
  320. forService:@"*"
  321. accessibility:NULL
  322. account:@"*"
  323. handler:^(NSError *error) {
  324. XCTAssertNotNil(error);
  325. [invalidKeychainQueryExpectation fulfill];
  326. }];
  327. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  328. }
  329. - (void)testQueryAndAddEntry {
  330. FIRInstanceIDAuthKeychain *keychain =
  331. [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
  332. // Set the cache a different data under the same service but different account
  333. NSData *data = [[NSData alloc] init];
  334. NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  335. NSString *account1 = kBundleID1;
  336. [keychain.cachedKeychainData setObject:[@{account1 : data} mutableCopy] forKey:service];
  337. // Now account2 doesn't exist in cache
  338. NSString *account2 = kBundleID2;
  339. XCTAssertNil(keychain.cachedKeychainData[service][account2]);
  340. // Query account2
  341. XCTAssertNil([keychain dataForService:service account:account2]);
  342. // Service and account2 should exist in cache.
  343. XCTAssertNotNil(keychain.cachedKeychainData[service][account2]);
  344. }
  345. #pragma mark - helper function
  346. - (NSData *)tokenDataWithAuthorizedEntity:(NSString *)authorizedEntity
  347. scope:(NSString *)scope
  348. token:(NSString *)token {
  349. FIRInstanceIDTokenInfo *tokenInfo =
  350. [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:authorizedEntity
  351. scope:scope
  352. token:token
  353. appVersion:@"1.0"
  354. firebaseAppID:kFirebaseAppID];
  355. return [NSKeyedArchiver archivedDataWithRootObject:tokenInfo];
  356. }
  357. @end