FIRInstanceIDAuthKeyChainTest.m 20 KB

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