FIRMessagingAuthKeychainTest.m 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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 // TARGET_OS_IOS || TARGET_OS_TV
  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 *noCorruptionExpectation =
  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. FIRMessagingTokenInfo *tokenInfo1 =
  89. [NSKeyedUnarchiver unarchivedObjectOfClass:FIRMessagingTokenInfo.class
  90. fromData:data1
  91. error:&error];
  92. XCTAssertNil(error);
  93. XCTAssertEqualObjects(kToken1, tokenInfo1.token);
  94. NSData *data2 = [weakKeychain dataForService:service account:account2];
  95. FIRMessagingTokenInfo *tokenInfo2 =
  96. [NSKeyedUnarchiver unarchivedObjectOfClass:FIRMessagingTokenInfo.class
  97. fromData:data2
  98. error:&error];
  99. XCTAssertNil(error);
  100. XCTAssertEqualObjects(kToken2, tokenInfo2.token);
  101. // Also check the cache data.
  102. XCTAssertEqual(weakKeychain.cachedKeychainData.count, 1);
  103. XCTAssertEqual(weakKeychain.cachedKeychainData[service].count, 2);
  104. XCTAssertEqualObjects(
  105. weakKeychain.cachedKeychainData[service][account1].firstObject,
  106. tokenInfoData1);
  107. XCTAssertEqualObjects(
  108. weakKeychain.cachedKeychainData[service][account2].firstObject,
  109. tokenInfoData2);
  110. // Check wildcard query
  111. NSArray *results = [weakKeychain itemsMatchingService:service account:@"*"];
  112. XCTAssertEqual(results.count, 2);
  113. // Clean up keychain at the end
  114. [weakKeychain removeItemsMatchingService:service
  115. account:@"*"
  116. handler:^(NSError *_Nonnull error) {
  117. XCTAssertNil(error);
  118. [noCorruptionExpectation fulfill];
  119. }];
  120. }];
  121. }];
  122. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  123. #endif // TARGET_OS_IOS || TARGET_OS_TV
  124. }
  125. - (void)testKeyChainNoCorruptionWithUniqueService {
  126. #if TARGET_OS_IOS || TARGET_OS_TV
  127. XCTestExpectation *noCorruptionExpectation =
  128. [self expectationWithDescription:@"No corruption between different services."];
  129. // Create a keychain with a service and a unique account
  130. NSString *service1 = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  131. NSString *account = kBundleID1;
  132. NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  133. scope:kScope
  134. token:kToken1];
  135. FIRMessagingAuthKeychain *keychain =
  136. [[FIRMessagingAuthKeychain alloc] initWithIdentifier:kFIRMessagingTestKeychainId];
  137. __weak FIRMessagingAuthKeychain *weakKeychain = keychain;
  138. [keychain
  139. setData:tokenData
  140. forService:service1
  141. account:account
  142. handler:^(NSError *error) {
  143. XCTAssertNil(error);
  144. // Store a checkin info using the same keychain account, but different service.
  145. NSString *service2 = @"com.google.iid.checkin";
  146. FIRMessagingCheckinPreferences *preferences =
  147. [[FIRMessagingCheckinPreferences alloc] initWithDeviceID:kAuthID
  148. secretToken:kSecret];
  149. NSString *checkinKeychainContent = [preferences checkinKeychainContent];
  150. NSData *checkinData = [checkinKeychainContent dataUsingEncoding:NSUTF8StringEncoding];
  151. [weakKeychain
  152. setData:checkinData
  153. forService:service2
  154. account:account
  155. handler:^(NSError *error) {
  156. XCTAssertNil(error);
  157. // Now query the token and compare, they should not corrupt
  158. // each other.
  159. NSData *data1 = [weakKeychain dataForService:service1 account:account];
  160. FIRMessagingTokenInfo *tokenInfo1 =
  161. [NSKeyedUnarchiver unarchivedObjectOfClass:FIRMessagingTokenInfo.class
  162. fromData:data1
  163. error:&error];
  164. XCTAssertNil(error);
  165. XCTAssertEqualObjects(kToken1, tokenInfo1.token);
  166. NSData *data2 = [weakKeychain dataForService:service2 account:account];
  167. NSString *checkinKeychainContent =
  168. [[NSString alloc] initWithData:data2 encoding:NSUTF8StringEncoding];
  169. FIRMessagingCheckinPreferences *checkinPreferences =
  170. [FIRMessagingCheckinPreferences
  171. preferencesFromKeychainContents:checkinKeychainContent];
  172. XCTAssertEqualObjects(checkinPreferences.secretToken, kSecret);
  173. XCTAssertEqualObjects(checkinPreferences.deviceID, kAuthID);
  174. NSArray *results = [weakKeychain itemsMatchingService:@"*" account:account];
  175. XCTAssertEqual(results.count, 2);
  176. // Also check the cache data.
  177. XCTAssertEqual(weakKeychain.cachedKeychainData.count, 2);
  178. XCTAssertEqualObjects(
  179. weakKeychain.cachedKeychainData[service1][account].firstObject, 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. [noCorruptionExpectation fulfill];
  189. }];
  190. }];
  191. }];
  192. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  193. #endif // TARGET_OS_IOS || TARGET_OS_TV
  194. }
  195. // Skip keychain tests on Catalyst and macOS. Tests are skipped because they
  196. // involve interactions with the keychain that require a provisioning profile.
  197. // See go/firebase-macos-keychain-popups for more details.
  198. #if !TARGET_OS_MACCATALYST && !TARGET_OS_OSX
  199. - (void)testQueryCachedKeychainItems {
  200. XCTestExpectation *addItemToKeychainExpectation =
  201. [self expectationWithDescription:@"Test added item should be cached properly"];
  202. // A wildcard query should return empty data when there's nothing in keychain
  203. FIRMessagingAuthKeychain *keychain =
  204. [[FIRMessagingAuthKeychain alloc] initWithIdentifier:kFIRMessagingTestKeychainId];
  205. id keychainMock = OCMPartialMock(keychain);
  206. NSArray *result = [keychain itemsMatchingService:@"*" account:@"*"];
  207. XCTAssertEqual(result.count, 0);
  208. // Create a keychain item
  209. NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  210. NSString *account = kBundleID1;
  211. NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  212. scope:kScope
  213. token:kToken1];
  214. __weak FIRMessagingAuthKeychain *weakKeychain = keychain;
  215. __weak id weakKeychainMock = keychainMock;
  216. [keychain setData:tokenData
  217. forService:service
  218. account:account
  219. handler:^(NSError *error) {
  220. XCTAssertNil(error);
  221. // Now if we clean the cache
  222. [weakKeychain.cachedKeychainData removeAllObjects];
  223. // Then query the item should fetch from keychain.
  224. NSData *data = [weakKeychain dataForService:service account:account];
  225. XCTAssertEqualObjects(data, tokenData);
  226. // Verify we fetch from keychain by calling to get the query
  227. OCMVerify([weakKeychainMock keychainQueryForService:service account:account]);
  228. // Cache should now have the query item
  229. XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
  230. tokenData);
  231. // Wildcard query should simply return the results without cache it
  232. data = [weakKeychain dataForService:@"*" account:account];
  233. XCTAssertEqualObjects(data, tokenData);
  234. // Cache should not have wildcard query entry
  235. XCTAssertNil(weakKeychain.cachedKeychainData[@"*"]);
  236. // Assume keychain has empty service entry
  237. [weakKeychain.cachedKeychainData setObject:[@{} mutableCopy] forKey:service];
  238. // Query the item
  239. data = [weakKeychain dataForService:service account:account];
  240. XCTAssertEqualObjects(data, tokenData);
  241. // Cache should have the query item.
  242. XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
  243. tokenData);
  244. // Clean up keychain at the end
  245. [weakKeychain removeItemsMatchingService:@"*"
  246. account:@"*"
  247. handler:^(NSError *_Nonnull error) {
  248. XCTAssertNil(error);
  249. [addItemToKeychainExpectation fulfill];
  250. }];
  251. }];
  252. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  253. }
  254. - (void)testCachedKeychainOverwrite {
  255. XCTestExpectation *overwriteCachedKeychainExpectation =
  256. [self expectationWithDescription:@"Test the cached keychain item is overwrite properly"];
  257. FIRMessagingAuthKeychain *keychain =
  258. [[FIRMessagingAuthKeychain alloc] initWithIdentifier:kFIRMessagingTestKeychainId];
  259. // Set the cache a different data under the same service but different account
  260. NSData *data = [[NSData alloc] init];
  261. NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  262. [keychain.cachedKeychainData setObject:[@{kBundleID2 : data} mutableCopy] forKey:service];
  263. // Create a keychain item
  264. NSString *account = kBundleID1;
  265. NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  266. scope:kScope
  267. token:kToken1];
  268. __weak FIRMessagingAuthKeychain *weakKeychain = keychain;
  269. [keychain setData:tokenData
  270. forService:service
  271. account:account
  272. handler:^(NSError *error) {
  273. XCTAssertNil(error);
  274. // Query the item should fetch from keychain because no entry under the same
  275. // service and account.
  276. NSData *data = [weakKeychain dataForService:service account:account];
  277. XCTAssertEqualObjects(data, tokenData);
  278. // Cache should now have the query item
  279. XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
  280. tokenData);
  281. // Clean up keychain at the end
  282. [weakKeychain removeItemsMatchingService:@"*"
  283. account:@"*"
  284. handler:^(NSError *_Nonnull error) {
  285. XCTAssertNil(error);
  286. [overwriteCachedKeychainExpectation fulfill];
  287. }];
  288. }];
  289. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  290. }
  291. - (void)testSetKeychainItemShouldDeleteOldEntry {
  292. XCTestExpectation *overwriteCachedKeychainExpectation = [self
  293. expectationWithDescription:@"Test keychain entry should be deleted before adding a new one"];
  294. FIRMessagingAuthKeychain *keychain =
  295. [[FIRMessagingAuthKeychain alloc] initWithIdentifier:kFIRMessagingTestKeychainId];
  296. // Assume keychain had a old entry under the same service and account.
  297. // Now if we set the cache a different data under the same service
  298. NSData *oldData = [[NSData alloc] init];
  299. NSString *service = [NSString stringWithFormat:@"%@:%@", kAuthorizedEntity, kScope];
  300. NSString *account = kBundleID1;
  301. [keychain.cachedKeychainData setObject:[@{account : oldData} mutableCopy] forKey:service];
  302. // add a new keychain item
  303. NSData *tokenData = [self tokenDataWithAuthorizedEntity:kAuthorizedEntity
  304. scope:kScope
  305. token:kToken1];
  306. __weak FIRMessagingAuthKeychain *weakKeychain = keychain;
  307. [keychain setData:tokenData
  308. forService:service
  309. account:account
  310. handler:^(NSError *error) {
  311. XCTAssertNil(error);
  312. // Cache should now have the updated item
  313. XCTAssertEqualObjects(weakKeychain.cachedKeychainData[service][account].firstObject,
  314. tokenData);
  315. // Clean up keychain at the end
  316. [weakKeychain removeItemsMatchingService:@"*"
  317. account:@"*"
  318. handler:^(NSError *_Nonnull error) {
  319. XCTAssertNil(error);
  320. [overwriteCachedKeychainExpectation fulfill];
  321. }];
  322. }];
  323. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  324. }
  325. - (void)testInvalidQuery {
  326. XCTestExpectation *invalidKeychainQueryExpectation =
  327. [self expectationWithDescription:@"Test invalid keychain query"];
  328. FIRMessagingAuthKeychain *keychain =
  329. [[FIRMessagingAuthKeychain alloc] initWithIdentifier:kFIRMessagingTestKeychainId];
  330. NSData *data = [[NSData alloc] init];
  331. [keychain setData:data
  332. forService:@"*"
  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. FIRMessagingAuthKeychain *keychain =
  342. [[FIRMessagingAuthKeychain alloc] initWithIdentifier:kFIRMessagingTestKeychainId];
  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. #endif // !TARGET_OS_MACCATALYST && !TARGET_OS_OSX
  357. #pragma mark - helper function
  358. - (NSData *)tokenDataWithAuthorizedEntity:(NSString *)authorizedEntity
  359. scope:(NSString *)scope
  360. token:(NSString *)token {
  361. FIRMessagingTokenInfo *tokenInfo =
  362. [[FIRMessagingTokenInfo alloc] initWithAuthorizedEntity:authorizedEntity
  363. scope:scope
  364. token:token
  365. appVersion:@"1.0"
  366. firebaseAppID:kFirebaseAppID];
  367. NSError *error;
  368. NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:tokenInfo
  369. requiringSecureCoding:YES
  370. error:&error];
  371. XCTAssertNil(error);
  372. return archive;
  373. }
  374. @end
  375. #endif // !TARGET_OS_MACCATALYST && !SWIFT_PACKAGE