FIRInstanceIDAuthKeyChainTest.m 20 KB

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