GIDGoogleUserTest.m 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. // Copyright 2021 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDGoogleUser.h"
  15. #import <XCTest/XCTest.h>
  16. #import <TargetConditionals.h>
  17. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDConfiguration.h"
  18. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDProfileData.h"
  19. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDSignIn.h"
  20. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDToken.h"
  21. #import "GoogleSignIn/Sources/GIDGoogleUser_Private.h"
  22. #import "GoogleSignIn/Tests/Unit/GIDGoogleUser+Testing.h"
  23. #import "GoogleSignIn/Tests/Unit/GIDProfileData+Testing.h"
  24. #import "GoogleSignIn/Tests/Unit/OIDAuthState+Testing.h"
  25. #import "GoogleSignIn/Tests/Unit/OIDAuthorizationRequest+Testing.h"
  26. #import "GoogleSignIn/Tests/Unit/OIDTokenRequest+Testing.h"
  27. #import "GoogleSignIn/Tests/Unit/OIDTokenResponse+Testing.h"
  28. #ifdef SWIFT_PACKAGE
  29. @import AppAuth;
  30. @import GoogleUtilities_MethodSwizzler;
  31. @import GoogleUtilities_SwizzlerTestHelpers;
  32. @import GTMAppAuth;
  33. @import OCMock;
  34. #else
  35. #import <AppAuth/OIDAuthState.h>
  36. #import <AppAuth/OIDAuthorizationRequest.h>
  37. #import <AppAuth/OIDAuthorizationResponse.h>
  38. #import <AppAuth/OIDAuthorizationService.h>
  39. #import <AppAuth/OIDError.h>
  40. #import <AppAuth/OIDIDToken.h>
  41. #import <AppAuth/OIDTokenRequest.h>
  42. #import <AppAuth/OIDTokenResponse.h>
  43. #import <GoogleUtilities/GULSwizzler.h>
  44. #import <GoogleUtilities/GULSwizzler+Unswizzle.h>
  45. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization.h>
  46. #import <OCMock/OCMock.h>
  47. #endif
  48. static NSString *const kNewAccessToken = @"new_access_token";
  49. static NSString *const kNewRefreshToken = @"new_refresh_token";
  50. static NSTimeInterval const kTimeAccuracy = 10;
  51. static NSTimeInterval const kIDTokenExpiresIn = 100;
  52. static NSTimeInterval const kNewIDTokenExpiresIn = 200;
  53. static NSString *const kNewScope = @"newScope";
  54. @interface GIDGoogleUserTest : XCTestCase
  55. @end
  56. @implementation GIDGoogleUserTest {
  57. // The saved token fetch handler.
  58. OIDTokenCallback _tokenFetchHandler;
  59. }
  60. - (void)setUp {
  61. _tokenFetchHandler = nil;
  62. // We need to use swizzle here because OCMock can not stub class method with arguments.
  63. [GULSwizzler swizzleClass:[OIDAuthorizationService class]
  64. selector:@selector(performTokenRequest:originalAuthorizationResponse:callback:)
  65. isClassSelector:YES
  66. withBlock:^(id sender,
  67. OIDTokenRequest *request,
  68. OIDAuthorizationResponse *authorizationResponse,
  69. OIDTokenCallback callback) {
  70. // Save the OIDTokenCallback.
  71. self->_tokenFetchHandler = [callback copy];
  72. }];
  73. }
  74. - (void)tearDown {
  75. [GULSwizzler unswizzleClass:[OIDAuthorizationService class]
  76. selector:@selector(performTokenRequest:originalAuthorizationResponse:callback:)
  77. isClassSelector:YES];
  78. }
  79. #pragma mark - Tests
  80. - (void)testInitWithAuthState {
  81. OIDAuthState *authState = [OIDAuthState testInstance];
  82. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState
  83. profileData:[GIDProfileData testInstance]];
  84. XCTAssertEqualObjects(user.grantedScopes, @[ OIDAuthorizationRequestTestingScope2 ]);
  85. XCTAssertEqualObjects(user.userID, kUserID);
  86. XCTAssertEqualObjects(user.configuration.hostedDomain, kHostedDomain);
  87. XCTAssertEqualObjects(user.configuration.clientID, OIDAuthorizationRequestTestingClientID);
  88. XCTAssertEqualObjects(user.profile, [GIDProfileData testInstance]);
  89. XCTAssertEqualObjects(user.accessToken.tokenString, kAccessToken);
  90. XCTAssertEqualObjects(user.refreshToken.tokenString, kRefreshToken);
  91. OIDIDToken *idToken = [[OIDIDToken alloc]
  92. initWithIDTokenString:authState.lastTokenResponse.idToken];
  93. XCTAssertEqualObjects(user.idToken.expirationDate, [idToken expiresAt]);
  94. }
  95. - (void)testCoding {
  96. if (@available(iOS 11, macOS 10.13, *)) {
  97. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:[OIDAuthState testInstance]
  98. profileData:[GIDProfileData testInstance]];
  99. NSData *data = [NSKeyedArchiver archivedDataWithRootObject:user
  100. requiringSecureCoding:YES
  101. error:nil];
  102. GIDGoogleUser *newUser = [NSKeyedUnarchiver unarchivedObjectOfClass:[GIDGoogleUser class]
  103. fromData:data
  104. error:nil];
  105. XCTAssertEqualObjects(user, newUser);
  106. XCTAssertTrue(GIDGoogleUser.supportsSecureCoding);
  107. } else {
  108. XCTSkip(@"Required API is not available for this test.");
  109. }
  110. }
  111. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  112. // Deprecated in iOS 13 and macOS 10.14
  113. - (void)testLegacyCoding {
  114. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:[OIDAuthState testInstance]
  115. profileData:[GIDProfileData testInstance]];
  116. NSData *data = [NSKeyedArchiver archivedDataWithRootObject:user];
  117. GIDGoogleUser *newUser = [NSKeyedUnarchiver unarchiveObjectWithData:data];
  118. XCTAssertEqualObjects(user, newUser);
  119. XCTAssertTrue(GIDGoogleUser.supportsSecureCoding);
  120. }
  121. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  122. // Test the old encoding format for backword compatability.
  123. - (void)testOldFormatCoding {
  124. if (@available(iOS 11, macOS 10.13, *)) {
  125. OIDAuthState *authState = [OIDAuthState testInstance];
  126. GIDProfileData *profileDate = [GIDProfileData testInstance];
  127. GIDGoogleUserOldFormat *user = [[GIDGoogleUserOldFormat alloc] initWithAuthState:authState
  128. profileData:profileDate];
  129. NSData *data = [NSKeyedArchiver archivedDataWithRootObject:user
  130. requiringSecureCoding:YES
  131. error:nil];
  132. GIDGoogleUser *newUser = [NSKeyedUnarchiver unarchivedObjectOfClass:[GIDGoogleUser class]
  133. fromData:data
  134. error:nil];
  135. XCTAssertEqualObjects(user, newUser);
  136. }
  137. }
  138. - (void)testUpdateAuthState {
  139. GIDGoogleUser *user = [self googleUserWithAccessTokenExpiresIn:kAccessTokenExpiresIn
  140. idTokenExpiresIn:kIDTokenExpiresIn];
  141. NSString *updatedIDToken = [self idTokenWithExpiresIn:kNewIDTokenExpiresIn];
  142. OIDAuthState *updatedAuthState = [OIDAuthState testInstanceWithIDToken:updatedIDToken
  143. accessToken:kNewAccessToken
  144. accessTokenExpiresIn:kAccessTokenExpiresIn
  145. refreshToken:kNewRefreshToken];
  146. GIDProfileData *updatedProfileData = [GIDProfileData testInstance];
  147. [user updateWithTokenResponse:updatedAuthState.lastTokenResponse
  148. authorizationResponse:updatedAuthState.lastAuthorizationResponse
  149. profileData:updatedProfileData];
  150. XCTAssertEqualObjects(user.accessToken.tokenString, kNewAccessToken);
  151. [self verifyUser:user accessTokenExpiresIn:kAccessTokenExpiresIn];
  152. XCTAssertEqualObjects(user.idToken.tokenString, updatedIDToken);
  153. [self verifyUser:user idTokenExpiresIn:kNewIDTokenExpiresIn];
  154. XCTAssertEqualObjects(user.refreshToken.tokenString, kNewRefreshToken);
  155. XCTAssertEqual(user.profile, updatedProfileData);
  156. }
  157. // When updating with a new OIDAuthState in which token information is not changed, the token objects
  158. // should remain the same.
  159. - (void)testUpdateAuthState_tokensAreNotChanged {
  160. NSString *idToken = [self idTokenWithExpiresIn:kIDTokenExpiresIn];
  161. OIDAuthState *authState = [OIDAuthState testInstanceWithIDToken:idToken
  162. accessToken:kAccessToken
  163. accessTokenExpiresIn:kAccessTokenExpiresIn
  164. refreshToken:kRefreshToken];
  165. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState profileData:nil];
  166. GIDToken *accessTokenBeforeUpdate = user.accessToken;
  167. GIDToken *refreshTokenBeforeUpdate = user.refreshToken;
  168. GIDToken *idTokenBeforeUpdate = user.idToken;
  169. [user updateWithTokenResponse:authState.lastTokenResponse
  170. authorizationResponse:authState.lastAuthorizationResponse
  171. profileData:nil];
  172. XCTAssertIdentical(user.accessToken, accessTokenBeforeUpdate);
  173. XCTAssertIdentical(user.idToken, idTokenBeforeUpdate);
  174. XCTAssertIdentical(user.refreshToken, refreshTokenBeforeUpdate);
  175. }
  176. - (void)testFetcherAuthorizer {
  177. // This is really hard to test without assuming how GTMAppAuthFetcherAuthorization works
  178. // internally, so let's just take the shortcut here by asserting we get a
  179. // GTMAppAuthFetcherAuthorization object.
  180. GIDGoogleUser *user = [self googleUserWithAccessTokenExpiresIn:kAccessTokenExpiresIn
  181. idTokenExpiresIn:kIDTokenExpiresIn];
  182. #pragma clang diagnostic push
  183. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  184. id<GTMFetcherAuthorizationProtocol> fetcherAuthorizer = user.fetcherAuthorizer;
  185. #pragma clang diagnostic pop
  186. XCTAssertTrue([fetcherAuthorizer isKindOfClass:[GTMAppAuthFetcherAuthorization class]]);
  187. XCTAssertTrue([fetcherAuthorizer canAuthorize]);
  188. }
  189. - (void)testFetcherAuthorizer_returnTheSameInstance {
  190. GIDGoogleUser *user = [self googleUserWithAccessTokenExpiresIn:kAccessTokenExpiresIn
  191. idTokenExpiresIn:kIDTokenExpiresIn];
  192. #pragma clang diagnostic push
  193. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  194. id<GTMFetcherAuthorizationProtocol> fetcherAuthorizer = user.fetcherAuthorizer;
  195. id<GTMFetcherAuthorizationProtocol> fetcherAuthorizer2 = user.fetcherAuthorizer;
  196. #pragma clang diagnostic pop
  197. XCTAssertIdentical(fetcherAuthorizer, fetcherAuthorizer2);
  198. }
  199. #pragma mark - Test `refreshTokensIfNeededWithCompletion:`
  200. - (void)testRefreshTokensIfNeededWithCompletion_refresh_givenBothTokensExpired {
  201. // Both tokens expired 10 seconds ago.
  202. GIDGoogleUser *user = [self googleUserWithAccessTokenExpiresIn:-10 idTokenExpiresIn:-10];
  203. NSString *newIdToken = [self idTokenWithExpiresIn:kNewIDTokenExpiresIn];
  204. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback is called"];
  205. // Save the intermediate states.
  206. [user refreshTokensIfNeededWithCompletion:^(GIDGoogleUser * _Nullable user,
  207. NSError * _Nullable error) {
  208. [expectation fulfill];
  209. XCTAssertNil(error);
  210. XCTAssertEqualObjects(user.accessToken.tokenString, kNewAccessToken);
  211. [self verifyUser:user accessTokenExpiresIn:kAccessTokenExpiresIn];
  212. XCTAssertEqualObjects(user.idToken.tokenString, newIdToken);
  213. [self verifyUser:user idTokenExpiresIn:kNewIDTokenExpiresIn];
  214. }];
  215. // Creates a fake response.
  216. OIDTokenResponse *fakeResponse = [OIDTokenResponse testInstanceWithIDToken:newIdToken
  217. accessToken:kNewAccessToken
  218. expiresIn:@(kAccessTokenExpiresIn)
  219. refreshToken:kRefreshToken
  220. tokenRequest:nil];
  221. _tokenFetchHandler(fakeResponse, nil);
  222. [self waitForExpectationsWithTimeout:1 handler:nil];
  223. }
  224. - (void)testRefreshTokens_refresh_givenBothTokensExpired_NoNewIDToken {
  225. // Both tokens expired 10 seconds ago.
  226. GIDGoogleUser *user = [self googleUserWithAccessTokenExpiresIn:-10 idTokenExpiresIn:-10];
  227. // Creates a fake response without ID token.
  228. OIDTokenResponse *fakeResponse = [OIDTokenResponse testInstanceWithIDToken:nil
  229. accessToken:kNewAccessToken
  230. expiresIn:@(kAccessTokenExpiresIn)
  231. refreshToken:kRefreshToken
  232. tokenRequest:nil];
  233. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback is called"];
  234. // Save the intermediate states.
  235. [user refreshTokensIfNeededWithCompletion:^(GIDGoogleUser * _Nullable user,
  236. NSError * _Nullable error) {
  237. [expectation fulfill];
  238. XCTAssertNil(error);
  239. XCTAssertEqualObjects(user.accessToken.tokenString, kNewAccessToken);
  240. [self verifyUser:user accessTokenExpiresIn:kAccessTokenExpiresIn];
  241. XCTAssertNil(user.idToken);
  242. }];
  243. _tokenFetchHandler(fakeResponse, nil);
  244. [self waitForExpectationsWithTimeout:1 handler:nil];
  245. }
  246. - (void)testRefreshTokensIfNeededWithCompletion_refresh_givenAccessTokenExpired {
  247. // Access token expired 10 seconds ago. ID token will expire in 10 minutes.
  248. GIDGoogleUser *user = [self googleUserWithAccessTokenExpiresIn:-10 idTokenExpiresIn:10 * 60];
  249. // Creates a fake response.
  250. NSString *newIdToken = [self idTokenWithExpiresIn:kNewIDTokenExpiresIn];
  251. OIDTokenResponse *fakeResponse = [OIDTokenResponse testInstanceWithIDToken:newIdToken
  252. accessToken:kNewAccessToken
  253. expiresIn:@(kAccessTokenExpiresIn)
  254. refreshToken:kRefreshToken
  255. tokenRequest:nil];
  256. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback is called"];
  257. // Save the intermediate states.
  258. [user refreshTokensIfNeededWithCompletion:^(GIDGoogleUser * _Nullable user,
  259. NSError * _Nullable error) {
  260. [expectation fulfill];
  261. XCTAssertNil(error);
  262. XCTAssertEqualObjects(user.accessToken.tokenString, kNewAccessToken);
  263. [self verifyUser:user accessTokenExpiresIn:kAccessTokenExpiresIn];
  264. XCTAssertEqualObjects(user.idToken.tokenString, newIdToken);
  265. [self verifyUser:user idTokenExpiresIn:kNewIDTokenExpiresIn];
  266. }];
  267. _tokenFetchHandler(fakeResponse, nil);
  268. [self waitForExpectationsWithTimeout:1 handler:nil];
  269. }
  270. - (void)testRefreshTokensIfNeededWithCompletion_refresh_givenIDTokenExpired {
  271. // ID token expired 10 seconds ago. Access token will expire in 10 minutes.
  272. GIDGoogleUser *user = [self googleUserWithAccessTokenExpiresIn:10 * 60 idTokenExpiresIn:-10];
  273. // Creates a fake response.
  274. NSString *newIdToken = [self idTokenWithExpiresIn:kNewIDTokenExpiresIn];
  275. OIDTokenResponse *fakeResponse = [OIDTokenResponse testInstanceWithIDToken:newIdToken
  276. accessToken:kNewAccessToken
  277. expiresIn:@(kAccessTokenExpiresIn)
  278. refreshToken:kRefreshToken
  279. tokenRequest:nil];
  280. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback is called"];
  281. // Save the intermediate states.
  282. [user refreshTokensIfNeededWithCompletion:^(GIDGoogleUser * _Nullable user,
  283. NSError * _Nullable error) {
  284. [expectation fulfill];
  285. XCTAssertNil(error);
  286. XCTAssertEqualObjects(user.accessToken.tokenString, kNewAccessToken);
  287. [self verifyUser:user accessTokenExpiresIn:kAccessTokenExpiresIn];
  288. XCTAssertEqualObjects(user.idToken.tokenString, newIdToken);
  289. [self verifyUser:user idTokenExpiresIn:kNewIDTokenExpiresIn];
  290. }];
  291. _tokenFetchHandler(fakeResponse, nil);
  292. [self waitForExpectationsWithTimeout:1 handler:nil];
  293. }
  294. - (void)testRefreshTokensIfNeededWithCompletion_noRefresh_givenBothTokensNotExpired {
  295. // Both tokens will expire in 10 min.
  296. NSTimeInterval expiresIn = 10 * 60;
  297. GIDGoogleUser *user = [self googleUserWithAccessTokenExpiresIn:expiresIn
  298. idTokenExpiresIn:expiresIn];
  299. NSString *accessTokenStringBeforeRefresh = user.accessToken.tokenString;
  300. NSString *idTokenStringBeforeRefresh = user.idToken.tokenString;
  301. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback is called"];
  302. // Save the intermediate states.
  303. [user refreshTokensIfNeededWithCompletion:^(GIDGoogleUser * _Nullable user,
  304. NSError * _Nullable error) {
  305. [expectation fulfill];
  306. XCTAssertNil(error);
  307. }];
  308. [self waitForExpectationsWithTimeout:1 handler:nil];
  309. XCTAssertEqualObjects(user.accessToken.tokenString, accessTokenStringBeforeRefresh);
  310. [self verifyUser:user accessTokenExpiresIn:expiresIn];
  311. XCTAssertEqualObjects(user.idToken.tokenString, idTokenStringBeforeRefresh);
  312. [self verifyUser:user idTokenExpiresIn:expiresIn];
  313. }
  314. - (void)testRefreshTokensIfNeededWithCompletion_noRefresh_givenRefreshErrors {
  315. // Both tokens expired 10 second ago.
  316. NSTimeInterval expiresIn = -10;
  317. GIDGoogleUser *user = [self googleUserWithAccessTokenExpiresIn:expiresIn
  318. idTokenExpiresIn:expiresIn];
  319. NSString *accessTokenStringBeforeRefresh = user.accessToken.tokenString;
  320. NSString *idTokenStringBeforeRefresh = user.idToken.tokenString;
  321. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback is called"];
  322. // Save the intermediate states.
  323. [user refreshTokensIfNeededWithCompletion:^(GIDGoogleUser * _Nullable user,
  324. NSError * _Nullable error) {
  325. [expectation fulfill];
  326. XCTAssertNotNil(error);
  327. XCTAssertNil(user);
  328. }];
  329. _tokenFetchHandler(nil, [self fakeError]);
  330. [self waitForExpectationsWithTimeout:1 handler:nil];
  331. XCTAssertEqualObjects(user.accessToken.tokenString, accessTokenStringBeforeRefresh);
  332. [self verifyUser:user accessTokenExpiresIn:expiresIn];
  333. XCTAssertEqualObjects(user.idToken.tokenString, idTokenStringBeforeRefresh);
  334. [self verifyUser:user idTokenExpiresIn:expiresIn];
  335. }
  336. - (void)testRefreshTokensIfNeededWithCompletion_handleConcurrentRefresh {
  337. // Both tokens expired 10 second ago.
  338. NSTimeInterval expiresIn = -10;
  339. GIDGoogleUser *user = [self googleUserWithAccessTokenExpiresIn:expiresIn
  340. idTokenExpiresIn:expiresIn];
  341. // Creates a fake response.
  342. NSString *newIdToken = [self idTokenWithExpiresIn:kNewIDTokenExpiresIn];
  343. OIDTokenResponse *fakeResponse = [OIDTokenResponse testInstanceWithIDToken:newIdToken
  344. accessToken:kNewAccessToken
  345. expiresIn:@(kAccessTokenExpiresIn)
  346. refreshToken:kRefreshToken
  347. tokenRequest:nil];
  348. XCTestExpectation *firstExpectation =
  349. [self expectationWithDescription:@"First callback is called"];
  350. [user refreshTokensIfNeededWithCompletion:^(GIDGoogleUser *user, NSError *error) {
  351. [firstExpectation fulfill];
  352. XCTAssertNil(error);
  353. XCTAssertEqualObjects(user.accessToken.tokenString, kNewAccessToken);
  354. [self verifyUser:user accessTokenExpiresIn:kAccessTokenExpiresIn];
  355. XCTAssertEqualObjects(user.idToken.tokenString, newIdToken);
  356. [self verifyUser:user idTokenExpiresIn:kNewIDTokenExpiresIn];
  357. }];
  358. XCTestExpectation *secondExpectation =
  359. [self expectationWithDescription:@"Second callback is called"];
  360. [user refreshTokensIfNeededWithCompletion:^(GIDGoogleUser *user, NSError *error) {
  361. [secondExpectation fulfill];
  362. XCTAssertNil(error);
  363. XCTAssertEqualObjects(user.accessToken.tokenString, kNewAccessToken);
  364. [self verifyUser:user accessTokenExpiresIn:kAccessTokenExpiresIn];
  365. XCTAssertEqualObjects(user.idToken.tokenString, newIdToken);
  366. [self verifyUser:user idTokenExpiresIn:kNewIDTokenExpiresIn];
  367. }];
  368. _tokenFetchHandler(fakeResponse, nil);
  369. [self waitForExpectationsWithTimeout:1 handler:nil];
  370. }
  371. # pragma mark - Test `addScopes:`
  372. - (void)testAddScopes_success {
  373. id signIn = OCMClassMock([GIDSignIn class]);
  374. OCMStub([signIn sharedInstance]).andReturn(signIn);
  375. [[signIn expect] addScopes:OCMOCK_ANY
  376. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  377. presentingViewController:OCMOCK_ANY
  378. #elif TARGET_OS_OSX
  379. presentingWindow:OCMOCK_ANY
  380. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  381. completion:OCMOCK_ANY];
  382. GIDGoogleUser *currentUser = [self googleUserWithAccessTokenExpiresIn:kAccessTokenExpiresIn
  383. idTokenExpiresIn:kIDTokenExpiresIn];
  384. OCMStub([signIn currentUser]).andReturn(currentUser);
  385. [currentUser addScopes:@[kNewScope]
  386. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  387. presentingViewController:[[UIViewController alloc] init]
  388. #elif TARGET_OS_OSX
  389. presentingWindow:[[NSWindow alloc] init]
  390. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  391. completion:nil];
  392. [signIn verify];
  393. }
  394. - (void)testAddScopes_failure_addScopesToPreviousUser {
  395. id signIn = OCMClassMock([GIDSignIn class]);
  396. OCMStub([signIn sharedInstance]).andReturn(signIn);
  397. GIDGoogleUser *currentUser = [self googleUserWithAccessTokenExpiresIn:kAccessTokenExpiresIn
  398. idTokenExpiresIn:kIDTokenExpiresIn];
  399. OCMStub([signIn currentUser]).andReturn(currentUser);
  400. GIDGoogleUser *previousUser = [self googleUserWithAccessTokenExpiresIn:kAccessTokenExpiresIn
  401. idTokenExpiresIn:kNewIDTokenExpiresIn];
  402. XCTestExpectation *expectation =
  403. [self expectationWithDescription:@"Completion is called."];
  404. [previousUser addScopes:@[kNewScope]
  405. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  406. presentingViewController:[[UIViewController alloc] init]
  407. #elif TARGET_OS_OSX
  408. presentingWindow:[[NSWindow alloc] init]
  409. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  410. completion:^(GIDSignInResult *signInResult, NSError *error) {
  411. [expectation fulfill];
  412. XCTAssertNil(signInResult);
  413. XCTAssertEqual(error.code, kGIDSignInErrorCodeMismatchWithCurrentUser);
  414. }];
  415. [self waitForExpectationsWithTimeout:1 handler:nil];
  416. }
  417. - (void)testAddScopes_failure_addScopesToPreviousUser_currentUserIsNull {
  418. id signIn = OCMClassMock([GIDSignIn class]);
  419. OCMStub([signIn sharedInstance]).andReturn(signIn);
  420. GIDGoogleUser *currentUser = nil;
  421. OCMStub([signIn currentUser]).andReturn(currentUser);
  422. GIDGoogleUser *previousUser = [self googleUserWithAccessTokenExpiresIn:kAccessTokenExpiresIn
  423. idTokenExpiresIn:kNewIDTokenExpiresIn];
  424. XCTestExpectation *expectation =
  425. [self expectationWithDescription:@"Completion is called."];
  426. [previousUser addScopes:@[kNewScope]
  427. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  428. presentingViewController:[[UIViewController alloc] init]
  429. #elif TARGET_OS_OSX
  430. presentingWindow:[[NSWindow alloc] init]
  431. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  432. completion:^(GIDSignInResult *signInResult, NSError *error) {
  433. [expectation fulfill];
  434. XCTAssertNil(signInResult);
  435. XCTAssertEqual(error.code, kGIDSignInErrorCodeMismatchWithCurrentUser);
  436. }];
  437. [self waitForExpectationsWithTimeout:1 handler:nil];
  438. }
  439. #pragma mark - Helpers
  440. // Returns a GIDGoogleUser with different tokens expiresIn time. The token strings are constants.
  441. - (GIDGoogleUser *)googleUserWithAccessTokenExpiresIn:(NSTimeInterval)accessTokenExpiresIn
  442. idTokenExpiresIn:(NSTimeInterval)idTokenExpiresIn {
  443. NSString *idToken = [self idTokenWithExpiresIn:idTokenExpiresIn];
  444. OIDAuthState *authState = [OIDAuthState testInstanceWithIDToken:idToken
  445. accessToken:kAccessToken
  446. accessTokenExpiresIn:accessTokenExpiresIn
  447. refreshToken:kRefreshToken];
  448. return [[GIDGoogleUser alloc] initWithAuthState:authState profileData:nil];
  449. }
  450. - (NSString *)idTokenWithExpiresIn:(NSTimeInterval)expiresIn {
  451. // The expireTime should be based on 1970.
  452. NSTimeInterval expireTime = [[NSDate date] timeIntervalSince1970] + expiresIn;
  453. return [OIDTokenResponse idTokenWithSub:kUserID exp:@(expireTime)];
  454. }
  455. - (void)verifyUser:(GIDGoogleUser *)user accessTokenExpiresIn:(NSTimeInterval)expiresIn {
  456. NSDate *expectedAccessTokenExpirationDate = [[NSDate date] dateByAddingTimeInterval:expiresIn];
  457. XCTAssertEqualWithAccuracy([user.accessToken.expirationDate timeIntervalSince1970],
  458. [expectedAccessTokenExpirationDate timeIntervalSince1970],
  459. kTimeAccuracy);
  460. }
  461. - (void)verifyUser:(GIDGoogleUser *)user idTokenExpiresIn:(NSTimeInterval)expiresIn {
  462. NSDate *expectedIDTokenExpirationDate = [[NSDate date] dateByAddingTimeInterval:expiresIn];
  463. XCTAssertEqualWithAccuracy([user.idToken.expirationDate timeIntervalSince1970],
  464. [expectedIDTokenExpirationDate timeIntervalSince1970], kTimeAccuracy);
  465. }
  466. - (NSError *)fakeError {
  467. return [NSError errorWithDomain:@"fake.domain" code:-1 userInfo:nil];
  468. }
  469. @end