FIRInstanceIDTest.m 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205
  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 <OCMock/OCMock.h>
  20. #import "Firebase/InstanceID/FIRInstanceID+Testing.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/FIRInstanceIDTokenInfo.h"
  26. #import "Firebase/InstanceID/FIRInstanceIDTokenManager.h"
  27. #import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
  28. #import "Firebase/InstanceID/NSError+FIRInstanceID.h"
  29. static NSString *const kFakeIID = @"12345678";
  30. static NSString *const kFakeAPNSToken = @"this is a fake apns token";
  31. static NSString *const kAuthorizedEntity = @"test-audience";
  32. static NSString *const kScope = @"test-scope";
  33. static NSString *const kToken = @"test-token";
  34. static FIRInstanceIDTokenInfo *sTokenInfo;
  35. // Faking checkin calls
  36. static NSString *const kDeviceAuthId = @"device-id";
  37. static NSString *const kSecretToken = @"secret-token";
  38. static NSString *const kDigest = @"com.google.digest";
  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. - (NSInteger)retryIntervalToFetchDefaultToken;
  45. - (BOOL)isFCMAutoInitEnabled;
  46. - (void)didCompleteConfigure;
  47. - (NSString *)cachedTokenIfAvailable;
  48. - (void)deleteIdentityWithHandler:(FIRInstanceIDDeleteHandler)handler;
  49. + (FIRInstanceID *)instanceIDForTests;
  50. - (void)defaultTokenWithHandler:(FIRInstanceIDTokenHandler)handler;
  51. @end
  52. @interface FIRInstanceIDTest : XCTestCase
  53. @property(nonatomic, readwrite, assign) BOOL hasCheckinInfo;
  54. @property(nonatomic, readwrite, strong) FIRInstanceID *instanceID;
  55. @property(nonatomic, readwrite, strong) id mockInstanceID;
  56. @property(nonatomic, readwrite, strong) id mockTokenManager;
  57. @property(nonatomic, readwrite, strong) id mockKeyPairStore;
  58. @property(nonatomic, readwrite, strong) id mockAuthService;
  59. @property(nonatomic, readwrite, strong) id<NSObject> tokenRefreshNotificationObserver;
  60. @property(nonatomic, readwrite, copy) FIRInstanceIDTokenHandler newTokenCompletion;
  61. @property(nonatomic, readwrite, copy) FIRInstanceIDDeleteTokenHandler deleteTokenCompletion;
  62. @end
  63. @implementation FIRInstanceIDTest
  64. - (void)setUp {
  65. [super setUp];
  66. _instanceID = [[FIRInstanceID alloc] initPrivately];
  67. [_instanceID start];
  68. if (!sTokenInfo) {
  69. sTokenInfo = [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
  70. scope:kScope
  71. token:kToken
  72. appVersion:nil
  73. firebaseAppID:nil];
  74. sTokenInfo.cacheTime = [NSDate date];
  75. }
  76. [self mockInstanceIDObjects];
  77. }
  78. - (void)tearDown {
  79. [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
  80. self.instanceID = nil;
  81. self.mockTokenManager = nil;
  82. self.mockInstanceID = nil;
  83. [super tearDown];
  84. }
  85. - (void)mockInstanceIDObjects {
  86. // Mock that we have valid checkin info. Individual tests can override this.
  87. self.hasCheckinInfo = YES;
  88. self.mockAuthService = OCMClassMock([FIRInstanceIDAuthService class]);
  89. [[[self.mockAuthService stub] andDo:^(NSInvocation *invocation) {
  90. [invocation setReturnValue:&self->_hasCheckinInfo];
  91. }] hasValidCheckinInfo];
  92. self.mockTokenManager = OCMClassMock([FIRInstanceIDTokenManager class]);
  93. [[[self.mockTokenManager stub] andReturn:self.mockAuthService] authService];
  94. self.mockKeyPairStore = OCMClassMock([FIRInstanceIDKeyPairStore class]);
  95. _instanceID.fcmSenderID = kAuthorizedEntity;
  96. self.mockInstanceID = OCMPartialMock(_instanceID);
  97. [self.mockInstanceID setTokenManager:self.mockTokenManager];
  98. [self.mockInstanceID setKeyPairStore:self.mockKeyPairStore];
  99. id instanceIDClassMock = OCMClassMock([FIRInstanceID class]);
  100. OCMStub(ClassMethod([instanceIDClassMock minIntervalForDefaultTokenRetry])).andReturn(2);
  101. OCMStub(ClassMethod([instanceIDClassMock maxRetryIntervalForDefaultTokenInSeconds]))
  102. .andReturn(10);
  103. }
  104. /**
  105. * Tests that the FIRInstanceID's sharedInstance class method produces an instance of
  106. * FIRInstanceID with an associated FIRInstanceIDTokenManager.
  107. */
  108. - (void)testSharedInstance {
  109. // The shared instance should be `nil` before the app is configured.
  110. XCTAssertNil([FIRInstanceID instanceID]);
  111. // The shared instance relies on the default app being configured. Configure it.
  112. FIROptions *options = [[FIROptions alloc] initWithGoogleAppID:kGoogleAppID
  113. GCMSenderID:kGCMSenderID];
  114. [FIRApp configureWithName:kFIRDefaultAppName options:options];
  115. FIRInstanceID *instanceID = [FIRInstanceID instanceID];
  116. XCTAssertNotNil(instanceID);
  117. XCTAssertNotNil(instanceID.tokenManager);
  118. // Ensure a second call returns the same instance as the first.
  119. FIRInstanceID *secondInstanceID = [FIRInstanceID instanceID];
  120. XCTAssertEqualObjects(instanceID, secondInstanceID);
  121. // Reset the default app for the next test.
  122. [FIRApp resetApps];
  123. }
  124. - (void)testFCMAutoInitEnabled {
  125. XCTAssertFalse([_instanceID isFCMAutoInitEnabled],
  126. @"When FCM is not available, FCM Auto Init Enabled should be NO.");
  127. }
  128. - (void)testTokenShouldBeRefreshedIfCacheTokenNeedsToBeRefreshed {
  129. [[[self.mockInstanceID stub] andReturn:kToken] cachedTokenIfAvailable];
  130. [[[self.mockTokenManager stub] andReturnValue:@(YES)] checkForTokenRefreshPolicy];
  131. [[[self.mockInstanceID stub] andDo:^(NSInvocation *invocation){
  132. }] tokenWithAuthorizedEntity:[OCMArg any]
  133. scope:[OCMArg any]
  134. options:[OCMArg any]
  135. handler:[OCMArg any]];
  136. [self.mockInstanceID didCompleteConfigure];
  137. OCMVerify([self.mockInstanceID defaultTokenWithHandler:nil]);
  138. XCTAssertEqualObjects([self.mockInstanceID token], kToken);
  139. }
  140. - (void)testTokenShouldBeRefreshedIfNoCacheTokenButAutoInitAllowed {
  141. [[[self.mockInstanceID stub] andReturn:nil] cachedTokenIfAvailable];
  142. [[[self.mockInstanceID stub] andReturnValue:@(YES)] isFCMAutoInitEnabled];
  143. [[[self.mockInstanceID stub] andDo:^(NSInvocation *invocation){
  144. }] tokenWithAuthorizedEntity:[OCMArg any]
  145. scope:[OCMArg any]
  146. options:[OCMArg any]
  147. handler:[OCMArg any]];
  148. [self.mockInstanceID didCompleteConfigure];
  149. OCMVerify([self.mockInstanceID defaultTokenWithHandler:nil]);
  150. }
  151. - (void)testTokenIsDeletedAlongWithIdentity {
  152. [[[self.mockInstanceID stub] andReturnValue:@(YES)] isFCMAutoInitEnabled];
  153. [[[self.mockInstanceID stub] andDo:^(NSInvocation *invocation){
  154. }] tokenWithAuthorizedEntity:[OCMArg any]
  155. scope:[OCMArg any]
  156. options:[OCMArg any]
  157. handler:[OCMArg any]];
  158. [self.mockInstanceID deleteIdentityWithHandler:^(NSError *_Nullable error) {
  159. XCTAssertNil([self.mockInstanceID token]);
  160. }];
  161. }
  162. - (void)testTokenIsFetchedDuringIIDGeneration {
  163. XCTestExpectation *tokenExpectation = [self
  164. expectationWithDescription:@"Token is refreshed when getID is called to avoid IID conflict."];
  165. NSError *error;
  166. [[[self.mockKeyPairStore stub] andReturn:kFakeIID] appIdentityWithError:[OCMArg setTo:error]];
  167. [self.mockInstanceID getIDWithHandler:^(NSString *identity, NSError *error) {
  168. XCTAssertNotNil(identity);
  169. XCTAssertEqual(identity, kFakeIID);
  170. OCMVerify([self.mockInstanceID token]);
  171. [tokenExpectation fulfill];
  172. }];
  173. [self waitForExpectationsWithTimeout:0.1
  174. handler:^(NSError *error) {
  175. XCTAssertNil(error);
  176. }];
  177. }
  178. /**
  179. * Tests that when a new InstanceID token is successfully produced,
  180. * the callback is invoked with a token that is not an empty string and with no error.
  181. */
  182. - (void)testNewTokenSuccess {
  183. XCTestExpectation *tokenExpectation =
  184. [self expectationWithDescription:@"New token handler invoked."];
  185. NSString *APNSKey = kFIRInstanceIDTokenOptionsAPNSKey;
  186. NSString *serverKey = kFIRInstanceIDTokenOptionsAPNSIsSandboxKey;
  187. [self stubKeyPairStoreToReturnValidKeypair];
  188. [self mockAuthServiceToAlwaysReturnValidCheckin];
  189. NSData *fakeAPNSDeviceToken = [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding];
  190. BOOL isSandbox = YES;
  191. NSDictionary *tokenOptions = @{
  192. APNSKey : fakeAPNSDeviceToken,
  193. serverKey : @(isSandbox),
  194. };
  195. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  196. self.newTokenCompletion(kToken, nil);
  197. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  198. scope:kScope
  199. keyPair:[OCMArg any]
  200. options:[OCMArg checkWithBlock:^BOOL(id obj) {
  201. NSDictionary *options = (NSDictionary *)obj;
  202. XCTAssertTrue([options[APNSKey] isEqual:fakeAPNSDeviceToken]);
  203. XCTAssertTrue([options[serverKey] isEqual:@(isSandbox)]);
  204. return YES;
  205. }]
  206. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  207. self.newTokenCompletion = obj;
  208. return obj != nil;
  209. }]];
  210. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  211. scope:kScope
  212. options:tokenOptions
  213. handler:^(NSString *token, NSError *error) {
  214. XCTAssertNotNil(token);
  215. XCTAssertGreaterThan(token.length, 0);
  216. XCTAssertNil(error);
  217. [tokenExpectation fulfill];
  218. }];
  219. [self waitForExpectationsWithTimeout:1
  220. handler:^(NSError *error) {
  221. XCTAssertNil(error);
  222. }];
  223. }
  224. /**
  225. * Get Token should fail if we do not have valid checkin info and are unable to
  226. * retreive one.
  227. */
  228. - (void)testNewTokenCheckinFailure {
  229. self.hasCheckinInfo = NO;
  230. __block FIRInstanceIDDeviceCheckinCompletion checkinHandler;
  231. [[[self.mockAuthService stub] andDo:^(NSInvocation *invocation) {
  232. if (checkinHandler) {
  233. FIRInstanceIDErrorCode code = kFIRInstanceIDErrorCodeUnknown;
  234. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:code];
  235. checkinHandler(nil, error);
  236. }
  237. }] fetchCheckinInfoWithHandler:[OCMArg checkWithBlock:^BOOL(id obj) {
  238. return (checkinHandler = obj) != nil;
  239. }]];
  240. XCTestExpectation *tokenExpectation =
  241. [self expectationWithDescription:@"New token handler invoked."];
  242. NSDictionary *tokenOptions = @{
  243. kFIRInstanceIDTokenOptionsAPNSKey : [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding],
  244. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(YES),
  245. };
  246. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  247. self.newTokenCompletion(kToken, nil);
  248. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  249. scope:kScope
  250. keyPair:[OCMArg any]
  251. options:[OCMArg any]
  252. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  253. self.newTokenCompletion = obj;
  254. return obj != nil;
  255. }]];
  256. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  257. scope:kScope
  258. options:tokenOptions
  259. handler:^(NSString *token, NSError *error) {
  260. XCTAssertNil(token);
  261. XCTAssertNotNil(error);
  262. [tokenExpectation fulfill];
  263. }];
  264. [self waitForExpectationsWithTimeout:60.0
  265. handler:^(NSError *error) {
  266. XCTAssertNil(error);
  267. }];
  268. }
  269. /**
  270. * Get token with no valid checkin should wait for any existing checkin operation to finish.
  271. * If the checkin succeeds within a stipulated amount of time period getting the token should
  272. * also succeed.
  273. */
  274. - (void)testNewTokenSuccessAfterWaiting {
  275. self.hasCheckinInfo = NO;
  276. __block FIRInstanceIDDeviceCheckinCompletion checkinHandler;
  277. [[[self.mockAuthService stub] andDo:^(NSInvocation *invocation) {
  278. if (checkinHandler) {
  279. FIRInstanceIDErrorCode code = kFIRInstanceIDErrorCodeUnknown;
  280. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:code];
  281. checkinHandler(nil, error);
  282. }
  283. }] fetchCheckinInfoWithHandler:[OCMArg checkWithBlock:^BOOL(id obj) {
  284. return (checkinHandler = obj) != nil;
  285. }]];
  286. XCTestExpectation *tokenExpectation =
  287. [self expectationWithDescription:@"New token handler invoked."];
  288. NSDictionary *tokenOptions = @{
  289. kFIRInstanceIDTokenOptionsAPNSKey : [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding],
  290. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(YES),
  291. };
  292. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  293. self.newTokenCompletion(kToken, nil);
  294. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  295. scope:kScope
  296. keyPair:[OCMArg any]
  297. options:[OCMArg any]
  298. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  299. self.newTokenCompletion = obj;
  300. return obj != nil;
  301. }]];
  302. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  303. scope:kScope
  304. options:tokenOptions
  305. handler:^(NSString *token, NSError *error) {
  306. XCTAssertNil(token);
  307. XCTAssertNotNil(error);
  308. [tokenExpectation fulfill];
  309. }];
  310. [self waitForExpectationsWithTimeout:60.0
  311. handler:^(NSError *error) {
  312. XCTAssertNil(error);
  313. }];
  314. }
  315. /**
  316. * Test that the prod APNS token is correctly prefixed with "prod".
  317. */
  318. - (void)testAPNSTokenIsPrefixedCorrectlyForServerType {
  319. NSString *APNSKey = kFIRInstanceIDTokenOptionsAPNSKey;
  320. NSString *serverTypeKey = kFIRInstanceIDTokenOptionsAPNSIsSandboxKey;
  321. NSDictionary *prodTokenOptions = @{
  322. APNSKey : [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding],
  323. serverTypeKey : @(NO),
  324. };
  325. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation){
  326. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  327. scope:kScope
  328. keyPair:[OCMArg any]
  329. options:[OCMArg checkWithBlock:^BOOL(id obj) {
  330. NSDictionary *options = (NSDictionary *)obj;
  331. XCTAssertTrue([options[APNSKey] hasPrefix:@"p_"]);
  332. XCTAssertFalse([options[serverTypeKey] boolValue]);
  333. return YES;
  334. }]
  335. handler:OCMOCK_ANY];
  336. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  337. scope:kScope
  338. options:prodTokenOptions
  339. handler:^(NSString *token, NSError *error){
  340. }];
  341. }
  342. /**
  343. * Tests that when there is a failure in producing a new InstanceID token,
  344. * the callback is invoked with an error and a nil token.
  345. */
  346. - (void)testNewTokenFailure {
  347. XCTestExpectation *tokenExpectation =
  348. [self expectationWithDescription:@"New token handler invoked."];
  349. NSDictionary *tokenOptions = [NSDictionary dictionary];
  350. [self mockAuthServiceToAlwaysReturnValidCheckin];
  351. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  352. NSError *someError = [[NSError alloc] initWithDomain:@"InstanceIDUnitTest" code:0 userInfo:nil];
  353. self.newTokenCompletion(nil, someError);
  354. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  355. scope:kScope
  356. keyPair:[OCMArg any]
  357. options:tokenOptions
  358. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  359. self.newTokenCompletion = obj;
  360. return obj != nil;
  361. }]];
  362. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  363. scope:kScope
  364. options:tokenOptions
  365. handler:^(NSString *token, NSError *error) {
  366. XCTAssertNil(token);
  367. XCTAssertNotNil(error);
  368. [tokenExpectation fulfill];
  369. }];
  370. [self waitForExpectationsWithTimeout:1
  371. handler:^(NSError *error) {
  372. XCTAssertNil(error);
  373. }];
  374. }
  375. /**
  376. * Tests that when a token is deleted successfully, the callback is invoked with no error.
  377. */
  378. - (void)testDeleteTokenSuccess {
  379. XCTestExpectation *deleteExpectation =
  380. [self expectationWithDescription:@"Delete handler invoked."];
  381. [self stubKeyPairStoreToReturnValidKeypair];
  382. [self mockAuthServiceToAlwaysReturnValidCheckin];
  383. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  384. #pragma clang diagnostic push
  385. #pragma clang diagnostic ignored "-Wnonnull"
  386. self.deleteTokenCompletion(nil);
  387. #pragma clang diagnostic pop
  388. }] deleteTokenWithAuthorizedEntity:kAuthorizedEntity
  389. scope:kScope
  390. keyPair:[OCMArg any]
  391. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  392. self.deleteTokenCompletion = obj;
  393. return obj != nil;
  394. }]];
  395. [self.instanceID deleteTokenWithAuthorizedEntity:kAuthorizedEntity
  396. scope:kScope
  397. handler:^(NSError *error) {
  398. XCTAssertNil(error);
  399. [deleteExpectation fulfill];
  400. }];
  401. [self waitForExpectationsWithTimeout:1
  402. handler:^(NSError *error) {
  403. XCTAssertNil(error);
  404. }];
  405. }
  406. /**
  407. * Tests that when a token deletion fails, the callback is invoked with an error.
  408. */
  409. - (void)testDeleteTokenFailure {
  410. XCTestExpectation *deleteExpectation =
  411. [self expectationWithDescription:@"Delete handler invoked."];
  412. [self mockAuthServiceToAlwaysReturnValidCheckin];
  413. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  414. NSError *someError = [[NSError alloc] initWithDomain:@"InstanceIDUnitTest" code:0 userInfo:nil];
  415. self.deleteTokenCompletion(someError);
  416. }] deleteTokenWithAuthorizedEntity:kAuthorizedEntity
  417. scope:kScope
  418. keyPair:[OCMArg any]
  419. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  420. self.deleteTokenCompletion = obj;
  421. return obj != nil;
  422. }]];
  423. [self.instanceID deleteTokenWithAuthorizedEntity:kAuthorizedEntity
  424. scope:kScope
  425. handler:^(NSError *error) {
  426. XCTAssertNotNil(error);
  427. [deleteExpectation fulfill];
  428. }];
  429. [self waitForExpectationsWithTimeout:1
  430. handler:^(NSError *error) {
  431. XCTAssertNil(error);
  432. }];
  433. }
  434. /**
  435. * Tests that not having a senderID will fetch a `nil` default token.
  436. */
  437. - (void)testDefaultToken_noSenderID {
  438. _instanceID.fcmSenderID = nil;
  439. XCTAssertNil([self.mockInstanceID token]);
  440. }
  441. /**
  442. * Tests that not having a cached token results in trying to fetch a new default token.
  443. */
  444. - (void)testDefaultToken_noCachedToken {
  445. [[[self.mockTokenManager stub] andReturn:nil]
  446. cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
  447. scope:@"*"];
  448. OCMExpect([self.mockInstanceID defaultTokenWithHandler:nil]);
  449. NSString *token = [self.mockInstanceID token];
  450. XCTAssertNil(token);
  451. [self.mockInstanceID stopMocking];
  452. OCMVerify([self.mockInstanceID defaultTokenWithHandler:nil]);
  453. }
  454. /**
  455. * Tests that when we have a cached default token, calling `getToken` returns that token
  456. * without hitting the network.
  457. */
  458. - (void)testDefaultToken_validCachedToken {
  459. [[[self.mockTokenManager stub] andReturn:sTokenInfo]
  460. cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
  461. scope:@"*"];
  462. [[self.mockInstanceID reject] defaultTokenWithHandler:nil];
  463. NSString *token = [self.mockInstanceID token];
  464. XCTAssertEqualObjects(token, kToken);
  465. }
  466. /**
  467. * Test that when we fetch a new default token and cache it successfully we post a
  468. * tokenRefresh notification which allows to fetch the cached token.
  469. */
  470. - (void)testDefaultTokenFetch_returnValidToken {
  471. XCTestExpectation *defaultTokenExpectation =
  472. [self expectationWithDescription:@"Successfully got default token."];
  473. __block FIRInstanceIDTokenInfo *cachedTokenInfo = nil;
  474. [self stubKeyPairStoreToReturnValidKeypair];
  475. [self mockAuthServiceToAlwaysReturnValidCheckin];
  476. // Mock Token manager to always succeed the token fetch, and return
  477. // a particular cached value.
  478. // Return a dynamic cachedToken variable whenever the cached is checked.
  479. // This uses an invocation-based mock because the |cachedToken| pointer
  480. // will change. Normal stubbing will always return the initial pointer,
  481. // which in this case is 0x0 (nil).
  482. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  483. [invocation setReturnValue:&cachedTokenInfo];
  484. }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
  485. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  486. self.newTokenCompletion(kToken, nil);
  487. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  488. scope:kFIRInstanceIDDefaultTokenScope
  489. keyPair:[OCMArg any]
  490. options:[OCMArg any]
  491. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  492. self.newTokenCompletion = obj;
  493. return obj != nil;
  494. }]];
  495. __block int notificationPostCount = 0;
  496. __block NSString *notificationToken = nil;
  497. NSString *notificationName = kFIRInstanceIDTokenRefreshNotification;
  498. self.tokenRefreshNotificationObserver = [[NSNotificationCenter defaultCenter]
  499. addObserverForName:notificationName
  500. object:nil
  501. queue:nil
  502. usingBlock:^(NSNotification *_Nonnull note) {
  503. // Should have saved token to cache
  504. cachedTokenInfo = sTokenInfo;
  505. notificationPostCount++;
  506. #pragma clang diagnostic push
  507. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  508. notificationToken = [[self.instanceID token] copy];
  509. #pragma clang diagnostic pop
  510. [defaultTokenExpectation fulfill];
  511. }];
  512. NSString *token = [self.mockInstanceID token];
  513. [self waitForExpectationsWithTimeout:10.0 handler:nil];
  514. [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
  515. XCTAssertNil(token);
  516. XCTAssertEqualObjects(notificationToken, kToken);
  517. }
  518. /**
  519. * Tests that if we fail to fetch the token from the server for the first time we retry again
  520. * later with exponential backoff unless we succeed.
  521. */
  522. - (void)testDefaultTokenFetch_retryFetchToken {
  523. const int trialsBeforeSuccess = 3;
  524. __block int newTokenFetchCount = 0;
  525. __block int64_t lastFetchTimestampInSeconds;
  526. XCTestExpectation *defaultTokenExpectation =
  527. [self expectationWithDescription:@"Successfully got default token."];
  528. __block FIRInstanceIDTokenInfo *cachedTokenInfo = nil;
  529. [self stubKeyPairStoreToReturnValidKeypair];
  530. [self mockAuthServiceToAlwaysReturnValidCheckin];
  531. // Mock Token manager.
  532. // Return a dynamic cachedToken variable whenever the cached is checked.
  533. // This uses an invocation-based mock because the |cachedToken| pointer
  534. // will change. Normal stubbing will always return the initial pointer,
  535. // which in this case is 0x0 (nil).
  536. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  537. [invocation setReturnValue:&cachedTokenInfo];
  538. }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
  539. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  540. newTokenFetchCount++;
  541. int64_t delaySinceLastFetchInSeconds =
  542. FIRInstanceIDCurrentTimestampInSeconds() - lastFetchTimestampInSeconds;
  543. // Test exponential backoff.
  544. if (newTokenFetchCount > 1) {
  545. XCTAssertLessThanOrEqual(1 << (newTokenFetchCount - 1), delaySinceLastFetchInSeconds);
  546. }
  547. lastFetchTimestampInSeconds = FIRInstanceIDCurrentTimestampInSeconds();
  548. if (newTokenFetchCount < trialsBeforeSuccess) {
  549. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeTimeout];
  550. self.newTokenCompletion(nil, error);
  551. } else {
  552. self.newTokenCompletion(kToken, nil);
  553. }
  554. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  555. scope:kFIRInstanceIDDefaultTokenScope
  556. keyPair:[OCMArg any]
  557. options:[OCMArg any]
  558. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  559. self.newTokenCompletion = obj;
  560. return obj != nil;
  561. }]];
  562. __block int notificationPostCount = 0;
  563. __block NSString *notificationToken = nil;
  564. NSString *notificationName = kFIRInstanceIDTokenRefreshNotification;
  565. self.tokenRefreshNotificationObserver = [[NSNotificationCenter defaultCenter]
  566. addObserverForName:notificationName
  567. object:nil
  568. queue:nil
  569. usingBlock:^(NSNotification *_Nonnull note) {
  570. // Should have saved token to cache
  571. cachedTokenInfo = sTokenInfo;
  572. notificationPostCount++;
  573. #pragma clang diagnostic push
  574. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  575. notificationToken = [[self.instanceID token] copy];
  576. #pragma clang diagnostic pop
  577. [defaultTokenExpectation fulfill];
  578. }];
  579. NSString *token = [self.mockInstanceID token];
  580. [self waitForExpectationsWithTimeout:20.0 handler:nil];
  581. [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
  582. XCTAssertNil(token);
  583. XCTAssertEqualObjects(notificationToken, kToken);
  584. XCTAssertEqual(notificationPostCount, 1);
  585. XCTAssertEqual(newTokenFetchCount, trialsBeforeSuccess);
  586. }
  587. /**
  588. * Tests that when we don't have a cached default token multiple invocations to `getToken`
  589. * lead to a single networking call to fetch the token. Also verify that we post one unique
  590. * TokenRefresh notification for multiple invocations.
  591. */
  592. - (void)testDefaultToken_multipleInvocations {
  593. __block int newTokenFetchCount = 0;
  594. XCTestExpectation *defaultTokenExpectation =
  595. [self expectationWithDescription:@"Successfully got default token."];
  596. __block FIRInstanceIDTokenInfo *cachedTokenInfo = nil;
  597. [self stubKeyPairStoreToReturnValidKeypair];
  598. [self mockAuthServiceToAlwaysReturnValidCheckin];
  599. // Mock Token manager.
  600. // Return a dynamic cachedToken variable whenever the cached is checked.
  601. // This uses an invocation-based mock because the |cachedToken| pointer
  602. // will change. Normal stubbing will always return the initial pointer,
  603. // which in this case is 0x0 (nil).
  604. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  605. [invocation setReturnValue:&cachedTokenInfo];
  606. }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
  607. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  608. // Invoke callback after some delay (network delay)
  609. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)),
  610. dispatch_get_main_queue(), ^{
  611. self.newTokenCompletion(kToken, nil);
  612. });
  613. newTokenFetchCount++;
  614. XCTAssertEqual(newTokenFetchCount, 1);
  615. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  616. scope:kFIRInstanceIDDefaultTokenScope
  617. keyPair:[OCMArg any]
  618. options:[OCMArg any]
  619. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  620. self.newTokenCompletion = obj;
  621. return obj != nil;
  622. }]];
  623. __block int notificationPostCount = 0;
  624. __block NSString *notificationToken = nil;
  625. NSString *notificationName = kFIRInstanceIDTokenRefreshNotification;
  626. self.tokenRefreshNotificationObserver = [[NSNotificationCenter defaultCenter]
  627. addObserverForName:notificationName
  628. object:nil
  629. queue:nil
  630. usingBlock:^(NSNotification *_Nonnull note) {
  631. // Should have saved token to cache
  632. cachedTokenInfo = sTokenInfo;
  633. notificationPostCount++;
  634. #pragma clang diagnostic push
  635. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  636. notificationToken = [[self.instanceID token] copy];
  637. #pragma clang diagnostic pop
  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