FIRInstanceIDTest.m 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  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 <FirebaseCore/FIRAppInternal.h>
  18. #import <FirebaseCore/FIROptionsInternal.h>
  19. #import <FirebaseInstanceID/FIRInstanceID_Private.h>
  20. #import <OCMock/OCMock.h>
  21. #import "Firebase/InstanceID/FIRInstanceIDAuthService.h"
  22. #import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.h"
  23. #import "Firebase/InstanceID/FIRInstanceIDConstants.h"
  24. #import "Firebase/InstanceID/FIRInstanceIDKeyPair.h"
  25. #import "Firebase/InstanceID/FIRInstanceIDKeyPairStore.h"
  26. #import "Firebase/InstanceID/FIRInstanceIDTokenInfo.h"
  27. #import "Firebase/InstanceID/FIRInstanceIDTokenManager.h"
  28. #import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
  29. #import "Firebase/InstanceID/NSError+FIRInstanceID.h"
  30. static NSString *const kFakeIID = @"12345678";
  31. static NSString *const kFakeAPNSToken = @"this is a fake apns token";
  32. static NSString *const kAuthorizedEntity = @"test-audience";
  33. static NSString *const kScope = @"test-scope";
  34. static NSString *const kToken = @"test-token";
  35. static FIRInstanceIDTokenInfo *sTokenInfo;
  36. // Faking checkin calls
  37. static NSString *const kDeviceAuthId = @"device-id";
  38. static NSString *const kSecretToken = @"secret-token";
  39. static NSString *const kDigest = @"com.google.digest";
  40. static NSString *const kVersionInfo = @"1.0";
  41. // FIRApp configuration.
  42. static NSString *const kGCMSenderID = @"correct_gcm_sender_id";
  43. static NSString *const kGoogleAppID = @"1:123:ios:123abc";
  44. @interface FIRInstanceID (ExposedForTest)
  45. @property(nonatomic, readwrite, strong) FIRInstanceIDTokenManager *tokenManager;
  46. @property(nonatomic, readwrite, strong) FIRInstanceIDKeyPairStore *keyPairStore;
  47. @property(nonatomic, readwrite, copy) NSString *fcmSenderID;
  48. - (NSInteger)retryIntervalToFetchDefaultToken;
  49. - (BOOL)isFCMAutoInitEnabled;
  50. - (void)didCompleteConfigure;
  51. - (NSString *)cachedTokenIfAvailable;
  52. - (void)deleteIdentityWithHandler:(FIRInstanceIDDeleteHandler)handler;
  53. + (FIRInstanceID *)instanceIDForTests;
  54. - (void)defaultTokenWithHandler:(FIRInstanceIDTokenHandler)handler;
  55. - (instancetype)initPrivately;
  56. - (void)start;
  57. + (int64_t)maxRetryCountForDefaultToken;
  58. + (int64_t)minIntervalForDefaultTokenRetry;
  59. + (int64_t)maxRetryIntervalForDefaultTokenInSeconds;
  60. @end
  61. @interface FIRInstanceIDTest : XCTestCase
  62. @property(nonatomic, readwrite, assign) BOOL hasCheckinInfo;
  63. @property(nonatomic, readwrite, strong) FIRInstanceID *instanceID;
  64. @property(nonatomic, readwrite, strong) id mockInstanceID;
  65. @property(nonatomic, readwrite, strong) id mockTokenManager;
  66. @property(nonatomic, readwrite, strong) id mockKeyPairStore;
  67. @property(nonatomic, readwrite, strong) id mockAuthService;
  68. @property(nonatomic, readwrite, strong) id<NSObject> tokenRefreshNotificationObserver;
  69. @property(nonatomic, readwrite, copy) FIRInstanceIDTokenHandler newTokenCompletion;
  70. @property(nonatomic, readwrite, copy) FIRInstanceIDDeleteTokenHandler deleteTokenCompletion;
  71. @end
  72. @implementation FIRInstanceIDTest
  73. - (void)setUp {
  74. [super setUp];
  75. _instanceID = [[FIRInstanceID alloc] initPrivately];
  76. [_instanceID start];
  77. if (!sTokenInfo) {
  78. sTokenInfo = [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
  79. scope:kScope
  80. token:kToken
  81. appVersion:nil
  82. firebaseAppID:nil];
  83. sTokenInfo.cacheTime = [NSDate date];
  84. }
  85. [self mockInstanceIDObjects];
  86. }
  87. - (void)tearDown {
  88. [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
  89. self.instanceID = nil;
  90. self.mockTokenManager = nil;
  91. self.mockInstanceID = nil;
  92. [super tearDown];
  93. }
  94. - (void)mockInstanceIDObjects {
  95. // Mock that we have valid checkin info. Individual tests can override this.
  96. self.hasCheckinInfo = YES;
  97. self.mockAuthService = OCMClassMock([FIRInstanceIDAuthService class]);
  98. [[[self.mockAuthService stub] andDo:^(NSInvocation *invocation) {
  99. [invocation setReturnValue:&self->_hasCheckinInfo];
  100. }] hasValidCheckinInfo];
  101. self.mockTokenManager = OCMClassMock([FIRInstanceIDTokenManager class]);
  102. [[[self.mockTokenManager stub] andReturn:self.mockAuthService] authService];
  103. self.mockKeyPairStore = OCMClassMock([FIRInstanceIDKeyPairStore class]);
  104. _instanceID.fcmSenderID = kAuthorizedEntity;
  105. self.mockInstanceID = OCMPartialMock(_instanceID);
  106. [self.mockInstanceID setTokenManager:self.mockTokenManager];
  107. [self.mockInstanceID setKeyPairStore:self.mockKeyPairStore];
  108. id instanceIDClassMock = OCMClassMock([FIRInstanceID class]);
  109. OCMStub(ClassMethod([instanceIDClassMock minIntervalForDefaultTokenRetry])).andReturn(2);
  110. OCMStub(ClassMethod([instanceIDClassMock maxRetryIntervalForDefaultTokenInSeconds]))
  111. .andReturn(10);
  112. }
  113. /**
  114. * Tests that the FIRInstanceID's sharedInstance class method produces an instance of
  115. * FIRInstanceID with an associated FIRInstanceIDTokenManager.
  116. */
  117. - (void)testSharedInstance {
  118. // The shared instance should be `nil` before the app is configured.
  119. XCTAssertNil([FIRInstanceID instanceID]);
  120. // The shared instance relies on the default app being configured. Configure it.
  121. FIROptions *options = [[FIROptions alloc] initWithGoogleAppID:kGoogleAppID
  122. GCMSenderID:kGCMSenderID];
  123. [FIRApp configureWithName:kFIRDefaultAppName options:options];
  124. FIRInstanceID *instanceID = [FIRInstanceID instanceID];
  125. XCTAssertNotNil(instanceID);
  126. XCTAssertNotNil(instanceID.tokenManager);
  127. // Ensure a second call returns the same instance as the first.
  128. FIRInstanceID *secondInstanceID = [FIRInstanceID instanceID];
  129. XCTAssertEqualObjects(instanceID, secondInstanceID);
  130. // Reset the default app for the next test.
  131. [FIRApp resetApps];
  132. }
  133. - (void)testFCMAutoInitEnabled {
  134. XCTAssertFalse([_instanceID isFCMAutoInitEnabled],
  135. @"When FCM is not available, FCM Auto Init Enabled should be NO.");
  136. }
  137. - (void)testTokenShouldBeRefreshedIfCacheTokenNeedsToBeRefreshed {
  138. [[[self.mockInstanceID stub] andReturn:kToken] cachedTokenIfAvailable];
  139. [[[self.mockTokenManager stub] andReturnValue:@(YES)] checkForTokenRefreshPolicy];
  140. [[[self.mockInstanceID stub] andDo:^(NSInvocation *invocation){
  141. }] tokenWithAuthorizedEntity:[OCMArg any]
  142. scope:[OCMArg any]
  143. options:[OCMArg any]
  144. handler:[OCMArg any]];
  145. [self.mockInstanceID didCompleteConfigure];
  146. OCMVerify([self.mockInstanceID defaultTokenWithHandler:nil]);
  147. XCTAssertEqualObjects([self.mockInstanceID token], kToken);
  148. }
  149. - (void)testTokenShouldBeRefreshedIfNoCacheTokenButAutoInitAllowed {
  150. [[[self.mockInstanceID stub] andReturn:nil] cachedTokenIfAvailable];
  151. [[[self.mockInstanceID stub] andReturnValue:@(YES)] isFCMAutoInitEnabled];
  152. [[[self.mockInstanceID stub] andDo:^(NSInvocation *invocation){
  153. }] tokenWithAuthorizedEntity:[OCMArg any]
  154. scope:[OCMArg any]
  155. options:[OCMArg any]
  156. handler:[OCMArg any]];
  157. [self.mockInstanceID didCompleteConfigure];
  158. OCMVerify([self.mockInstanceID defaultTokenWithHandler:nil]);
  159. }
  160. - (void)testTokenIsDeletedAlongWithIdentity {
  161. [[[self.mockInstanceID stub] andReturnValue:@(YES)] isFCMAutoInitEnabled];
  162. [[[self.mockInstanceID stub] andDo:^(NSInvocation *invocation){
  163. }] tokenWithAuthorizedEntity:[OCMArg any]
  164. scope:[OCMArg any]
  165. options:[OCMArg any]
  166. handler:[OCMArg any]];
  167. [self.mockInstanceID deleteIdentityWithHandler:^(NSError *_Nullable error) {
  168. XCTAssertNil([self.mockInstanceID token]);
  169. }];
  170. }
  171. - (void)testTokenIsFetchedDuringIIDGeneration {
  172. XCTestExpectation *tokenExpectation = [self
  173. expectationWithDescription:@"Token is refreshed when getID is called to avoid IID conflict."];
  174. NSError *error;
  175. [[[self.mockKeyPairStore stub] andReturn:kFakeIID] appIdentityWithError:[OCMArg setTo:error]];
  176. [self.mockInstanceID getIDWithHandler:^(NSString *identity, NSError *error) {
  177. XCTAssertNotNil(identity);
  178. XCTAssertEqual(identity, kFakeIID);
  179. OCMVerify([self.mockInstanceID token]);
  180. [tokenExpectation fulfill];
  181. }];
  182. [self waitForExpectationsWithTimeout:0.1
  183. handler:^(NSError *error) {
  184. XCTAssertNil(error);
  185. }];
  186. }
  187. /**
  188. * Tests that when a new InstanceID token is successfully produced,
  189. * the callback is invoked with a token that is not an empty string and with no error.
  190. */
  191. - (void)testNewTokenSuccess {
  192. XCTestExpectation *tokenExpectation =
  193. [self expectationWithDescription:@"New token handler invoked."];
  194. NSString *APNSKey = kFIRInstanceIDTokenOptionsAPNSKey;
  195. NSString *serverKey = kFIRInstanceIDTokenOptionsAPNSIsSandboxKey;
  196. [self stubKeyPairStoreToReturnValidKeypair];
  197. [self mockAuthServiceToAlwaysReturnValidCheckin];
  198. NSData *fakeAPNSDeviceToken = [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding];
  199. BOOL isSandbox = YES;
  200. NSDictionary *tokenOptions = @{
  201. APNSKey : fakeAPNSDeviceToken,
  202. serverKey : @(isSandbox),
  203. };
  204. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  205. self.newTokenCompletion(kToken, nil);
  206. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  207. scope:kScope
  208. keyPair:[OCMArg any]
  209. options:[OCMArg checkWithBlock:^BOOL(id obj) {
  210. NSDictionary *options = (NSDictionary *)obj;
  211. XCTAssertTrue([options[APNSKey] isEqual:fakeAPNSDeviceToken]);
  212. XCTAssertTrue([options[serverKey] isEqual:@(isSandbox)]);
  213. return YES;
  214. }]
  215. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  216. self.newTokenCompletion = obj;
  217. return obj != nil;
  218. }]];
  219. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  220. scope:kScope
  221. options:tokenOptions
  222. handler:^(NSString *token, NSError *error) {
  223. XCTAssertNotNil(token);
  224. XCTAssertGreaterThan(token.length, 0);
  225. XCTAssertNil(error);
  226. [tokenExpectation fulfill];
  227. }];
  228. [self waitForExpectationsWithTimeout:1
  229. handler:^(NSError *error) {
  230. XCTAssertNil(error);
  231. }];
  232. }
  233. /**
  234. * Get Token should fail if we do not have valid checkin info and are unable to
  235. * retreive one.
  236. */
  237. - (void)testNewTokenCheckinFailure {
  238. self.hasCheckinInfo = NO;
  239. __block FIRInstanceIDDeviceCheckinCompletion checkinHandler;
  240. [[[self.mockAuthService stub] andDo:^(NSInvocation *invocation) {
  241. if (checkinHandler) {
  242. FIRInstanceIDErrorCode code = kFIRInstanceIDErrorCodeUnknown;
  243. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:code];
  244. checkinHandler(nil, error);
  245. }
  246. }] fetchCheckinInfoWithHandler:[OCMArg checkWithBlock:^BOOL(id obj) {
  247. return (checkinHandler = obj) != nil;
  248. }]];
  249. XCTestExpectation *tokenExpectation =
  250. [self expectationWithDescription:@"New token handler invoked."];
  251. NSDictionary *tokenOptions = @{
  252. kFIRInstanceIDTokenOptionsAPNSKey : [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding],
  253. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(YES),
  254. };
  255. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  256. self.newTokenCompletion(kToken, nil);
  257. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  258. scope:kScope
  259. keyPair:[OCMArg any]
  260. options:[OCMArg any]
  261. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  262. self.newTokenCompletion = obj;
  263. return obj != nil;
  264. }]];
  265. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  266. scope:kScope
  267. options:tokenOptions
  268. handler:^(NSString *token, NSError *error) {
  269. XCTAssertNil(token);
  270. XCTAssertNotNil(error);
  271. [tokenExpectation fulfill];
  272. }];
  273. [self waitForExpectationsWithTimeout:60.0
  274. handler:^(NSError *error) {
  275. XCTAssertNil(error);
  276. }];
  277. }
  278. /**
  279. * Get token with no valid checkin should wait for any existing checkin operation to finish.
  280. * If the checkin succeeds within a stipulated amount of time period getting the token should
  281. * also succeed.
  282. */
  283. - (void)testNewTokenSuccessAfterWaiting {
  284. self.hasCheckinInfo = NO;
  285. __block FIRInstanceIDDeviceCheckinCompletion checkinHandler;
  286. [[[self.mockAuthService stub] andDo:^(NSInvocation *invocation) {
  287. if (checkinHandler) {
  288. FIRInstanceIDErrorCode code = kFIRInstanceIDErrorCodeUnknown;
  289. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:code];
  290. checkinHandler(nil, error);
  291. }
  292. }] fetchCheckinInfoWithHandler:[OCMArg checkWithBlock:^BOOL(id obj) {
  293. return (checkinHandler = obj) != nil;
  294. }]];
  295. XCTestExpectation *tokenExpectation =
  296. [self expectationWithDescription:@"New token handler invoked."];
  297. NSDictionary *tokenOptions = @{
  298. kFIRInstanceIDTokenOptionsAPNSKey : [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding],
  299. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(YES),
  300. };
  301. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  302. self.newTokenCompletion(kToken, nil);
  303. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  304. scope:kScope
  305. keyPair:[OCMArg any]
  306. options:[OCMArg any]
  307. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  308. self.newTokenCompletion = obj;
  309. return obj != nil;
  310. }]];
  311. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  312. scope:kScope
  313. options:tokenOptions
  314. handler:^(NSString *token, NSError *error) {
  315. XCTAssertNil(token);
  316. XCTAssertNotNil(error);
  317. [tokenExpectation fulfill];
  318. }];
  319. [self waitForExpectationsWithTimeout:60.0
  320. handler:^(NSError *error) {
  321. XCTAssertNil(error);
  322. }];
  323. }
  324. /**
  325. * Test that the prod APNS token is correctly prefixed with "prod".
  326. */
  327. - (void)testAPNSTokenIsPrefixedCorrectlyForServerType {
  328. NSString *APNSKey = kFIRInstanceIDTokenOptionsAPNSKey;
  329. NSString *serverTypeKey = kFIRInstanceIDTokenOptionsAPNSIsSandboxKey;
  330. NSDictionary *prodTokenOptions = @{
  331. APNSKey : [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding],
  332. serverTypeKey : @(NO),
  333. };
  334. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation){
  335. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  336. scope:kScope
  337. keyPair:[OCMArg any]
  338. options:[OCMArg checkWithBlock:^BOOL(id obj) {
  339. NSDictionary *options = (NSDictionary *)obj;
  340. XCTAssertTrue([options[APNSKey] hasPrefix:@"p_"]);
  341. XCTAssertFalse([options[serverTypeKey] boolValue]);
  342. return YES;
  343. }]
  344. handler:OCMOCK_ANY];
  345. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  346. scope:kScope
  347. options:prodTokenOptions
  348. handler:^(NSString *token, NSError *error){
  349. }];
  350. }
  351. /**
  352. * Tests that when there is a failure in producing a new InstanceID token,
  353. * the callback is invoked with an error and a nil token.
  354. */
  355. - (void)testNewTokenFailure {
  356. XCTestExpectation *tokenExpectation =
  357. [self expectationWithDescription:@"New token handler invoked."];
  358. NSDictionary *tokenOptions = [NSDictionary dictionary];
  359. [self mockAuthServiceToAlwaysReturnValidCheckin];
  360. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  361. NSError *someError = [[NSError alloc] initWithDomain:@"InstanceIDUnitTest" code:0 userInfo:nil];
  362. self.newTokenCompletion(nil, someError);
  363. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  364. scope:kScope
  365. keyPair:[OCMArg any]
  366. options:tokenOptions
  367. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  368. self.newTokenCompletion = obj;
  369. return obj != nil;
  370. }]];
  371. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  372. scope:kScope
  373. options:tokenOptions
  374. handler:^(NSString *token, NSError *error) {
  375. XCTAssertNil(token);
  376. XCTAssertNotNil(error);
  377. [tokenExpectation fulfill];
  378. }];
  379. [self waitForExpectationsWithTimeout:1
  380. handler:^(NSError *error) {
  381. XCTAssertNil(error);
  382. }];
  383. }
  384. /**
  385. * Tests that when a token is deleted successfully, the callback is invoked with no error.
  386. */
  387. - (void)testDeleteTokenSuccess {
  388. XCTestExpectation *deleteExpectation =
  389. [self expectationWithDescription:@"Delete handler invoked."];
  390. [self stubKeyPairStoreToReturnValidKeypair];
  391. [self mockAuthServiceToAlwaysReturnValidCheckin];
  392. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  393. #pragma clang diagnostic push
  394. #pragma clang diagnostic ignored "-Wnonnull"
  395. self.deleteTokenCompletion(nil);
  396. #pragma clang diagnostic pop
  397. }] deleteTokenWithAuthorizedEntity:kAuthorizedEntity
  398. scope:kScope
  399. keyPair:[OCMArg any]
  400. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  401. self.deleteTokenCompletion = obj;
  402. return obj != nil;
  403. }]];
  404. [self.instanceID deleteTokenWithAuthorizedEntity:kAuthorizedEntity
  405. scope:kScope
  406. handler:^(NSError *error) {
  407. XCTAssertNil(error);
  408. [deleteExpectation fulfill];
  409. }];
  410. [self waitForExpectationsWithTimeout:1
  411. handler:^(NSError *error) {
  412. XCTAssertNil(error);
  413. }];
  414. }
  415. /**
  416. * Tests that when a token deletion fails, the callback is invoked with an error.
  417. */
  418. - (void)testDeleteTokenFailure {
  419. XCTestExpectation *deleteExpectation =
  420. [self expectationWithDescription:@"Delete handler invoked."];
  421. [self mockAuthServiceToAlwaysReturnValidCheckin];
  422. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  423. NSError *someError = [[NSError alloc] initWithDomain:@"InstanceIDUnitTest" code:0 userInfo:nil];
  424. self.deleteTokenCompletion(someError);
  425. }] deleteTokenWithAuthorizedEntity:kAuthorizedEntity
  426. scope:kScope
  427. keyPair:[OCMArg any]
  428. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  429. self.deleteTokenCompletion = obj;
  430. return obj != nil;
  431. }]];
  432. [self.instanceID deleteTokenWithAuthorizedEntity:kAuthorizedEntity
  433. scope:kScope
  434. handler:^(NSError *error) {
  435. XCTAssertNotNil(error);
  436. [deleteExpectation fulfill];
  437. }];
  438. [self waitForExpectationsWithTimeout:1
  439. handler:^(NSError *error) {
  440. XCTAssertNil(error);
  441. }];
  442. }
  443. /**
  444. * Tests that not having a senderID will fetch a `nil` default token.
  445. */
  446. - (void)testDefaultToken_noSenderID {
  447. _instanceID.fcmSenderID = nil;
  448. XCTAssertNil([self.mockInstanceID token]);
  449. }
  450. /**
  451. * Tests that not having a cached token results in trying to fetch a new default token.
  452. */
  453. - (void)testDefaultToken_noCachedToken {
  454. [[[self.mockTokenManager stub] andReturn:nil]
  455. cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
  456. scope:@"*"];
  457. OCMExpect([self.mockInstanceID defaultTokenWithHandler:nil]);
  458. NSString *token = [self.mockInstanceID token];
  459. XCTAssertNil(token);
  460. [self.mockInstanceID stopMocking];
  461. OCMVerify([self.mockInstanceID defaultTokenWithHandler:nil]);
  462. }
  463. /**
  464. * Tests that when we have a cached default token, calling `getToken` returns that token
  465. * without hitting the network.
  466. */
  467. - (void)testDefaultToken_validCachedToken {
  468. [[[self.mockTokenManager stub] andReturn:sTokenInfo]
  469. cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
  470. scope:@"*"];
  471. [[self.mockInstanceID reject] defaultTokenWithHandler:nil];
  472. NSString *token = [self.mockInstanceID token];
  473. XCTAssertEqualObjects(token, kToken);
  474. }
  475. /**
  476. * Test that when we fetch a new default token and cache it successfully we post a
  477. * tokenRefresh notification which allows to fetch the cached token.
  478. */
  479. - (void)testDefaultTokenFetch_returnValidToken {
  480. XCTestExpectation *defaultTokenExpectation =
  481. [self expectationWithDescription:@"Successfully got default token."];
  482. __block FIRInstanceIDTokenInfo *cachedTokenInfo = nil;
  483. [self stubKeyPairStoreToReturnValidKeypair];
  484. [self mockAuthServiceToAlwaysReturnValidCheckin];
  485. // Mock Token manager to always succeed the token fetch, and return
  486. // a particular cached value.
  487. // Return a dynamic cachedToken variable whenever the cached is checked.
  488. // This uses an invocation-based mock because the |cachedToken| pointer
  489. // will change. Normal stubbing will always return the initial pointer,
  490. // which in this case is 0x0 (nil).
  491. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  492. [invocation setReturnValue:&cachedTokenInfo];
  493. }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
  494. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  495. self.newTokenCompletion(kToken, nil);
  496. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  497. scope:kFIRInstanceIDDefaultTokenScope
  498. keyPair:[OCMArg any]
  499. options:[OCMArg any]
  500. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  501. self.newTokenCompletion = obj;
  502. return obj != nil;
  503. }]];
  504. __block int notificationPostCount = 0;
  505. __block NSString *notificationToken = nil;
  506. NSString *notificationName = kFIRInstanceIDTokenRefreshNotification;
  507. self.tokenRefreshNotificationObserver = [[NSNotificationCenter defaultCenter]
  508. addObserverForName:notificationName
  509. object:nil
  510. queue:nil
  511. usingBlock:^(NSNotification *_Nonnull note) {
  512. // Should have saved token to cache
  513. cachedTokenInfo = sTokenInfo;
  514. notificationPostCount++;
  515. notificationToken = [[self.instanceID token] copy];
  516. [defaultTokenExpectation fulfill];
  517. }];
  518. NSString *token = [self.mockInstanceID token];
  519. [self waitForExpectationsWithTimeout:10.0 handler:nil];
  520. [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
  521. XCTAssertNil(token);
  522. XCTAssertEqualObjects(notificationToken, kToken);
  523. }
  524. /**
  525. * Tests that if we fail to fetch the token from the server for the first time we retry again
  526. * later with exponential backoff unless we succeed.
  527. */
  528. - (void)testDefaultTokenFetch_retryFetchToken {
  529. const int trialsBeforeSuccess = 3;
  530. __block int newTokenFetchCount = 0;
  531. __block int64_t lastFetchTimestampInSeconds;
  532. XCTestExpectation *defaultTokenExpectation =
  533. [self expectationWithDescription:@"Successfully got default token."];
  534. __block FIRInstanceIDTokenInfo *cachedTokenInfo = nil;
  535. [self stubKeyPairStoreToReturnValidKeypair];
  536. [self mockAuthServiceToAlwaysReturnValidCheckin];
  537. // Mock Token manager.
  538. // Return a dynamic cachedToken variable whenever the cached is checked.
  539. // This uses an invocation-based mock because the |cachedToken| pointer
  540. // will change. Normal stubbing will always return the initial pointer,
  541. // which in this case is 0x0 (nil).
  542. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  543. [invocation setReturnValue:&cachedTokenInfo];
  544. }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
  545. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  546. newTokenFetchCount++;
  547. int64_t delaySinceLastFetchInSeconds =
  548. FIRInstanceIDCurrentTimestampInSeconds() - lastFetchTimestampInSeconds;
  549. // Test exponential backoff.
  550. if (newTokenFetchCount > 1) {
  551. XCTAssertLessThanOrEqual(1 << (newTokenFetchCount - 1), delaySinceLastFetchInSeconds);
  552. }
  553. lastFetchTimestampInSeconds = FIRInstanceIDCurrentTimestampInSeconds();
  554. if (newTokenFetchCount < trialsBeforeSuccess) {
  555. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeTimeout];
  556. self.newTokenCompletion(nil, error);
  557. } else {
  558. self.newTokenCompletion(kToken, nil);
  559. }
  560. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  561. scope:kFIRInstanceIDDefaultTokenScope
  562. keyPair:[OCMArg any]
  563. options:[OCMArg any]
  564. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  565. self.newTokenCompletion = obj;
  566. return obj != nil;
  567. }]];
  568. __block int notificationPostCount = 0;
  569. __block NSString *notificationToken = nil;
  570. NSString *notificationName = kFIRInstanceIDTokenRefreshNotification;
  571. self.tokenRefreshNotificationObserver = [[NSNotificationCenter defaultCenter]
  572. addObserverForName:notificationName
  573. object:nil
  574. queue:nil
  575. usingBlock:^(NSNotification *_Nonnull note) {
  576. // Should have saved token to cache
  577. cachedTokenInfo = sTokenInfo;
  578. notificationPostCount++;
  579. notificationToken = [[self.instanceID token] copy];
  580. [defaultTokenExpectation fulfill];
  581. }];
  582. NSString *token = [self.mockInstanceID token];
  583. [self waitForExpectationsWithTimeout:20.0 handler:nil];
  584. [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
  585. XCTAssertNil(token);
  586. XCTAssertEqualObjects(notificationToken, kToken);
  587. XCTAssertEqual(notificationPostCount, 1);
  588. XCTAssertEqual(newTokenFetchCount, trialsBeforeSuccess);
  589. }
  590. /**
  591. * Tests that when we don't have a cached default token multiple invocations to `getToken`
  592. * lead to a single networking call to fetch the token. Also verify that we post one unique
  593. * TokenRefresh notification for multiple invocations.
  594. */
  595. - (void)testDefaultToken_multipleInvocations {
  596. __block int newTokenFetchCount = 0;
  597. XCTestExpectation *defaultTokenExpectation =
  598. [self expectationWithDescription:@"Successfully got default token."];
  599. __block FIRInstanceIDTokenInfo *cachedTokenInfo = nil;
  600. [self stubKeyPairStoreToReturnValidKeypair];
  601. [self mockAuthServiceToAlwaysReturnValidCheckin];
  602. // Mock Token manager.
  603. // Return a dynamic cachedToken variable whenever the cached is checked.
  604. // This uses an invocation-based mock because the |cachedToken| pointer
  605. // will change. Normal stubbing will always return the initial pointer,
  606. // which in this case is 0x0 (nil).
  607. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  608. [invocation setReturnValue:&cachedTokenInfo];
  609. }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
  610. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  611. // Invoke callback after some delay (network delay)
  612. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)),
  613. dispatch_get_main_queue(), ^{
  614. self.newTokenCompletion(kToken, nil);
  615. });
  616. newTokenFetchCount++;
  617. XCTAssertEqual(newTokenFetchCount, 1);
  618. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  619. scope:kFIRInstanceIDDefaultTokenScope
  620. keyPair:[OCMArg any]
  621. options:[OCMArg any]
  622. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  623. self.newTokenCompletion = obj;
  624. return obj != nil;
  625. }]];
  626. __block int notificationPostCount = 0;
  627. __block NSString *notificationToken = nil;
  628. NSString *notificationName = kFIRInstanceIDTokenRefreshNotification;
  629. self.tokenRefreshNotificationObserver = [[NSNotificationCenter defaultCenter]
  630. addObserverForName:notificationName
  631. object:nil
  632. queue:nil
  633. usingBlock:^(NSNotification *_Nonnull note) {
  634. // Should have saved token to cache
  635. cachedTokenInfo = sTokenInfo;
  636. notificationPostCount++;
  637. notificationToken = [[self.instanceID token] copy];
  638. [defaultTokenExpectation fulfill];
  639. }];
  640. NSString *token = [self.mockInstanceID token];
  641. // Invoke get token again with some delay. Our initial request to getToken hasn't yet
  642. // returned from the server.
  643. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
  644. dispatch_get_main_queue(), ^{
  645. XCTAssertNil([self.mockInstanceID token]);
  646. });
  647. // Invoke again after further delay.
  648. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)),
  649. dispatch_get_main_queue(), ^{
  650. XCTAssertNil([self.mockInstanceID token]);
  651. });
  652. [self waitForExpectationsWithTimeout:15.0 handler:nil];
  653. [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
  654. XCTAssertNil(token);
  655. XCTAssertEqualObjects(notificationToken, kToken);
  656. XCTAssertEqual(notificationPostCount, 1);
  657. XCTAssertEqual(newTokenFetchCount, 1);
  658. }
  659. - (void)testDefaultToken_maxRetries {
  660. __block int newTokenFetchCount = 0;
  661. XCTestExpectation *defaultTokenExpectation =
  662. [self expectationWithDescription:@"Did retry maximum times to fetch default token."];
  663. [self stubKeyPairStoreToReturnValidKeypair];
  664. [self mockAuthServiceToAlwaysReturnValidCheckin];
  665. // Mock Token manager.
  666. [[[self.mockTokenManager stub] andReturn:nil]
  667. cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
  668. scope:kFIRInstanceIDDefaultTokenScope];
  669. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  670. newTokenFetchCount++;
  671. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeNetwork];
  672. self.newTokenCompletion(nil, error);
  673. if (newTokenFetchCount == [FIRInstanceID maxRetryCountForDefaultToken]) {
  674. [defaultTokenExpectation fulfill];
  675. }
  676. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  677. scope:kFIRInstanceIDDefaultTokenScope
  678. keyPair:[OCMArg any]
  679. options:[OCMArg any]
  680. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  681. self.newTokenCompletion = obj;
  682. return obj != nil;
  683. }]];
  684. // Mock Instance ID's retry interval to 0, to vastly speed up this test.
  685. [[[self.mockInstanceID stub] andReturnValue:@(0)] retryIntervalToFetchDefaultToken];
  686. // Try to fetch token once. It should set off retries since we mock failure.
  687. NSString *token = [self.mockInstanceID token];
  688. [self waitForExpectationsWithTimeout:1.0 handler:nil];
  689. XCTAssertNil(token);
  690. XCTAssertEqual(newTokenFetchCount, [FIRInstanceID maxRetryCountForDefaultToken]);
  691. }
  692. - (void)testInstanceIDWithHandler_WhileRequesting_Success {
  693. [self stubKeyPairStoreToReturnValidKeypair];
  694. [self mockAuthServiceToAlwaysReturnValidCheckin];
  695. // Expect `fetchNewTokenWithAuthorizedEntity` to be called once
  696. XCTestExpectation *fetchNewTokenExpectation =
  697. [self expectationWithDescription:@"fetchNewTokenExpectation"];
  698. __block FIRInstanceIDTokenHandler tokenHandler;
  699. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  700. [invocation getArgument:&tokenHandler atIndex:6];
  701. [fetchNewTokenExpectation fulfill];
  702. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  703. scope:kFIRInstanceIDDefaultTokenScope
  704. keyPair:[OCMArg any]
  705. options:[OCMArg any]
  706. handler:[OCMArg any]];
  707. // Make 1st call
  708. XCTestExpectation *handlerExpectation1 = [self expectationWithDescription:@"handlerExpectation1"];
  709. FIRInstanceIDResultHandler handler1 =
  710. ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
  711. [handlerExpectation1 fulfill];
  712. XCTAssertNotNil(result);
  713. XCTAssertEqual(result.token, kToken);
  714. XCTAssertNil(error);
  715. };
  716. [self.mockInstanceID instanceIDWithHandler:handler1];
  717. // Make 2nd call
  718. XCTestExpectation *handlerExpectation2 = [self expectationWithDescription:@"handlerExpectation1"];
  719. FIRInstanceIDResultHandler handler2 =
  720. ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
  721. [handlerExpectation2 fulfill];
  722. XCTAssertNotNil(result);
  723. XCTAssertEqual(result.token, kToken);
  724. XCTAssertNil(error);
  725. };
  726. [self.mockInstanceID instanceIDWithHandler:handler2];
  727. // Wait for `fetchNewTokenWithAuthorizedEntity` to be performed
  728. [self waitForExpectations:@[ fetchNewTokenExpectation ] timeout:1 enforceOrder:false];
  729. // Finish token fetch request
  730. tokenHandler(kToken, nil);
  731. // Wait for completion handlers for both calls to be performed
  732. [self waitForExpectationsWithTimeout:1 handler:NULL];
  733. }
  734. - (void)testInstanceIDWithHandler_WhileRequesting_RetrySuccess {
  735. [self stubKeyPairStoreToReturnValidKeypair];
  736. [self mockAuthServiceToAlwaysReturnValidCheckin];
  737. // Expect `fetchNewTokenWithAuthorizedEntity` to be called twice
  738. XCTestExpectation *fetchNewTokenExpectation1 =
  739. [self expectationWithDescription:@"fetchNewTokenExpectation1"];
  740. XCTestExpectation *fetchNewTokenExpectation2 =
  741. [self expectationWithDescription:@"fetchNewTokenExpectation2"];
  742. NSArray *fetchNewTokenExpectations = @[ fetchNewTokenExpectation1, fetchNewTokenExpectation2 ];
  743. __block NSInteger fetchNewTokenCallCount = 0;
  744. __block FIRInstanceIDTokenHandler tokenHandler;
  745. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  746. [invocation getArgument:&tokenHandler atIndex:6];
  747. [fetchNewTokenExpectations[fetchNewTokenCallCount] fulfill];
  748. fetchNewTokenCallCount += 1;
  749. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  750. scope:kFIRInstanceIDDefaultTokenScope
  751. keyPair:[OCMArg any]
  752. options:[OCMArg any]
  753. handler:[OCMArg any]];
  754. // Mock Instance ID's retry interval to 0, to vastly speed up this test.
  755. [[[self.mockInstanceID stub] andReturnValue:@(0)] retryIntervalToFetchDefaultToken];
  756. // Make 1st call
  757. XCTestExpectation *handlerExpectation1 = [self expectationWithDescription:@"handlerExpectation1"];
  758. FIRInstanceIDResultHandler handler1 =
  759. ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
  760. [handlerExpectation1 fulfill];
  761. XCTAssertNotNil(result);
  762. XCTAssertEqual(result.token, kToken);
  763. XCTAssertNil(error);
  764. };
  765. [self.mockInstanceID instanceIDWithHandler:handler1];
  766. // Make 2nd call
  767. XCTestExpectation *handlerExpectation2 = [self expectationWithDescription:@"handlerExpectation1"];
  768. FIRInstanceIDResultHandler handler2 =
  769. ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
  770. [handlerExpectation2 fulfill];
  771. XCTAssertNotNil(result);
  772. XCTAssertEqual(result.token, kToken);
  773. XCTAssertNil(error);
  774. };
  775. [self.mockInstanceID instanceIDWithHandler:handler2];
  776. // Wait for the 1st `fetchNewTokenWithAuthorizedEntity` to be performed
  777. [self waitForExpectations:@[ fetchNewTokenExpectation1 ] timeout:1 enforceOrder:false];
  778. // Fail for the 1st time
  779. tokenHandler(nil, [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeUnknown]);
  780. // Wait for the 2nd token feth
  781. [self waitForExpectations:@[ fetchNewTokenExpectation2 ] timeout:1 enforceOrder:false];
  782. // Finish with success
  783. tokenHandler(kToken, nil);
  784. // Wait for completion handlers for both calls to be performed
  785. [self waitForExpectationsWithTimeout:1 handler:NULL];
  786. }
  787. - (void)testInstanceIDWithHandler_WhileRequesting_RetryFailure {
  788. [self stubKeyPairStoreToReturnValidKeypair];
  789. [self mockAuthServiceToAlwaysReturnValidCheckin];
  790. // Expect `fetchNewTokenWithAuthorizedEntity` to be called once
  791. NSMutableArray<XCTestExpectation *> *fetchNewTokenExpectations = [NSMutableArray array];
  792. for (NSInteger i = 0; i < [[self.instanceID class] maxRetryCountForDefaultToken]; ++i) {
  793. NSString *name = [NSString stringWithFormat:@"fetchNewTokenExpectation-%ld", (long)i];
  794. [fetchNewTokenExpectations addObject:[self expectationWithDescription:name]];
  795. }
  796. __block NSInteger fetchNewTokenCallCount = 0;
  797. __block FIRInstanceIDTokenHandler tokenHandler;
  798. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  799. [invocation getArgument:&tokenHandler atIndex:6];
  800. [fetchNewTokenExpectations[fetchNewTokenCallCount] fulfill];
  801. fetchNewTokenCallCount += 1;
  802. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  803. scope:kFIRInstanceIDDefaultTokenScope
  804. keyPair:[OCMArg any]
  805. options:[OCMArg any]
  806. handler:[OCMArg any]];
  807. // Mock Instance ID's retry interval to 0, to vastly speed up this test.
  808. [[[self.mockInstanceID stub] andReturnValue:@(0)] retryIntervalToFetchDefaultToken];
  809. // Make 1st call
  810. XCTestExpectation *handlerExpectation1 = [self expectationWithDescription:@"handlerExpectation1"];
  811. FIRInstanceIDResultHandler handler1 =
  812. ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
  813. [handlerExpectation1 fulfill];
  814. XCTAssertNil(result);
  815. XCTAssertNotNil(error);
  816. };
  817. [self.mockInstanceID instanceIDWithHandler:handler1];
  818. // Make 2nd call
  819. XCTestExpectation *handlerExpectation2 = [self expectationWithDescription:@"handlerExpectation1"];
  820. FIRInstanceIDResultHandler handler2 =
  821. ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
  822. [handlerExpectation2 fulfill];
  823. XCTAssertNil(result);
  824. XCTAssertNotNil(error);
  825. };
  826. [self.mockInstanceID instanceIDWithHandler:handler2];
  827. for (NSInteger i = 0; i < [[self.instanceID class] maxRetryCountForDefaultToken]; ++i) {
  828. // Wait for the i `fetchNewTokenWithAuthorizedEntity` to be performed
  829. [self waitForExpectations:@[ fetchNewTokenExpectations[i] ] timeout:1 enforceOrder:false];
  830. // Fail for the i time
  831. tokenHandler(nil, [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeUnknown]);
  832. }
  833. // Wait for completion handlers for both calls to be performed
  834. [self waitForExpectationsWithTimeout:1 handler:NULL];
  835. }
  836. /**
  837. * Tests a Keychain read failure while we try to fetch a new InstanceID token. If the Keychain
  838. * read fails we won't be able to fetch the public key which is required while fetching a new
  839. * token. In such a case we should return KeyPair failure.
  840. */
  841. - (void)testNewTokenFetch_keyChainError {
  842. XCTestExpectation *tokenExpectation =
  843. [self expectationWithDescription:@"New token handler invoked."];
  844. [self mockAuthServiceToAlwaysReturnValidCheckin];
  845. // Simulate keypair fetch/generation failure.
  846. [[[self.mockKeyPairStore stub] andReturn:nil] loadKeyPairWithError:[OCMArg anyObjectRef]];
  847. [[self.mockTokenManager reject] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  848. scope:kScope
  849. keyPair:[OCMArg any]
  850. options:[OCMArg any]
  851. handler:[OCMArg any]];
  852. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  853. scope:kScope
  854. options:nil
  855. handler:^(NSString *token, NSError *error) {
  856. XCTAssertNil(token);
  857. XCTAssertNotNil(error);
  858. [tokenExpectation fulfill];
  859. }];
  860. [self waitForExpectationsWithTimeout:1 handler:nil];
  861. OCMVerifyAll(self.mockTokenManager);
  862. }
  863. /**
  864. * If a token fetch includes in its options an "apns_token" object, but not a "apns_sandbox" key,
  865. * ensure that an "apns_sandbox" key is added to the token options (via automatic detection).
  866. */
  867. - (void)testTokenFetchAPNSServerTypeIsIncludedIfAPNSTokenProvided {
  868. XCTestExpectation *apnsServerTypeExpectation =
  869. [self expectationWithDescription:@"apns_sandbox key was included in token options"];
  870. [self stubKeyPairStoreToReturnValidKeypair];
  871. [self mockAuthServiceToAlwaysReturnValidCheckin];
  872. NSData *apnsToken = [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding];
  873. // Option is purposefully missing the apns_sandbox key
  874. NSDictionary *tokenOptions = @{kFIRInstanceIDTokenOptionsAPNSKey : apnsToken};
  875. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  876. // Inspect
  877. NSDictionary *options;
  878. [invocation getArgument:&options atIndex:5];
  879. if (options[kFIRInstanceIDTokenOptionsAPNSIsSandboxKey] != nil) {
  880. [apnsServerTypeExpectation fulfill];
  881. }
  882. self.newTokenCompletion(kToken, nil);
  883. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  884. scope:kScope
  885. keyPair:[OCMArg any]
  886. options:[OCMArg any]
  887. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  888. self.newTokenCompletion = obj;
  889. return obj != nil;
  890. }]];
  891. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  892. scope:kScope
  893. options:tokenOptions
  894. handler:^(NSString *token, NSError *error){
  895. }];
  896. [self waitForExpectationsWithTimeout:60.0
  897. handler:^(NSError *error) {
  898. XCTAssertNil(error);
  899. }];
  900. }
  901. /**
  902. * Tests that if a token was fetched, but during the fetch the APNs data was set, that a new
  903. * token is fetched to associate the APNs data, and is not returned from the cache.
  904. */
  905. - (void)testTokenFetch_ignoresCacheIfAPNSInfoDifferent {
  906. XCTestExpectation *tokenRequestExpectation =
  907. [self expectationWithDescription:@"Token was fetched from the network"];
  908. // Initialize a token in the cache *WITHOUT* APNSInfo
  909. // This token is |kToken|, but we will simulate that a fetch will return another token
  910. NSString *oldCachedToken = kToken;
  911. NSString *fetchedToken = @"abcd123_newtoken";
  912. __block FIRInstanceIDTokenInfo *cachedTokenInfo =
  913. [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
  914. scope:kFIRInstanceIDDefaultTokenScope
  915. token:oldCachedToken
  916. appVersion:@"1.0"
  917. firebaseAppID:@"firebaseAppID"];
  918. [self stubKeyPairStoreToReturnValidKeypair];
  919. [self mockAuthServiceToAlwaysReturnValidCheckin];
  920. // During this test use the default scope ("*") to simulate the default token behavior.
  921. // Return a dynamic cachedToken variable whenever the cached is checked.
  922. // This uses an invocation-based mock because the |cachedToken| pointer
  923. // will change. Normal stubbing will always return the initial pointer,
  924. // which in this case is 0x0 (nil).
  925. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  926. [invocation setReturnValue:&cachedTokenInfo];
  927. }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
  928. // Mock the network request to return |fetchedToken|, so we can clearly see if the token is
  929. // is different than what was cached.
  930. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  931. [tokenRequestExpectation fulfill];
  932. self.newTokenCompletion(fetchedToken, nil);
  933. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  934. scope:kFIRInstanceIDDefaultTokenScope
  935. keyPair:[OCMArg any]
  936. options:[OCMArg any]
  937. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  938. self.newTokenCompletion = obj;
  939. return obj != nil;
  940. }]];
  941. // Begin request
  942. // Token options has APNS data, which is not associated with the cached token
  943. NSDictionary *tokenOptions = @{
  944. kFIRInstanceIDTokenOptionsAPNSKey : [@"apns" dataUsingEncoding:NSUTF8StringEncoding],
  945. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(NO)
  946. };
  947. [self.instanceID
  948. tokenWithAuthorizedEntity:kAuthorizedEntity
  949. scope:kFIRInstanceIDDefaultTokenScope
  950. options:tokenOptions
  951. handler:^(NSString *_Nullable token, NSError *_Nullable error) {
  952. XCTAssertEqualObjects(token, fetchedToken);
  953. }];
  954. [self waitForExpectationsWithTimeout:0.5 handler:nil];
  955. }
  956. /**
  957. * Tests that if there is a keychain failure while fetching the InstanceID of the token we should
  958. * return nil for the identity.
  959. */
  960. - (void)testInstanceIDFetch_keyChainError {
  961. XCTestExpectation *tokenExpectation =
  962. [self expectationWithDescription:@"InstanceID fetch handler invoked."];
  963. // Simulate keypair fetch/generation failure.
  964. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  965. [[[self.mockKeyPairStore stub] andReturn:nil] appIdentityWithError:[OCMArg setTo:error]];
  966. [self.instanceID getIDWithHandler:^(NSString *_Nullable identity, NSError *_Nullable error) {
  967. XCTAssertNil(identity);
  968. XCTAssertNotNil(error);
  969. [tokenExpectation fulfill];
  970. }];
  971. [self waitForExpectationsWithTimeout:1 handler:nil];
  972. }
  973. - (void)testInstanceIDDelete_keyChainError {
  974. XCTestExpectation *tokenExpectation =
  975. [self expectationWithDescription:@"InstanceID deleteID handler invoked."];
  976. // Simulate keypair fetch/generation failure.
  977. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  978. [[[self.mockKeyPairStore stub] andReturn:nil] appIdentityWithError:[OCMArg setTo:error]];
  979. [self.instanceID deleteIDWithHandler:^(NSError *_Nullable error) {
  980. XCTAssertNotNil(error);
  981. [tokenExpectation fulfill];
  982. }];
  983. [self waitForExpectationsWithTimeout:1 handler:nil];
  984. }
  985. #pragma mark - Private Helpers
  986. - (void)stubKeyPairStoreToReturnValidKeypair {
  987. [[[self.mockKeyPairStore stub] andReturn:[self createValidMockKeypair]]
  988. loadKeyPairWithError:[OCMArg anyObjectRef]];
  989. }
  990. - (id)createValidMockKeypair {
  991. id mockKeypair = OCMClassMock([FIRInstanceIDKeyPair class]);
  992. [[[mockKeypair stub] andReturnValue:@YES] isValid];
  993. return mockKeypair;
  994. }
  995. - (FIRInstanceIDCheckinPreferences *)validCheckinPreferences {
  996. NSDictionary *gservicesData = @{
  997. kFIRInstanceIDVersionInfoStringKey : kVersionInfo,
  998. kFIRInstanceIDLastCheckinTimeKey : @(FIRInstanceIDCurrentTimestampInMilliseconds())
  999. };
  1000. FIRInstanceIDCheckinPreferences *checkinPreferences =
  1001. [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kDeviceAuthId
  1002. secretToken:kSecretToken];
  1003. [checkinPreferences updateWithCheckinPlistContents:gservicesData];
  1004. return checkinPreferences;
  1005. }
  1006. - (void)mockAuthServiceToAlwaysReturnValidCheckin {
  1007. FIRInstanceIDCheckinPreferences *validCheckin = [self validCheckinPreferences];
  1008. __block FIRInstanceIDDeviceCheckinCompletion checkinHandler;
  1009. [[[self.mockAuthService stub] andDo:^(NSInvocation *invocation) {
  1010. if (checkinHandler) {
  1011. checkinHandler(validCheckin, nil);
  1012. }
  1013. }] fetchCheckinInfoWithHandler:[OCMArg checkWithBlock:^BOOL(id obj) {
  1014. return (checkinHandler = obj) != nil;
  1015. }]];
  1016. }
  1017. @end