FIRInstanceIDTest.m 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  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 = @"12345678: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 kVersionInfo = @"1.0";
  40. // FIRApp configuration.
  41. static NSString *const kGCMSenderID = @"correct_gcm_sender_id";
  42. static NSString *const kGoogleAppID = @"1:123:ios:123abc";
  43. @interface FIRInstanceID (ExposedForTest)
  44. @property(nonatomic, readwrite, strong) FIRInstanceIDTokenManager *tokenManager;
  45. @property(nonatomic, readwrite, strong) FIRInstanceIDKeyPairStore *keyPairStore;
  46. @property(nonatomic, readwrite, copy) NSString *fcmSenderID;
  47. - (NSInteger)retryIntervalToFetchDefaultToken;
  48. - (BOOL)isFCMAutoInitEnabled;
  49. - (void)didCompleteConfigure;
  50. - (NSString *)cachedTokenIfAvailable;
  51. - (void)deleteIdentityWithHandler:(FIRInstanceIDDeleteHandler)handler;
  52. + (FIRInstanceID *)instanceIDForTests;
  53. - (void)defaultTokenWithHandler:(FIRInstanceIDTokenHandler)handler;
  54. - (instancetype)initPrivately;
  55. - (void)start;
  56. + (int64_t)maxRetryCountForDefaultToken;
  57. + (int64_t)minIntervalForDefaultTokenRetry;
  58. + (int64_t)maxRetryIntervalForDefaultTokenInSeconds;
  59. @end
  60. @interface FIRInstanceIDTest : XCTestCase
  61. @property(nonatomic, readwrite, assign) BOOL hasCheckinInfo;
  62. @property(nonatomic, readwrite, strong) FIRInstanceID *instanceID;
  63. @property(nonatomic, readwrite, strong) id mockInstanceID;
  64. @property(nonatomic, readwrite, strong) id mockTokenManager;
  65. @property(nonatomic, readwrite, strong) id mockKeyPairStore;
  66. @property(nonatomic, readwrite, strong) id mockAuthService;
  67. @property(nonatomic, readwrite, strong) id<NSObject> tokenRefreshNotificationObserver;
  68. @property(nonatomic, readwrite, copy) FIRInstanceIDTokenHandler newTokenCompletion;
  69. @property(nonatomic, readwrite, copy) FIRInstanceIDDeleteTokenHandler deleteTokenCompletion;
  70. @end
  71. @implementation FIRInstanceIDTest
  72. - (void)setUp {
  73. [super setUp];
  74. _instanceID = [[FIRInstanceID alloc] initPrivately];
  75. [_instanceID start];
  76. if (!sTokenInfo) {
  77. sTokenInfo = [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
  78. scope:kScope
  79. token:kToken
  80. appVersion:nil
  81. firebaseAppID:nil];
  82. sTokenInfo.cacheTime = [NSDate date];
  83. }
  84. [self mockInstanceIDObjects];
  85. }
  86. - (void)tearDown {
  87. [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
  88. self.instanceID = nil;
  89. self.mockTokenManager = nil;
  90. self.mockInstanceID = nil;
  91. [super tearDown];
  92. }
  93. - (void)mockInstanceIDObjects {
  94. // Mock that we have valid checkin info. Individual tests can override this.
  95. self.hasCheckinInfo = YES;
  96. self.mockAuthService = OCMClassMock([FIRInstanceIDAuthService class]);
  97. [[[self.mockAuthService stub] andDo:^(NSInvocation *invocation) {
  98. [invocation setReturnValue:&self->_hasCheckinInfo];
  99. }] hasValidCheckinInfo];
  100. self.mockTokenManager = OCMClassMock([FIRInstanceIDTokenManager class]);
  101. [[[self.mockTokenManager stub] andReturn:self.mockAuthService] authService];
  102. self.mockKeyPairStore = OCMClassMock([FIRInstanceIDKeyPairStore class]);
  103. _instanceID.fcmSenderID = kAuthorizedEntity;
  104. self.mockInstanceID = OCMPartialMock(_instanceID);
  105. [self.mockInstanceID setTokenManager:self.mockTokenManager];
  106. [self.mockInstanceID setKeyPairStore:self.mockKeyPairStore];
  107. id instanceIDClassMock = OCMClassMock([FIRInstanceID class]);
  108. OCMStub(ClassMethod([instanceIDClassMock minIntervalForDefaultTokenRetry])).andReturn(2);
  109. OCMStub(ClassMethod([instanceIDClassMock maxRetryIntervalForDefaultTokenInSeconds]))
  110. .andReturn(10);
  111. }
  112. /**
  113. * Tests that the FIRInstanceID's sharedInstance class method produces an instance of
  114. * FIRInstanceID with an associated FIRInstanceIDTokenManager.
  115. */
  116. - (void)testSharedInstance {
  117. // The shared instance should be `nil` before the app is configured.
  118. XCTAssertNil([FIRInstanceID instanceID]);
  119. // The shared instance relies on the default app being configured. Configure it.
  120. FIROptions *options = [[FIROptions alloc] initWithGoogleAppID:kGoogleAppID
  121. GCMSenderID:kGCMSenderID];
  122. [FIRApp configureWithName:kFIRDefaultAppName options:options];
  123. FIRInstanceID *instanceID = [FIRInstanceID instanceID];
  124. XCTAssertNotNil(instanceID);
  125. XCTAssertNotNil(instanceID.tokenManager);
  126. // Ensure a second call returns the same instance as the first.
  127. FIRInstanceID *secondInstanceID = [FIRInstanceID instanceID];
  128. XCTAssertEqualObjects(instanceID, secondInstanceID);
  129. // Reset the default app for the next test.
  130. [FIRApp resetApps];
  131. }
  132. - (void)testFCMAutoInitEnabled {
  133. XCTAssertFalse([_instanceID isFCMAutoInitEnabled],
  134. @"When FCM is not available, FCM Auto Init Enabled should be NO.");
  135. }
  136. - (void)testTokenShouldBeRefreshedIfCacheTokenNeedsToBeRefreshed {
  137. [[[self.mockInstanceID stub] andReturn:kToken] cachedTokenIfAvailable];
  138. [[[self.mockTokenManager stub] andReturnValue:@(YES)]
  139. checkTokenRefreshPolicyWithIID:[OCMArg any]];
  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 = nil;
  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. XCTAssertNil([self.mockInstanceID token]);
  459. [self.mockInstanceID stopMocking];
  460. OCMVerify([self.mockInstanceID defaultTokenWithHandler:nil]);
  461. }
  462. /**
  463. * Tests that when we have a cached default token, calling `getToken` returns that token
  464. * without hitting the network.
  465. */
  466. - (void)testDefaultToken_validCachedToken {
  467. [[[self.mockTokenManager stub] andReturn:sTokenInfo]
  468. cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
  469. scope:@"*"];
  470. [[self.mockInstanceID reject] defaultTokenWithHandler:nil];
  471. XCTAssertEqualObjects([self.mockInstanceID token], kToken);
  472. }
  473. /**
  474. * Tests that the callback handler will be invoked when the default token is fetched
  475. * despite the token being unchanged.
  476. */
  477. - (void)testDefaultToken_callbackInvokedForUnchangedToken {
  478. XCTestExpectation *defaultTokenExpectation =
  479. [self expectationWithDescription:@"Token fetch was successful."];
  480. __block FIRInstanceIDTokenInfo *cachedTokenInfo = nil;
  481. [self stubKeyPairStoreToReturnValidKeypair];
  482. [self mockAuthServiceToAlwaysReturnValidCheckin];
  483. // Mock Token manager to always succeed the token fetch, and return
  484. // a particular cached value.
  485. // Return a dynamic cachedToken variable whenever the cached is checked.
  486. // This uses an invocation-based mock because the |cachedToken| pointer
  487. // will change. Normal stubbing will always return the initial pointer,
  488. // which in this case is 0x0 (nil).
  489. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  490. [invocation setReturnValue:&cachedTokenInfo];
  491. }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
  492. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  493. self.newTokenCompletion(kToken, nil);
  494. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  495. scope:kFIRInstanceIDDefaultTokenScope
  496. keyPair:[OCMArg any]
  497. options:[OCMArg any]
  498. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  499. self.newTokenCompletion = obj;
  500. return obj != nil;
  501. }]];
  502. __block NSInteger notificationPostCount = 0;
  503. __block NSString *notificationToken = nil;
  504. // Fetch token once to store token state
  505. NSString *notificationName = kFIRInstanceIDTokenRefreshNotification;
  506. self.tokenRefreshNotificationObserver = [[NSNotificationCenter defaultCenter]
  507. addObserverForName:notificationName
  508. object:nil
  509. queue:nil
  510. usingBlock:^(NSNotification *_Nonnull note) {
  511. // Should have saved token to cache
  512. cachedTokenInfo = sTokenInfo;
  513. notificationPostCount++;
  514. notificationToken = [[self.instanceID token] copy];
  515. [defaultTokenExpectation fulfill];
  516. }];
  517. XCTAssertNil([self.mockInstanceID token]);
  518. [self waitForExpectationsWithTimeout:10.0 handler:nil];
  519. [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
  520. XCTAssertEqualObjects(notificationToken, kToken);
  521. // Fetch default handler again without any token changes
  522. XCTestExpectation *tokenCallback = [self expectationWithDescription:@"Callback was invoked."];
  523. [self.mockInstanceID defaultTokenWithHandler:^(NSString *token, NSError *error) {
  524. notificationToken = token;
  525. [tokenCallback fulfill];
  526. }];
  527. [self waitForExpectationsWithTimeout:10.0 handler:nil];
  528. XCTAssertEqualObjects(notificationToken, kToken);
  529. }
  530. /**
  531. * Test that when we fetch a new default token and cache it successfully we post a
  532. * tokenRefresh notification which allows to fetch the cached token.
  533. */
  534. - (void)testDefaultTokenFetch_returnValidToken {
  535. XCTestExpectation *defaultTokenExpectation =
  536. [self expectationWithDescription:@"Successfully got default token."];
  537. __block FIRInstanceIDTokenInfo *cachedTokenInfo = nil;
  538. [self stubKeyPairStoreToReturnValidKeypair];
  539. [self mockAuthServiceToAlwaysReturnValidCheckin];
  540. // Mock Token manager to always succeed the token fetch, and return
  541. // a particular cached value.
  542. // Return a dynamic cachedToken variable whenever the cached is checked.
  543. // This uses an invocation-based mock because the |cachedToken| pointer
  544. // will change. Normal stubbing will always return the initial pointer,
  545. // which in this case is 0x0 (nil).
  546. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  547. [invocation setReturnValue:&cachedTokenInfo];
  548. }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
  549. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  550. self.newTokenCompletion(kToken, nil);
  551. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  552. scope:kFIRInstanceIDDefaultTokenScope
  553. keyPair:[OCMArg any]
  554. options:[OCMArg any]
  555. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  556. self.newTokenCompletion = obj;
  557. return obj != nil;
  558. }]];
  559. __block int notificationPostCount = 0;
  560. __block NSString *notificationToken = nil;
  561. NSString *notificationName = kFIRInstanceIDTokenRefreshNotification;
  562. self.tokenRefreshNotificationObserver = [[NSNotificationCenter defaultCenter]
  563. addObserverForName:notificationName
  564. object:nil
  565. queue:nil
  566. usingBlock:^(NSNotification *_Nonnull note) {
  567. // Should have saved token to cache
  568. cachedTokenInfo = sTokenInfo;
  569. notificationPostCount++;
  570. notificationToken = [[self.instanceID token] copy];
  571. [defaultTokenExpectation fulfill];
  572. }];
  573. XCTAssertNil([self.mockInstanceID token]);
  574. [self waitForExpectationsWithTimeout:10.0 handler:nil];
  575. [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
  576. XCTAssertEqualObjects(notificationToken, kToken);
  577. }
  578. /**
  579. * Tests that if we fail to fetch the token from the server for the first time we retry again
  580. * later with exponential backoff unless we succeed.
  581. */
  582. - (void)testDefaultTokenFetch_retryFetchToken {
  583. const int trialsBeforeSuccess = 3;
  584. __block int newTokenFetchCount = 0;
  585. __block int64_t lastFetchTimestampInSeconds;
  586. XCTestExpectation *defaultTokenExpectation =
  587. [self expectationWithDescription:@"Successfully got default token."];
  588. __block FIRInstanceIDTokenInfo *cachedTokenInfo = nil;
  589. [self stubKeyPairStoreToReturnValidKeypair];
  590. [self mockAuthServiceToAlwaysReturnValidCheckin];
  591. // Mock Token manager.
  592. // Return a dynamic cachedToken variable whenever the cached is checked.
  593. // This uses an invocation-based mock because the |cachedToken| pointer
  594. // will change. Normal stubbing will always return the initial pointer,
  595. // which in this case is 0x0 (nil).
  596. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  597. [invocation setReturnValue:&cachedTokenInfo];
  598. }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
  599. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  600. newTokenFetchCount++;
  601. int64_t delaySinceLastFetchInSeconds =
  602. FIRInstanceIDCurrentTimestampInSeconds() - lastFetchTimestampInSeconds;
  603. // Test exponential backoff.
  604. if (newTokenFetchCount > 1) {
  605. XCTAssertLessThanOrEqual(1 << (newTokenFetchCount - 1), delaySinceLastFetchInSeconds);
  606. }
  607. lastFetchTimestampInSeconds = FIRInstanceIDCurrentTimestampInSeconds();
  608. if (newTokenFetchCount < trialsBeforeSuccess) {
  609. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeTimeout];
  610. self.newTokenCompletion(nil, error);
  611. } else {
  612. self.newTokenCompletion(kToken, nil);
  613. }
  614. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  615. scope:kFIRInstanceIDDefaultTokenScope
  616. keyPair:[OCMArg any]
  617. options:[OCMArg any]
  618. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  619. self.newTokenCompletion = obj;
  620. return obj != nil;
  621. }]];
  622. __block int notificationPostCount = 0;
  623. __block NSString *notificationToken = nil;
  624. NSString *notificationName = kFIRInstanceIDTokenRefreshNotification;
  625. self.tokenRefreshNotificationObserver = [[NSNotificationCenter defaultCenter]
  626. addObserverForName:notificationName
  627. object:nil
  628. queue:nil
  629. usingBlock:^(NSNotification *_Nonnull note) {
  630. // Should have saved token to cache
  631. cachedTokenInfo = sTokenInfo;
  632. notificationPostCount++;
  633. notificationToken = [[self.instanceID token] copy];
  634. [defaultTokenExpectation fulfill];
  635. }];
  636. XCTAssertNil([self.mockInstanceID token]);
  637. [self waitForExpectationsWithTimeout:20.0 handler:nil];
  638. [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
  639. XCTAssertEqualObjects(notificationToken, kToken);
  640. XCTAssertEqual(notificationPostCount, 1);
  641. XCTAssertEqual(newTokenFetchCount, trialsBeforeSuccess);
  642. }
  643. /**
  644. * Tests that when we don't have a cached default token multiple invocations to `getToken`
  645. * lead to a single networking call to fetch the token. Also verify that we post one unique
  646. * TokenRefresh notification for multiple invocations.
  647. */
  648. - (void)testDefaultToken_multipleInvocations {
  649. __block int newTokenFetchCount = 0;
  650. XCTestExpectation *defaultTokenExpectation =
  651. [self expectationWithDescription:@"Successfully got default token."];
  652. __block FIRInstanceIDTokenInfo *cachedTokenInfo = nil;
  653. [self stubKeyPairStoreToReturnValidKeypair];
  654. [self mockAuthServiceToAlwaysReturnValidCheckin];
  655. // Mock Token manager.
  656. // Return a dynamic cachedToken variable whenever the cached is checked.
  657. // This uses an invocation-based mock because the |cachedToken| pointer
  658. // will change. Normal stubbing will always return the initial pointer,
  659. // which in this case is 0x0 (nil).
  660. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  661. [invocation setReturnValue:&cachedTokenInfo];
  662. }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
  663. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  664. // Invoke callback after some delay (network delay)
  665. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)),
  666. dispatch_get_main_queue(), ^{
  667. self.newTokenCompletion(kToken, nil);
  668. });
  669. newTokenFetchCount++;
  670. XCTAssertEqual(newTokenFetchCount, 1);
  671. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  672. scope:kFIRInstanceIDDefaultTokenScope
  673. keyPair:[OCMArg any]
  674. options:[OCMArg any]
  675. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  676. self.newTokenCompletion = obj;
  677. return obj != nil;
  678. }]];
  679. __block int notificationPostCount = 0;
  680. __block NSString *notificationToken = nil;
  681. NSString *notificationName = kFIRInstanceIDTokenRefreshNotification;
  682. self.tokenRefreshNotificationObserver = [[NSNotificationCenter defaultCenter]
  683. addObserverForName:notificationName
  684. object:nil
  685. queue:nil
  686. usingBlock:^(NSNotification *_Nonnull note) {
  687. // Should have saved token to cache
  688. cachedTokenInfo = sTokenInfo;
  689. notificationPostCount++;
  690. notificationToken = [[self.instanceID token] copy];
  691. [defaultTokenExpectation fulfill];
  692. }];
  693. XCTAssertNil([self.mockInstanceID token]);
  694. // Invoke get token again with some delay. Our initial request to getToken hasn't yet
  695. // returned from the server.
  696. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
  697. dispatch_get_main_queue(), ^{
  698. XCTAssertNil([self.mockInstanceID token]);
  699. });
  700. // Invoke again after further delay.
  701. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)),
  702. dispatch_get_main_queue(), ^{
  703. XCTAssertNil([self.mockInstanceID token]);
  704. });
  705. [self waitForExpectationsWithTimeout:15.0 handler:nil];
  706. [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
  707. XCTAssertEqualObjects(notificationToken, kToken);
  708. XCTAssertEqual(notificationPostCount, 1);
  709. XCTAssertEqual(newTokenFetchCount, 1);
  710. }
  711. - (void)testDefaultToken_maxRetries {
  712. __block int newTokenFetchCount = 0;
  713. XCTestExpectation *defaultTokenExpectation =
  714. [self expectationWithDescription:@"Did retry maximum times to fetch default token."];
  715. [self stubKeyPairStoreToReturnValidKeypair];
  716. [self mockAuthServiceToAlwaysReturnValidCheckin];
  717. // Mock Token manager.
  718. [[[self.mockTokenManager stub] andReturn:nil]
  719. cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
  720. scope:kFIRInstanceIDDefaultTokenScope];
  721. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  722. newTokenFetchCount++;
  723. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeNetwork];
  724. self.newTokenCompletion(nil, error);
  725. if (newTokenFetchCount == [FIRInstanceID maxRetryCountForDefaultToken]) {
  726. [defaultTokenExpectation fulfill];
  727. }
  728. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  729. scope:kFIRInstanceIDDefaultTokenScope
  730. keyPair:[OCMArg any]
  731. options:[OCMArg any]
  732. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  733. self.newTokenCompletion = obj;
  734. return obj != nil;
  735. }]];
  736. // Mock Instance ID's retry interval to 0, to vastly speed up this test.
  737. [[[self.mockInstanceID stub] andReturnValue:@(0)] retryIntervalToFetchDefaultToken];
  738. // Try to fetch token once. It should set off retries since we mock failure.
  739. XCTAssertNil([self.mockInstanceID token]);
  740. [self waitForExpectationsWithTimeout:1.0 handler:nil];
  741. XCTAssertEqual(newTokenFetchCount, [FIRInstanceID maxRetryCountForDefaultToken]);
  742. }
  743. - (void)testInstanceIDWithHandler_WhileRequesting_Success {
  744. [self stubKeyPairStoreToReturnValidKeypair];
  745. [self mockAuthServiceToAlwaysReturnValidCheckin];
  746. // Expect `fetchNewTokenWithAuthorizedEntity` to be called once
  747. XCTestExpectation *fetchNewTokenExpectation =
  748. [self expectationWithDescription:@"fetchNewTokenExpectation"];
  749. __block FIRInstanceIDTokenHandler tokenHandler;
  750. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  751. [invocation getArgument:&tokenHandler atIndex:6];
  752. [fetchNewTokenExpectation fulfill];
  753. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  754. scope:kFIRInstanceIDDefaultTokenScope
  755. keyPair:[OCMArg any]
  756. options:[OCMArg any]
  757. handler:[OCMArg any]];
  758. // Make 1st call
  759. XCTestExpectation *handlerExpectation1 = [self expectationWithDescription:@"handlerExpectation1"];
  760. FIRInstanceIDResultHandler handler1 =
  761. ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
  762. [handlerExpectation1 fulfill];
  763. XCTAssertNotNil(result);
  764. XCTAssertEqual(result.token, kToken);
  765. XCTAssertNil(error);
  766. };
  767. [self.mockInstanceID instanceIDWithHandler:handler1];
  768. // Make 2nd call
  769. XCTestExpectation *handlerExpectation2 = [self expectationWithDescription:@"handlerExpectation1"];
  770. FIRInstanceIDResultHandler handler2 =
  771. ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
  772. [handlerExpectation2 fulfill];
  773. XCTAssertNotNil(result);
  774. XCTAssertEqual(result.token, kToken);
  775. XCTAssertNil(error);
  776. };
  777. [self.mockInstanceID instanceIDWithHandler:handler2];
  778. // Wait for `fetchNewTokenWithAuthorizedEntity` to be performed
  779. [self waitForExpectations:@[ fetchNewTokenExpectation ] timeout:1 enforceOrder:false];
  780. // Finish token fetch request
  781. tokenHandler(kToken, nil);
  782. // Wait for completion handlers for both calls to be performed
  783. [self waitForExpectationsWithTimeout:1 handler:NULL];
  784. }
  785. - (void)testInstanceIDWithHandler_WhileRequesting_RetrySuccess {
  786. [self stubKeyPairStoreToReturnValidKeypair];
  787. [self mockAuthServiceToAlwaysReturnValidCheckin];
  788. // Expect `fetchNewTokenWithAuthorizedEntity` to be called twice
  789. XCTestExpectation *fetchNewTokenExpectation1 =
  790. [self expectationWithDescription:@"fetchNewTokenExpectation1"];
  791. XCTestExpectation *fetchNewTokenExpectation2 =
  792. [self expectationWithDescription:@"fetchNewTokenExpectation2"];
  793. NSArray *fetchNewTokenExpectations = @[ fetchNewTokenExpectation1, fetchNewTokenExpectation2 ];
  794. __block NSInteger fetchNewTokenCallCount = 0;
  795. __block FIRInstanceIDTokenHandler tokenHandler;
  796. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  797. [invocation getArgument:&tokenHandler atIndex:6];
  798. [fetchNewTokenExpectations[fetchNewTokenCallCount] fulfill];
  799. fetchNewTokenCallCount += 1;
  800. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  801. scope:kFIRInstanceIDDefaultTokenScope
  802. keyPair:[OCMArg any]
  803. options:[OCMArg any]
  804. handler:[OCMArg any]];
  805. // Mock Instance ID's retry interval to 0, to vastly speed up this test.
  806. [[[self.mockInstanceID stub] andReturnValue:@(0)] retryIntervalToFetchDefaultToken];
  807. // Make 1st call
  808. XCTestExpectation *handlerExpectation1 = [self expectationWithDescription:@"handlerExpectation1"];
  809. FIRInstanceIDResultHandler handler1 =
  810. ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
  811. [handlerExpectation1 fulfill];
  812. XCTAssertNotNil(result);
  813. XCTAssertEqual(result.token, kToken);
  814. XCTAssertNil(error);
  815. };
  816. [self.mockInstanceID instanceIDWithHandler:handler1];
  817. // Make 2nd call
  818. XCTestExpectation *handlerExpectation2 = [self expectationWithDescription:@"handlerExpectation1"];
  819. FIRInstanceIDResultHandler handler2 =
  820. ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
  821. [handlerExpectation2 fulfill];
  822. XCTAssertNotNil(result);
  823. XCTAssertEqual(result.token, kToken);
  824. XCTAssertNil(error);
  825. };
  826. [self.mockInstanceID instanceIDWithHandler:handler2];
  827. // Wait for the 1st `fetchNewTokenWithAuthorizedEntity` to be performed
  828. [self waitForExpectations:@[ fetchNewTokenExpectation1 ] timeout:1 enforceOrder:false];
  829. // Fail for the 1st time
  830. tokenHandler(nil, [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeUnknown]);
  831. // Wait for the 2nd token feth
  832. [self waitForExpectations:@[ fetchNewTokenExpectation2 ] timeout:1 enforceOrder:false];
  833. // Finish with success
  834. tokenHandler(kToken, nil);
  835. // Wait for completion handlers for both calls to be performed
  836. [self waitForExpectationsWithTimeout:1 handler:NULL];
  837. }
  838. - (void)testInstanceIDWithHandler_WhileRequesting_RetryFailure {
  839. [self stubKeyPairStoreToReturnValidKeypair];
  840. [self mockAuthServiceToAlwaysReturnValidCheckin];
  841. // Expect `fetchNewTokenWithAuthorizedEntity` to be called once
  842. NSMutableArray<XCTestExpectation *> *fetchNewTokenExpectations = [NSMutableArray array];
  843. for (NSInteger i = 0; i < [[self.instanceID class] maxRetryCountForDefaultToken]; ++i) {
  844. NSString *name = [NSString stringWithFormat:@"fetchNewTokenExpectation-%ld", (long)i];
  845. [fetchNewTokenExpectations addObject:[self expectationWithDescription:name]];
  846. }
  847. __block NSInteger fetchNewTokenCallCount = 0;
  848. __block FIRInstanceIDTokenHandler tokenHandler;
  849. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  850. [invocation getArgument:&tokenHandler atIndex:6];
  851. [fetchNewTokenExpectations[fetchNewTokenCallCount] fulfill];
  852. fetchNewTokenCallCount += 1;
  853. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  854. scope:kFIRInstanceIDDefaultTokenScope
  855. keyPair:[OCMArg any]
  856. options:[OCMArg any]
  857. handler:[OCMArg any]];
  858. // Mock Instance ID's retry interval to 0, to vastly speed up this test.
  859. [[[self.mockInstanceID stub] andReturnValue:@(0)] retryIntervalToFetchDefaultToken];
  860. // Make 1st call
  861. XCTestExpectation *handlerExpectation1 = [self expectationWithDescription:@"handlerExpectation1"];
  862. FIRInstanceIDResultHandler handler1 =
  863. ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
  864. [handlerExpectation1 fulfill];
  865. XCTAssertNil(result);
  866. XCTAssertNotNil(error);
  867. };
  868. [self.mockInstanceID instanceIDWithHandler:handler1];
  869. // Make 2nd call
  870. XCTestExpectation *handlerExpectation2 = [self expectationWithDescription:@"handlerExpectation1"];
  871. FIRInstanceIDResultHandler handler2 =
  872. ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
  873. [handlerExpectation2 fulfill];
  874. XCTAssertNil(result);
  875. XCTAssertNotNil(error);
  876. };
  877. [self.mockInstanceID instanceIDWithHandler:handler2];
  878. for (NSInteger i = 0; i < [[self.instanceID class] maxRetryCountForDefaultToken]; ++i) {
  879. // Wait for the i `fetchNewTokenWithAuthorizedEntity` to be performed
  880. [self waitForExpectations:@[ fetchNewTokenExpectations[i] ] timeout:1 enforceOrder:false];
  881. // Fail for the i time
  882. tokenHandler(nil, [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeUnknown]);
  883. }
  884. // Wait for completion handlers for both calls to be performed
  885. [self waitForExpectationsWithTimeout:1 handler:NULL];
  886. }
  887. /**
  888. * Tests a Keychain read failure while we try to fetch a new InstanceID token. If the Keychain
  889. * read fails we won't be able to fetch the public key which is required while fetching a new
  890. * token. In such a case we should return KeyPair failure.
  891. */
  892. - (void)testNewTokenFetch_keyChainError {
  893. XCTestExpectation *tokenExpectation =
  894. [self expectationWithDescription:@"New token handler invoked."];
  895. [self mockAuthServiceToAlwaysReturnValidCheckin];
  896. // Simulate keypair fetch/generation failure.
  897. [[[self.mockKeyPairStore stub] andReturn:nil] loadKeyPairWithError:[OCMArg anyObjectRef]];
  898. [[self.mockTokenManager reject] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  899. scope:kScope
  900. keyPair:[OCMArg any]
  901. options:[OCMArg any]
  902. handler:[OCMArg any]];
  903. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  904. scope:kScope
  905. options:nil
  906. handler:^(NSString *token, NSError *error) {
  907. XCTAssertNil(token);
  908. XCTAssertNotNil(error);
  909. [tokenExpectation fulfill];
  910. }];
  911. [self waitForExpectationsWithTimeout:1 handler:nil];
  912. OCMVerifyAll(self.mockTokenManager);
  913. }
  914. /**
  915. * If a token fetch includes in its options an "apns_token" object, but not a "apns_sandbox" key,
  916. * ensure that an "apns_sandbox" key is added to the token options (via automatic detection).
  917. */
  918. - (void)testTokenFetchAPNSServerTypeIsIncludedIfAPNSTokenProvided {
  919. XCTestExpectation *apnsServerTypeExpectation =
  920. [self expectationWithDescription:@"apns_sandbox key was included in token options"];
  921. [self stubKeyPairStoreToReturnValidKeypair];
  922. [self mockAuthServiceToAlwaysReturnValidCheckin];
  923. NSData *apnsToken = [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding];
  924. // Option is purposefully missing the apns_sandbox key
  925. NSDictionary *tokenOptions = @{kFIRInstanceIDTokenOptionsAPNSKey : apnsToken};
  926. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  927. // Inspect
  928. NSDictionary *options;
  929. [invocation getArgument:&options atIndex:5];
  930. if (options[kFIRInstanceIDTokenOptionsAPNSIsSandboxKey] != nil) {
  931. [apnsServerTypeExpectation fulfill];
  932. }
  933. self.newTokenCompletion(kToken, nil);
  934. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  935. scope:kScope
  936. keyPair:[OCMArg any]
  937. options:[OCMArg any]
  938. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  939. self.newTokenCompletion = obj;
  940. return obj != nil;
  941. }]];
  942. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  943. scope:kScope
  944. options:tokenOptions
  945. handler:^(NSString *token, NSError *error){
  946. }];
  947. [self waitForExpectationsWithTimeout:60.0
  948. handler:^(NSError *error) {
  949. XCTAssertNil(error);
  950. }];
  951. }
  952. /**
  953. * Tests that if a token was fetched, but during the fetch the APNs data was set, that a new
  954. * token is fetched to associate the APNs data, and is not returned from the cache.
  955. */
  956. - (void)testTokenFetch_ignoresCacheIfAPNSInfoDifferent {
  957. XCTestExpectation *tokenRequestExpectation =
  958. [self expectationWithDescription:@"Token was fetched from the network"];
  959. // Initialize a token in the cache *WITHOUT* APNSInfo
  960. // This token is |kToken|, but we will simulate that a fetch will return another token
  961. NSString *oldCachedToken = kToken;
  962. NSString *fetchedToken = @"abcd123_newtoken";
  963. __block FIRInstanceIDTokenInfo *cachedTokenInfo =
  964. [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
  965. scope:kFIRInstanceIDDefaultTokenScope
  966. token:oldCachedToken
  967. appVersion:@"1.0"
  968. firebaseAppID:@"firebaseAppID"];
  969. [self stubKeyPairStoreToReturnValidKeypair];
  970. [self mockAuthServiceToAlwaysReturnValidCheckin];
  971. // During this test use the default scope ("*") to simulate the default token behavior.
  972. // Return a dynamic cachedToken variable whenever the cached is checked.
  973. // This uses an invocation-based mock because the |cachedToken| pointer
  974. // will change. Normal stubbing will always return the initial pointer,
  975. // which in this case is 0x0 (nil).
  976. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  977. [invocation setReturnValue:&cachedTokenInfo];
  978. }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
  979. // Mock the network request to return |fetchedToken|, so we can clearly see if the token is
  980. // is different than what was cached.
  981. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  982. [tokenRequestExpectation fulfill];
  983. self.newTokenCompletion(fetchedToken, nil);
  984. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  985. scope:kFIRInstanceIDDefaultTokenScope
  986. keyPair:[OCMArg any]
  987. options:[OCMArg any]
  988. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  989. self.newTokenCompletion = obj;
  990. return obj != nil;
  991. }]];
  992. // Begin request
  993. // Token options has APNS data, which is not associated with the cached token
  994. NSDictionary *tokenOptions = @{
  995. kFIRInstanceIDTokenOptionsAPNSKey : [@"apns" dataUsingEncoding:NSUTF8StringEncoding],
  996. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(NO)
  997. };
  998. [self.instanceID
  999. tokenWithAuthorizedEntity:kAuthorizedEntity
  1000. scope:kFIRInstanceIDDefaultTokenScope
  1001. options:tokenOptions
  1002. handler:^(NSString *_Nullable token, NSError *_Nullable error) {
  1003. XCTAssertEqualObjects(token, fetchedToken);
  1004. }];
  1005. [self waitForExpectationsWithTimeout:0.5 handler:nil];
  1006. }
  1007. /**
  1008. * Tests that if there is a keychain failure while fetching the InstanceID of the token we should
  1009. * return nil for the identity.
  1010. */
  1011. - (void)testInstanceIDFetch_keyChainError {
  1012. XCTestExpectation *tokenExpectation =
  1013. [self expectationWithDescription:@"InstanceID fetch handler invoked."];
  1014. // Simulate keypair fetch/generation failure.
  1015. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  1016. [[[self.mockKeyPairStore stub] andReturn:nil] appIdentityWithError:[OCMArg setTo:error]];
  1017. [self.instanceID getIDWithHandler:^(NSString *_Nullable identity, NSError *_Nullable error) {
  1018. XCTAssertNil(identity);
  1019. XCTAssertNotNil(error);
  1020. [tokenExpectation fulfill];
  1021. }];
  1022. [self waitForExpectationsWithTimeout:1 handler:nil];
  1023. }
  1024. - (void)testInstanceIDDelete_keyChainError {
  1025. XCTestExpectation *tokenExpectation =
  1026. [self expectationWithDescription:@"InstanceID deleteID handler invoked."];
  1027. // Simulate keypair fetch/generation failure.
  1028. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  1029. [[[self.mockKeyPairStore stub] andReturn:nil] appIdentityWithError:[OCMArg setTo:error]];
  1030. [self.instanceID deleteIDWithHandler:^(NSError *_Nullable error) {
  1031. XCTAssertNotNil(error);
  1032. [tokenExpectation fulfill];
  1033. }];
  1034. [self waitForExpectationsWithTimeout:1 handler:nil];
  1035. }
  1036. #pragma mark - Private Helpers
  1037. - (void)stubKeyPairStoreToReturnValidKeypair {
  1038. [[[self.mockKeyPairStore stub] andReturn:[self createValidMockKeypair]]
  1039. loadKeyPairWithError:[OCMArg anyObjectRef]];
  1040. }
  1041. - (id)createValidMockKeypair {
  1042. id mockKeypair = OCMClassMock([FIRInstanceIDKeyPair class]);
  1043. [[[mockKeypair stub] andReturnValue:@YES] isValid];
  1044. return mockKeypair;
  1045. }
  1046. - (FIRInstanceIDCheckinPreferences *)validCheckinPreferences {
  1047. NSDictionary *gservicesData = @{
  1048. kFIRInstanceIDVersionInfoStringKey : kVersionInfo,
  1049. kFIRInstanceIDLastCheckinTimeKey : @(FIRInstanceIDCurrentTimestampInMilliseconds())
  1050. };
  1051. FIRInstanceIDCheckinPreferences *checkinPreferences =
  1052. [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kDeviceAuthId
  1053. secretToken:kSecretToken];
  1054. [checkinPreferences updateWithCheckinPlistContents:gservicesData];
  1055. return checkinPreferences;
  1056. }
  1057. - (void)mockAuthServiceToAlwaysReturnValidCheckin {
  1058. FIRInstanceIDCheckinPreferences *validCheckin = [self validCheckinPreferences];
  1059. __block FIRInstanceIDDeviceCheckinCompletion checkinHandler;
  1060. [[[self.mockAuthService stub] andDo:^(NSInvocation *invocation) {
  1061. if (checkinHandler) {
  1062. checkinHandler(validCheckin, nil);
  1063. }
  1064. }] fetchCheckinInfoWithHandler:[OCMArg checkWithBlock:^BOOL(id obj) {
  1065. return (checkinHandler = obj) != nil;
  1066. }]];
  1067. }
  1068. @end