FIRInstanceIDTest.m 62 KB

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