FIRInstanceIDTest.m 59 KB

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