FIRInstanceIDAuthKeyChainTest.m 20 KB

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