FIRMessagingAuthKeychainTest.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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 && !SWIFT_PACKAGE
  18. // Skip keychain tests on Catalyst and swift package
  19. #import <OCMock/OCMock.h>
  20. #import <XCTest/XCTest.h>
  21. #import "FirebaseMessaging/Sources/Token/FIRMessagingAuthKeychain.h"
  22. #import "FirebaseMessaging/Sources/Token/FIRMessagingCheckinPreferences.h"
  23. #import "FirebaseMessaging/Sources/Token/FIRMessagingTokenInfo.h"
  24. static NSString *const kFIRMessagingTestKeychainId = @"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 FIRMessagingAuthKeychain (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 FIRMessagingAuthKeychainTest : XCTestCase
  47. @end
  48. @implementation FIRMessagingAuthKeychainTest
  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. FIRMessagingAuthKeychain *keychain =
  67. [[FIRMessagingAuthKeychain alloc] initWithIdentifier:kFIRMessagingTestKeychainId];
  68. __weak FIRMessagingAuthKeychain *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. FIRMessagingTokenInfo *tokenInfo1 =
  91. [NSKeyedUnarchiver unarchiveObjectWithData:data1];
  92. XCTAssertEqualObjects(kToken1, tokenInfo1.token);
  93. NSData *data2 = [weakKeychain dataForService:service account:account2];
  94. FIRMessagingTokenInfo *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. FIRMessagingAuthKeychain *keychain =
  133. [[FIRMessagingAuthKeychain alloc] initWithIdentifier:kFIRMessagingTestKeychainId];
  134. __weak FIRMessagingAuthKeychain *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. FIRMessagingCheckinPreferences *preferences =
  144. [[FIRMessagingCheckinPreferences 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. FIRMessagingTokenInfo *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. FIRMessagingCheckinPreferences *checkinPreferences =
  167. [FIRMessagingCheckinPreferences
  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. // Skip keychain tests on Catalyst and macOS. Tests are skipped because they
  193. // involve interactions with the keychain that require a provisioning profile.
  194. // See go/firebase-macos-keychain-popups for more details.
  195. #if !TARGET_OS_MACCATALYST && !TARGET_OS_OSX
  196. - (void)testQueryCachedKeychainItems {
  197. XCTestExpectation *addItemToKeychainExpectation =
  198. [self expectationWithDescription:@"Test added item should be cached properly"];
  199. // A wildcard query should return empty data when there's nothing in keychain
  200. FIRMessagingAuthKeychain *keychain =
  201. [[FIRMessagingAuthKeychain alloc] initWithIdentifier:kFIRMessagingTestKeychainId];
  202. id keychainMock = OCMPartialMock(keychain);
  203. NSArray *result = [keychain itemsMatchingService:@"*" account:@"*"];
  204. XCTAssertEqual(result.count, 0);
  205. // Create a keychain item
  206. NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  207. NSString *account = kBundleID1;
  208. NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  209. scope:kScope
  210. token:kToken1];
  211. __weak FIRMessagingAuthKeychain *weakKeychain = keychain;
  212. __weak id weakKeychainMock = keychainMock;
  213. [keychain setData:tokenData
  214. forService:service
  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. FIRMessagingAuthKeychain *keychain =
  255. [[FIRMessagingAuthKeychain alloc] initWithIdentifier:kFIRMessagingTestKeychainId];
  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 FIRMessagingAuthKeychain *weakKeychain = keychain;
  266. [keychain setData:tokenData
  267. forService:service
  268. account:account
  269. handler:^(NSError *error) {
  270. XCTAssertNil(error);
  271. // Query the item should fetch from keychain because no entry under the same
  272. // service and account.
  273. NSData *data = [weakKeychain dataForService:service account:account];
  274. XCTAssertEqualObjects(data, tokenData);
  275. // Cache should now have the query item
  276. XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
  277. tokenData);
  278. // Clean up keychain at the end
  279. [weakKeychain removeItemsMatchingService:@"*"
  280. account:@"*"
  281. handler:^(NSError *_Nonnull error) {
  282. XCTAssertNil(error);
  283. [overwriteCachedKeychainExpectation fulfill];
  284. }];
  285. }];
  286. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  287. }
  288. - (void)testSetKeychainItemShouldDeleteOldEntry {
  289. XCTestExpectation *overwriteCachedKeychainExpectation = [self
  290. expectationWithDescription:@"Test keychain entry should be deleted before adding a new one"];
  291. FIRMessagingAuthKeychain *keychain =
  292. [[FIRMessagingAuthKeychain alloc] initWithIdentifier:kFIRMessagingTestKeychainId];
  293. // Assume keychain had a old entry under the same service and account.
  294. // Now if we set the cache a different data under the same service
  295. NSData *oldData = [[NSData alloc] init];
  296. NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  297. NSString *account = kBundleID1;
  298. [keychain.cachedKeychainData setObject:[@{account : oldData} mutableCopy] forKey:service];
  299. // add a new keychain item
  300. NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  301. scope:kScope
  302. token:kToken1];
  303. __weak FIRMessagingAuthKeychain *weakKeychain = keychain;
  304. [keychain setData:tokenData
  305. forService:service
  306. account:account
  307. handler:^(NSError *error) {
  308. XCTAssertNil(error);
  309. // Cache should now have the updated item
  310. XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
  311. tokenData);
  312. // Clean up keychain at the end
  313. [weakKeychain removeItemsMatchingService:@"*"
  314. account:@"*"
  315. handler:^(NSError *_Nonnull error) {
  316. XCTAssertNil(error);
  317. [overwriteCachedKeychainExpectation fulfill];
  318. }];
  319. }];
  320. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  321. }
  322. - (void)testInvalidQuery {
  323. XCTestExpectation *invalidKeychainQueryExpectation =
  324. [self expectationWithDescription:@"Test invalid keychain query"];
  325. FIRMessagingAuthKeychain *keychain =
  326. [[FIRMessagingAuthKeychain alloc] initWithIdentifier:kFIRMessagingTestKeychainId];
  327. NSData *data = [[NSData alloc] init];
  328. [keychain setData:data
  329. forService:@"*"
  330. account:@"*"
  331. handler:^(NSError *error) {
  332. XCTAssertNotNil(error);
  333. [invalidKeychainQueryExpectation fulfill];
  334. }];
  335. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  336. }
  337. - (void)testQueryAndAddEntry {
  338. FIRMessagingAuthKeychain *keychain =
  339. [[FIRMessagingAuthKeychain alloc] initWithIdentifier:kFIRMessagingTestKeychainId];
  340. // Set the cache a different data under the same service but different account
  341. NSData *data = [[NSData alloc] init];
  342. NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  343. NSString *account1 = kBundleID1;
  344. [keychain.cachedKeychainData setObject:[@{account1 : data} mutableCopy] forKey:service];
  345. // Now account2 doesn't exist in cache
  346. NSString *account2 = kBundleID2;
  347. XCTAssertNil(keychain.cachedKeychainData[service][account2]);
  348. // Query account2
  349. XCTAssertNil([keychain dataForService:service account:account2]);
  350. // Service and account2 should exist in cache.
  351. XCTAssertNotNil(keychain.cachedKeychainData[service][account2]);
  352. }
  353. #endif
  354. #pragma mark - helper function
  355. - (NSData *)tokenDataWithAuthorizedEntity:(NSString *)authorizedEntity
  356. scope:(NSString *)scope
  357. token:(NSString *)token {
  358. FIRMessagingTokenInfo *tokenInfo =
  359. [[FIRMessagingTokenInfo alloc] initWithAuthorizedEntity:authorizedEntity
  360. scope:scope
  361. token:token
  362. appVersion:@"1.0"
  363. firebaseAppID:kFirebaseAppID];
  364. #pragma clang diagnostic push
  365. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  366. return [NSKeyedArchiver archivedDataWithRootObject:tokenInfo];
  367. #pragma clang diagnostic pop
  368. }
  369. @end
  370. #endif // TARGET_OS_MACCATALYST