FIRInstanceIDAuthKeyChainTest.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. accessibility:NULL
  69. account:account1
  70. handler:^(NSError *error) {
  71. XCTAssertNil(error);
  72. // Create another keychain with the same service but different account.
  73. NSString *account2 = kBundleID2;
  74. NSData *tokenInfoData2 = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  75. scope:kScope
  76. token:kToken2];
  77. [weakKeychain
  78. setData:tokenInfoData2
  79. forService:service
  80. accessibility:NULL
  81. account:account2
  82. handler:^(NSError *error) {
  83. XCTAssertNil(error);
  84. // Now query the token and compare, they should not corrupt
  85. // each other.
  86. NSData *data1 = [weakKeychain dataForService:service account:account1];
  87. #pragma clang diagnostic push
  88. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  89. FIRInstanceIDTokenInfo *tokenInfo1 =
  90. [NSKeyedUnarchiver unarchiveObjectWithData:data1];
  91. XCTAssertEqualObjects(kToken1, tokenInfo1.token);
  92. NSData *data2 = [weakKeychain dataForService:service account:account2];
  93. FIRInstanceIDTokenInfo *tokenInfo2 =
  94. [NSKeyedUnarchiver unarchiveObjectWithData:data2];
  95. #pragma clang diagnostic pop
  96. XCTAssertEqualObjects(kToken2, tokenInfo2.token);
  97. // Also check the cache data.
  98. XCTAssertEqual(weakKeychain.cachedKeychainData.count, 1);
  99. XCTAssertEqual(weakKeychain.cachedKeychainData[service].count, 2);
  100. XCTAssertEqualObjects(
  101. weakKeychain.cachedKeychainData[service][account1].firstObject,
  102. tokenInfoData1);
  103. XCTAssertEqualObjects(
  104. weakKeychain.cachedKeychainData[service][account2].firstObject,
  105. tokenInfoData2);
  106. // Check wildcard query
  107. NSArray *results = [weakKeychain itemsMatchingService:service
  108. 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 setData:tokenData
  136. forService:service1
  137. accessibility:NULL
  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. accessibility:NULL
  152. account:account
  153. handler:^(NSError *error) {
  154. XCTAssertNil(error);
  155. // Now query the token and compare, they should not corrupt
  156. // each other.
  157. NSData *data1 = [weakKeychain dataForService:service1 account:account];
  158. #pragma clang diagnostic push
  159. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  160. FIRInstanceIDTokenInfo *tokenInfo1 =
  161. [NSKeyedUnarchiver unarchiveObjectWithData:data1];
  162. #pragma clang diagnostic pop
  163. XCTAssertEqualObjects(kToken1, tokenInfo1.token);
  164. NSData *data2 = [weakKeychain dataForService:service2 account:account];
  165. NSString *checkinKeychainContent =
  166. [[NSString alloc] initWithData:data2 encoding:NSUTF8StringEncoding];
  167. FIRInstanceIDCheckinPreferences *checkinPreferences =
  168. [FIRInstanceIDCheckinPreferences
  169. preferencesFromKeychainContents:checkinKeychainContent];
  170. XCTAssertEqualObjects(checkinPreferences.secretToken, kSecret);
  171. XCTAssertEqualObjects(checkinPreferences.deviceID, kAuthID);
  172. NSArray *results = [weakKeychain itemsMatchingService:@"*"
  173. account:account];
  174. XCTAssertEqual(results.count, 2);
  175. // Also check the cache data.
  176. XCTAssertEqual(weakKeychain.cachedKeychainData.count, 2);
  177. XCTAssertEqualObjects(
  178. weakKeychain.cachedKeychainData[service1][account].firstObject,
  179. tokenData);
  180. XCTAssertEqualObjects(
  181. weakKeychain.cachedKeychainData[service2][account].firstObject,
  182. checkinData);
  183. // Clean up keychain at the end
  184. [weakKeychain removeItemsMatchingService:@"*"
  185. account:@"*"
  186. handler:^(NSError *_Nonnull error) {
  187. XCTAssertNil(error);
  188. [noCurruptionExpectation fulfill];
  189. }];
  190. }];
  191. }];
  192. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  193. #endif
  194. }
  195. - (void)testQueryCachedKeychainItems {
  196. XCTestExpectation *addItemToKeychainExpectation =
  197. [self expectationWithDescription:@"Test added item should be cached properly"];
  198. // A wildcard query should return empty data when there's nothing in keychain
  199. FIRInstanceIDAuthKeychain *keychain =
  200. [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
  201. id keychainMock = OCMPartialMock(keychain);
  202. NSArray *result = [keychain itemsMatchingService:@"*" account:@"*"];
  203. XCTAssertEqual(result.count, 0);
  204. // Create a keychain item
  205. NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  206. NSString *account = kBundleID1;
  207. NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  208. scope:kScope
  209. token:kToken1];
  210. __weak FIRInstanceIDAuthKeychain *weakKeychain = keychain;
  211. __weak id weakKeychainMock = keychainMock;
  212. [keychain setData:tokenData
  213. forService:service
  214. accessibility:NULL
  215. account:account
  216. handler:^(NSError *error) {
  217. XCTAssertNil(error);
  218. // Now if we clean the cache
  219. [weakKeychain.cachedKeychainData removeAllObjects];
  220. // Then query the item should fetch from keychain.
  221. NSData *data = [weakKeychain dataForService:service account:account];
  222. XCTAssertEqualObjects(data, tokenData);
  223. // Verify we fetch from keychain by calling to get the query
  224. OCMVerify([weakKeychainMock keychainQueryForService:service account:account]);
  225. // Cache should now have the query item
  226. XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
  227. tokenData);
  228. // Wildcard query should simply return the results without cache it
  229. data = [weakKeychain dataForService:@"*" account:account];
  230. XCTAssertEqualObjects(data, tokenData);
  231. // Cache should not have wildcard query entry
  232. XCTAssertNil(weakKeychain.cachedKeychainData[@"*"]);
  233. // Assume keychain has empty service entry
  234. [weakKeychain.cachedKeychainData setObject:[@{} mutableCopy] forKey:service];
  235. // Query the item
  236. data = [weakKeychain dataForService:service account:account];
  237. XCTAssertEqualObjects(data, tokenData);
  238. // Cache should have the query item.
  239. XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
  240. tokenData);
  241. // Clean up keychain at the end
  242. [weakKeychain removeItemsMatchingService:@"*"
  243. account:@"*"
  244. handler:^(NSError *_Nonnull error) {
  245. XCTAssertNil(error);
  246. [addItemToKeychainExpectation fulfill];
  247. }];
  248. }];
  249. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  250. }
  251. - (void)testCachedKeychainOverwrite {
  252. XCTestExpectation *overwriteCachedKeychainExpectation =
  253. [self expectationWithDescription:@"Test the cached keychain item is overwrite properly"];
  254. FIRInstanceIDAuthKeychain *keychain =
  255. [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
  256. // Set the cache a different data under the same service but different account
  257. NSData *data = [[NSData alloc] init];
  258. NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  259. [keychain.cachedKeychainData setObject:[@{kBundleID2 : data} mutableCopy] forKey:service];
  260. // Create a keychain item
  261. NSString *account = kBundleID1;
  262. NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  263. scope:kScope
  264. token:kToken1];
  265. __weak FIRInstanceIDAuthKeychain *weakKeychain = keychain;
  266. [keychain setData:tokenData
  267. forService:service
  268. accessibility:NULL
  269. account:account
  270. handler:^(NSError *error) {
  271. XCTAssertNil(error);
  272. // Query the item should fetch from keychain because no entry under the same
  273. // service and account.
  274. NSData *data = [weakKeychain dataForService:service account:account];
  275. XCTAssertEqualObjects(data, tokenData);
  276. // Cache should now have the query item
  277. XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
  278. tokenData);
  279. // Clean up keychain at the end
  280. [weakKeychain removeItemsMatchingService:@"*"
  281. account:@"*"
  282. handler:^(NSError *_Nonnull error) {
  283. XCTAssertNil(error);
  284. [overwriteCachedKeychainExpectation fulfill];
  285. }];
  286. }];
  287. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  288. }
  289. - (void)testSetKeychainItemShouldDeleteOldEntry {
  290. XCTestExpectation *overwriteCachedKeychainExpectation = [self
  291. expectationWithDescription:@"Test keychain entry should be deleted before adding a new one"];
  292. FIRInstanceIDAuthKeychain *keychain =
  293. [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
  294. // Assume keychain had a old entry under the same service and account.
  295. // Now if we set the cache a different data under the same service
  296. NSData *oldData = [[NSData alloc] init];
  297. NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  298. NSString *account = kBundleID1;
  299. [keychain.cachedKeychainData setObject:[@{account : oldData} mutableCopy] forKey:service];
  300. // add a new keychain item
  301. NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  302. scope:kScope
  303. token:kToken1];
  304. __weak FIRInstanceIDAuthKeychain *weakKeychain = keychain;
  305. [keychain setData:tokenData
  306. forService:service
  307. accessibility:NULL
  308. account:account
  309. handler:^(NSError *error) {
  310. XCTAssertNil(error);
  311. // Cache should now have the updated item
  312. XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
  313. tokenData);
  314. // Clean up keychain at the end
  315. [weakKeychain removeItemsMatchingService:@"*"
  316. account:@"*"
  317. handler:^(NSError *_Nonnull error) {
  318. XCTAssertNil(error);
  319. [overwriteCachedKeychainExpectation fulfill];
  320. }];
  321. }];
  322. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  323. }
  324. - (void)testInvalidQuery {
  325. XCTestExpectation *invalidKeychainQueryExpectation =
  326. [self expectationWithDescription:@"Test invalid keychain query"];
  327. FIRInstanceIDAuthKeychain *keychain =
  328. [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
  329. NSData *data = [[NSData alloc] init];
  330. [keychain setData:data
  331. forService:@"*"
  332. accessibility:NULL
  333. account:@"*"
  334. handler:^(NSError *error) {
  335. XCTAssertNotNil(error);
  336. [invalidKeychainQueryExpectation fulfill];
  337. }];
  338. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  339. }
  340. - (void)testQueryAndAddEntry {
  341. FIRInstanceIDAuthKeychain *keychain =
  342. [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
  343. // Set the cache a different data under the same service but different account
  344. NSData *data = [[NSData alloc] init];
  345. NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  346. NSString *account1 = kBundleID1;
  347. [keychain.cachedKeychainData setObject:[@{account1 : data} mutableCopy] forKey:service];
  348. // Now account2 doesn't exist in cache
  349. NSString *account2 = kBundleID2;
  350. XCTAssertNil(keychain.cachedKeychainData[service][account2]);
  351. // Query account2
  352. XCTAssertNil([keychain dataForService:service account:account2]);
  353. // Service and account2 should exist in cache.
  354. XCTAssertNotNil(keychain.cachedKeychainData[service][account2]);
  355. }
  356. #pragma mark - helper function
  357. - (NSData *)tokenDataWithAuthorizedEntity:(NSString *)authorizedEntity
  358. scope:(NSString *)scope
  359. token:(NSString *)token {
  360. FIRInstanceIDTokenInfo *tokenInfo =
  361. [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:authorizedEntity
  362. scope:scope
  363. token:token
  364. appVersion:@"1.0"
  365. firebaseAppID:kFirebaseAppID];
  366. #pragma clang diagnostic push
  367. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  368. return [NSKeyedArchiver archivedDataWithRootObject:tokenInfo];
  369. #pragma clang diagnostic pop
  370. }
  371. @end