FIRInstanceIDTest.m 55 KB

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