FIRInstanceIDAuthKeyChainTest.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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 kAuthID = @"test-auth-id";
  25. static NSString *const kSecret = @"test-secret";
  26. static NSString *const kToken1 =
  27. @"dOr37DpYQ9M:APA91bE5aQ2expDEmoSNDDrZqS6drAz2V-GHJHEsa-qVdlHXVSlWpUsK-Ta6Oe1QsVSLovL7_"
  28. @"rbm8GNnP7XPfwjtDQrjxYS1BdtxHdVVnQKuxlF3Z0QOwL380l1e1Fz91PX5b77XKj0FIyqzX1z0uJc0-pM6YcaPGg";
  29. static NSString *const kToken2 = @"c8oEXUYIl3s:APA91bHtJMs_dZ2lXYXIcwsC47abYIuWhEJ_CshY2PJRjVuI_"
  30. @"H659iYUwfmNNghnZVkCmeUdKDSrK8xqVb0PVHxyAW391Ynp2NchMB87kJWb3BS0z"
  31. @"ud6Ej_xDES_oc353eFRvt0E6NXefDmrUCpBY8y89_1eVFFfiA";
  32. static NSString *const kFirebaseAppID = @"abcdefg:ios:QrjxYS1BdtxHdVVnQKuxlF3Z0QO";
  33. static NSString *const kBundleID1 = @"com.google.fcm.dev";
  34. static NSString *const kBundleID2 = @"com.google.abtesting.dev";
  35. @interface FIRInstanceIDAuthKeychain (ExposedForTest)
  36. @property(nonatomic, copy)
  37. NSMutableDictionary<NSString *, NSMutableDictionary<NSString *, NSArray<NSData *> *> *>
  38. *cachedKeychainData;
  39. - (NSMutableDictionary *)keychainQueryForService:(NSString *)service account:(NSString *)account;
  40. @end
  41. @interface FIRInstanceIDAuthKeyChainTest : XCTestCase
  42. @end
  43. @implementation FIRInstanceIDAuthKeyChainTest
  44. - (void)setUp {
  45. [super setUp];
  46. }
  47. - (void)tearDown {
  48. [super tearDown];
  49. }
  50. - (void)testKeyChainNoCorruptionWithUniqueAccount {
  51. XCTestExpectation *noCurruptionExpectation =
  52. [self expectationWithDescription:@"No corruption between different accounts."];
  53. // Create a keychain with a service and a unique account
  54. NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  55. NSString *account1 = kBundleID1;
  56. NSData *tokenInfoData1 = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  57. scope:kScope
  58. token:kToken1];
  59. FIRInstanceIDAuthKeychain *keychain =
  60. [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
  61. __weak FIRInstanceIDAuthKeychain *weakKeychain = keychain;
  62. [keychain setData:tokenInfoData1
  63. forService:service
  64. accessibility:NULL
  65. account:account1
  66. handler:^(NSError *error) {
  67. XCTAssertNil(error);
  68. // Create another keychain with the same service but different account.
  69. NSString *account2 = kBundleID2;
  70. NSData *tokenInfoData2 = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  71. scope:kScope
  72. token:kToken2];
  73. [weakKeychain
  74. setData:tokenInfoData2
  75. forService:service
  76. accessibility:NULL
  77. account:account2
  78. handler:^(NSError *error) {
  79. XCTAssertNil(error);
  80. // Now query the token and compare, they should not corrupt
  81. // each other.
  82. NSData *data1 = [weakKeychain dataForService:service account:account1];
  83. #pragma clang diagnostic push
  84. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  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. #pragma clang diagnostic pop
  92. XCTAssertEqualObjects(kToken2, tokenInfo2.token);
  93. // Also check the cache data.
  94. XCTAssertEqual(weakKeychain.cachedKeychainData.count, 1);
  95. XCTAssertEqual(weakKeychain.cachedKeychainData[service].count, 2);
  96. XCTAssertEqualObjects(
  97. weakKeychain.cachedKeychainData[service][account1].firstObject,
  98. tokenInfoData1);
  99. XCTAssertEqualObjects(
  100. weakKeychain.cachedKeychainData[service][account2].firstObject,
  101. tokenInfoData2);
  102. // Check wildcard query
  103. NSArray *results = [weakKeychain itemsMatchingService:service
  104. account:@"*"];
  105. XCTAssertEqual(results.count, 2);
  106. // Clean up keychain at the end
  107. [weakKeychain removeItemsMatchingService:service
  108. account:@"*"
  109. handler:^(NSError *_Nonnull error) {
  110. XCTAssertNil(error);
  111. [noCurruptionExpectation fulfill];
  112. }];
  113. }];
  114. }];
  115. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  116. }
  117. - (void)testKeyChainNoCorruptionWithUniqueService {
  118. XCTestExpectation *noCurruptionExpectation =
  119. [self expectationWithDescription:@"No corruption between different services."];
  120. // Create a keychain with a service and a unique account
  121. NSString *service1 = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  122. NSString *account = kBundleID1;
  123. NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  124. scope:kScope
  125. token:kToken1];
  126. FIRInstanceIDAuthKeychain *keychain =
  127. [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
  128. __weak FIRInstanceIDAuthKeychain *weakKeychain = keychain;
  129. [keychain setData:tokenData
  130. forService:service1
  131. accessibility:NULL
  132. account:account
  133. handler:^(NSError *error) {
  134. XCTAssertNil(error);
  135. // Store a checkin info using the same keychain account, but different service.
  136. NSString *service2 = @"com.google.iid.checkin";
  137. FIRInstanceIDCheckinPreferences *preferences =
  138. [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kAuthID
  139. secretToken:kSecret];
  140. NSString *checkinKeychainContent = [preferences checkinKeychainContent];
  141. NSData *checkinData = [checkinKeychainContent dataUsingEncoding:NSUTF8StringEncoding];
  142. [weakKeychain
  143. setData:checkinData
  144. forService:service2
  145. accessibility:NULL
  146. account:account
  147. handler:^(NSError *error) {
  148. XCTAssertNil(error);
  149. // Now query the token and compare, they should not corrupt
  150. // each other.
  151. NSData *data1 = [weakKeychain dataForService:service1 account:account];
  152. #pragma clang diagnostic push
  153. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  154. FIRInstanceIDTokenInfo *tokenInfo1 =
  155. [NSKeyedUnarchiver unarchiveObjectWithData:data1];
  156. #pragma clang diagnostic pop
  157. XCTAssertEqualObjects(kToken1, tokenInfo1.token);
  158. NSData *data2 = [weakKeychain dataForService:service2 account:account];
  159. NSString *checkinKeychainContent =
  160. [[NSString alloc] initWithData:data2 encoding:NSUTF8StringEncoding];
  161. FIRInstanceIDCheckinPreferences *checkinPreferences =
  162. [FIRInstanceIDCheckinPreferences
  163. preferencesFromKeychainContents:checkinKeychainContent];
  164. XCTAssertEqualObjects(checkinPreferences.secretToken, kSecret);
  165. XCTAssertEqualObjects(checkinPreferences.deviceID, kAuthID);
  166. NSArray *results = [weakKeychain itemsMatchingService:@"*"
  167. account:account];
  168. XCTAssertEqual(results.count, 2);
  169. // Also check the cache data.
  170. XCTAssertEqual(weakKeychain.cachedKeychainData.count, 2);
  171. XCTAssertEqualObjects(
  172. weakKeychain.cachedKeychainData[service1][account].firstObject,
  173. 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. }
  188. - (void)testQueryCachedKeychainItems {
  189. XCTestExpectation *addItemToKeychainExpectation =
  190. [self expectationWithDescription:@"Test added item should be cached properly"];
  191. // A wildcard query should return empty data when there's nothing in keychain
  192. FIRInstanceIDAuthKeychain *keychain =
  193. [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
  194. id keychainMock = OCMPartialMock(keychain);
  195. NSArray *result = [keychain itemsMatchingService:@"*" account:@"*"];
  196. XCTAssertEqual(result.count, 0);
  197. // Create a keychain item
  198. NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  199. NSString *account = kBundleID1;
  200. NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  201. scope:kScope
  202. token:kToken1];
  203. __weak FIRInstanceIDAuthKeychain *weakKeychain = keychain;
  204. __weak id weakKeychainMock = keychainMock;
  205. [keychain setData:tokenData
  206. forService:service
  207. accessibility:NULL
  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. accessibility:NULL
  262. account:account
  263. handler:^(NSError *error) {
  264. XCTAssertNil(error);
  265. // Query the item should fetch from keychain because no entry under the same
  266. // service and account.
  267. NSData *data = [weakKeychain dataForService:service account:account];
  268. XCTAssertEqualObjects(data, tokenData);
  269. // Cache should now have the query item
  270. XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
  271. tokenData);
  272. // Clean up keychain at the end
  273. [weakKeychain removeItemsMatchingService:@"*"
  274. account:@"*"
  275. handler:^(NSError *_Nonnull error) {
  276. XCTAssertNil(error);
  277. [overwriteCachedKeychainExpectation fulfill];
  278. }];
  279. }];
  280. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  281. }
  282. - (void)testSetKeychainItemShouldDeleteOldEntry {
  283. XCTestExpectation *overwriteCachedKeychainExpectation = [self
  284. expectationWithDescription:@"Test keychain entry should be deleted before adding a new one"];
  285. FIRInstanceIDAuthKeychain *keychain =
  286. [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
  287. // Assume keychain had a old entry under the same service and account.
  288. // Now if we set the cache a different data under the same service
  289. NSData *oldData = [[NSData alloc] init];
  290. NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  291. NSString *account = kBundleID1;
  292. [keychain.cachedKeychainData setObject:[@{account : oldData} mutableCopy] forKey:service];
  293. // add a new keychain item
  294. NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  295. scope:kScope
  296. token:kToken1];
  297. __weak FIRInstanceIDAuthKeychain *weakKeychain = keychain;
  298. [keychain setData:tokenData
  299. forService:service
  300. accessibility:NULL
  301. account:account
  302. handler:^(NSError *error) {
  303. XCTAssertNil(error);
  304. // Cache should now have the updated item
  305. XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
  306. tokenData);
  307. // Clean up keychain at the end
  308. [weakKeychain removeItemsMatchingService:@"*"
  309. account:@"*"
  310. handler:^(NSError *_Nonnull error) {
  311. XCTAssertNil(error);
  312. [overwriteCachedKeychainExpectation fulfill];
  313. }];
  314. }];
  315. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  316. }
  317. - (void)testInvalidQuery {
  318. XCTestExpectation *invalidKeychainQueryExpectation =
  319. [self expectationWithDescription:@"Test invalid keychain query"];
  320. FIRInstanceIDAuthKeychain *keychain =
  321. [[FIRInstanceIDAuthKeychain alloc] initWithIdentifier:kFIRInstanceIDTestKeychainId];
  322. NSData *data = [[NSData alloc] init];
  323. [keychain setData:data
  324. forService:@"*"
  325. accessibility:NULL
  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