GIDGoogleUserTest.m 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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 `doWithFreshTokens:`
  200. - (void)testDoWithFreshTokens_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 doWithFreshTokens:^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) {
  207. [expectation fulfill];
  208. XCTAssertNil(error);
  209. XCTAssertEqualObjects(user.accessToken.tokenString, kNewAccessToken);
  210. [self verifyUser:user accessTokenExpiresIn:kAccessTokenExpiresIn];
  211. XCTAssertEqualObjects(user.idToken.tokenString, newIdToken);
  212. [self verifyUser:user idTokenExpiresIn:kNewIDTokenExpiresIn];
  213. }];
  214. // Creates a fake response.
  215. OIDTokenResponse *fakeResponse = [OIDTokenResponse testInstanceWithIDToken:newIdToken
  216. accessToken:kNewAccessToken
  217. expiresIn:@(kAccessTokenExpiresIn)
  218. refreshToken:kRefreshToken
  219. tokenRequest:nil];
  220. _tokenFetchHandler(fakeResponse, nil);
  221. [self waitForExpectationsWithTimeout:1 handler:nil];
  222. }
  223. - (void)testDoWithRefreshTokens_refresh_givenBothTokensExpired_NoNewIDToken {
  224. // Both tokens expired 10 seconds ago.
  225. GIDGoogleUser *user = [self googleUserWithAccessTokenExpiresIn:-10 idTokenExpiresIn:-10];
  226. // Creates a fake response without ID token.
  227. OIDTokenResponse *fakeResponse = [OIDTokenResponse testInstanceWithIDToken:nil
  228. accessToken:kNewAccessToken
  229. expiresIn:@(kAccessTokenExpiresIn)
  230. refreshToken:kRefreshToken
  231. tokenRequest:nil];
  232. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback is called"];
  233. // Save the intermediate states.
  234. [user doWithFreshTokens:^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) {
  235. [expectation fulfill];
  236. XCTAssertNil(error);
  237. XCTAssertEqualObjects(user.accessToken.tokenString, kNewAccessToken);
  238. [self verifyUser:user accessTokenExpiresIn:kAccessTokenExpiresIn];
  239. XCTAssertNil(user.idToken);
  240. }];
  241. _tokenFetchHandler(fakeResponse, nil);
  242. [self waitForExpectationsWithTimeout:1 handler:nil];
  243. }
  244. - (void)testDoWithFreshTokens_refresh_givenAccessTokenExpired {
  245. // Access token expired 10 seconds ago. ID token will expire in 10 minutes.
  246. GIDGoogleUser *user = [self googleUserWithAccessTokenExpiresIn:-10 idTokenExpiresIn:10 * 60];
  247. // Creates a fake response.
  248. NSString *newIdToken = [self idTokenWithExpiresIn:kNewIDTokenExpiresIn];
  249. OIDTokenResponse *fakeResponse = [OIDTokenResponse testInstanceWithIDToken:newIdToken
  250. accessToken:kNewAccessToken
  251. expiresIn:@(kAccessTokenExpiresIn)
  252. refreshToken:kRefreshToken
  253. tokenRequest:nil];
  254. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback is called"];
  255. // Save the intermediate states.
  256. [user doWithFreshTokens:^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) {
  257. [expectation fulfill];
  258. XCTAssertNil(error);
  259. XCTAssertEqualObjects(user.accessToken.tokenString, kNewAccessToken);
  260. [self verifyUser:user accessTokenExpiresIn:kAccessTokenExpiresIn];
  261. XCTAssertEqualObjects(user.idToken.tokenString, newIdToken);
  262. [self verifyUser:user idTokenExpiresIn:kNewIDTokenExpiresIn];
  263. }];
  264. _tokenFetchHandler(fakeResponse, nil);
  265. [self waitForExpectationsWithTimeout:1 handler:nil];
  266. }
  267. - (void)testDoWithFreshTokens_refresh_givenIDTokenExpired {
  268. // ID token expired 10 seconds ago. Access token will expire in 10 minutes.
  269. GIDGoogleUser *user = [self googleUserWithAccessTokenExpiresIn:10 * 60 idTokenExpiresIn:-10];
  270. // Creates a fake response.
  271. NSString *newIdToken = [self idTokenWithExpiresIn:kNewIDTokenExpiresIn];
  272. OIDTokenResponse *fakeResponse = [OIDTokenResponse testInstanceWithIDToken:newIdToken
  273. accessToken:kNewAccessToken
  274. expiresIn:@(kAccessTokenExpiresIn)
  275. refreshToken:kRefreshToken
  276. tokenRequest:nil];
  277. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback is called"];
  278. // Save the intermediate states.
  279. [user doWithFreshTokens:^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) {
  280. [expectation fulfill];
  281. XCTAssertNil(error);
  282. XCTAssertEqualObjects(user.accessToken.tokenString, kNewAccessToken);
  283. [self verifyUser:user accessTokenExpiresIn:kAccessTokenExpiresIn];
  284. XCTAssertEqualObjects(user.idToken.tokenString, newIdToken);
  285. [self verifyUser:user idTokenExpiresIn:kNewIDTokenExpiresIn];
  286. }];
  287. _tokenFetchHandler(fakeResponse, nil);
  288. [self waitForExpectationsWithTimeout:1 handler:nil];
  289. }
  290. - (void)testDoWithFreshTokens_noRefresh_givenBothTokensNotExpired {
  291. // Both tokens will expire in 10 min.
  292. NSTimeInterval expiresIn = 10 * 60;
  293. GIDGoogleUser *user = [self googleUserWithAccessTokenExpiresIn:expiresIn
  294. idTokenExpiresIn:expiresIn];
  295. NSString *accessTokenStringBeforeRefresh = user.accessToken.tokenString;
  296. NSString *idTokenStringBeforeRefresh = user.idToken.tokenString;
  297. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback is called"];
  298. // Save the intermediate states.
  299. [user doWithFreshTokens:^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) {
  300. [expectation fulfill];
  301. XCTAssertNil(error);
  302. }];
  303. [self waitForExpectationsWithTimeout:1 handler:nil];
  304. XCTAssertEqualObjects(user.accessToken.tokenString, accessTokenStringBeforeRefresh);
  305. [self verifyUser:user accessTokenExpiresIn:expiresIn];
  306. XCTAssertEqualObjects(user.idToken.tokenString, idTokenStringBeforeRefresh);
  307. [self verifyUser:user idTokenExpiresIn:expiresIn];
  308. }
  309. - (void)testDoWithFreshTokens_noRefresh_givenRefreshErrors {
  310. // Both tokens expired 10 second ago.
  311. NSTimeInterval expiresIn = -10;
  312. GIDGoogleUser *user = [self googleUserWithAccessTokenExpiresIn:expiresIn
  313. idTokenExpiresIn:expiresIn];
  314. NSString *accessTokenStringBeforeRefresh = user.accessToken.tokenString;
  315. NSString *idTokenStringBeforeRefresh = user.idToken.tokenString;
  316. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback is called"];
  317. // Save the intermediate states.
  318. [user doWithFreshTokens:^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) {
  319. [expectation fulfill];
  320. XCTAssertNotNil(error);
  321. XCTAssertNil(user);
  322. }];
  323. _tokenFetchHandler(nil, [self fakeError]);
  324. [self waitForExpectationsWithTimeout:1 handler:nil];
  325. XCTAssertEqualObjects(user.accessToken.tokenString, accessTokenStringBeforeRefresh);
  326. [self verifyUser:user accessTokenExpiresIn:expiresIn];
  327. XCTAssertEqualObjects(user.idToken.tokenString, idTokenStringBeforeRefresh);
  328. [self verifyUser:user idTokenExpiresIn:expiresIn];
  329. }
  330. - (void)testDoWithFreshTokens_handleConcurrentRefresh {
  331. // Both tokens expired 10 second ago.
  332. NSTimeInterval expiresIn = -10;
  333. GIDGoogleUser *user = [self googleUserWithAccessTokenExpiresIn:expiresIn
  334. idTokenExpiresIn:expiresIn];
  335. // Creates a fake response.
  336. NSString *newIdToken = [self idTokenWithExpiresIn:kNewIDTokenExpiresIn];
  337. OIDTokenResponse *fakeResponse = [OIDTokenResponse testInstanceWithIDToken:newIdToken
  338. accessToken:kNewAccessToken
  339. expiresIn:@(kAccessTokenExpiresIn)
  340. refreshToken:kRefreshToken
  341. tokenRequest:nil];
  342. XCTestExpectation *firstExpectation =
  343. [self expectationWithDescription:@"First callback is called"];
  344. [user doWithFreshTokens:^(GIDGoogleUser *user, NSError *error) {
  345. [firstExpectation fulfill];
  346. XCTAssertNil(error);
  347. XCTAssertEqualObjects(user.accessToken.tokenString, kNewAccessToken);
  348. [self verifyUser:user accessTokenExpiresIn:kAccessTokenExpiresIn];
  349. XCTAssertEqualObjects(user.idToken.tokenString, newIdToken);
  350. [self verifyUser:user idTokenExpiresIn:kNewIDTokenExpiresIn];
  351. }];
  352. XCTestExpectation *secondExpectation =
  353. [self expectationWithDescription:@"Second callback is called"];
  354. [user doWithFreshTokens:^(GIDGoogleUser *user, NSError *error) {
  355. [secondExpectation fulfill];
  356. XCTAssertNil(error);
  357. XCTAssertEqualObjects(user.accessToken.tokenString, kNewAccessToken);
  358. [self verifyUser:user accessTokenExpiresIn:kAccessTokenExpiresIn];
  359. XCTAssertEqualObjects(user.idToken.tokenString, newIdToken);
  360. [self verifyUser:user idTokenExpiresIn:kNewIDTokenExpiresIn];
  361. }];
  362. _tokenFetchHandler(fakeResponse, nil);
  363. [self waitForExpectationsWithTimeout:1 handler:nil];
  364. }
  365. - (void)testAddScopes_success {
  366. id signIn = OCMClassMock([GIDSignIn class]);
  367. OCMStub([signIn sharedInstance]).andReturn(signIn);
  368. [[signIn expect] addScopes:OCMOCK_ANY
  369. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  370. presentingViewController:OCMOCK_ANY
  371. #elif TARGET_OS_OSX
  372. presentingWindow:OCMOCK_ANY
  373. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  374. completion:OCMOCK_ANY];
  375. GIDGoogleUser *currentUser = [self googleUserWithAccessTokenExpiresIn:kAccessTokenExpiresIn
  376. idTokenExpiresIn:kIDTokenExpiresIn];
  377. OCMStub([signIn currentUser]).andReturn(currentUser);
  378. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  379. UIViewController *presentingViewController = [[UIViewController alloc] init];
  380. [currentUser addScopes:@[kNewScope]
  381. presentingViewController:presentingViewController
  382. completion:nil];
  383. #elif TARGET_OS_OSX
  384. NSWindow *presentingWindow = [[NSWindow alloc] init];
  385. [currentUser addScopes:@[kNewScope]
  386. presentingWindow:presentingWindow
  387. completion:nil];
  388. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  389. [signIn verify];
  390. }
  391. - (void)testAddScopes_failure_addScopesToPreviousAccount {
  392. id signIn = OCMClassMock([GIDSignIn class]);
  393. OCMStub([signIn sharedInstance]).andReturn(signIn);
  394. GIDGoogleUser *currentUser = [self googleUserWithAccessTokenExpiresIn:kAccessTokenExpiresIn
  395. idTokenExpiresIn:kIDTokenExpiresIn];
  396. OCMStub([signIn currentUser]).andReturn(currentUser);
  397. GIDGoogleUser *previousUser = [self googleUserWithAccessTokenExpiresIn:kAccessTokenExpiresIn
  398. idTokenExpiresIn:kNewIDTokenExpiresIn];
  399. XCTestExpectation *expectation =
  400. [self expectationWithDescription:@"Completion is called."];
  401. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  402. UIViewController *presentingViewController = [[UIViewController alloc] init];
  403. [previousUser addScopes:@[kNewScope]
  404. presentingViewController:presentingViewController
  405. completion:^(GIDUserAuth *userAuth, NSError *error) {
  406. [expectation fulfill];
  407. XCTAssertNil(userAuth);
  408. XCTAssertEqual(error.code, kGIDSignInErrorCodePreviousUser);
  409. }];
  410. #elif TARGET_OS_OSX
  411. NSWindow *presentingWindow = [[NSWindow alloc] init];
  412. [previousUser addScopes:@[kNewScope]
  413. presentingWindow:presentingWindow
  414. completion:^(GIDUserAuth *userAuth, NSError *error) {
  415. [expectation fulfill];
  416. XCTAssertNil(userAuth);
  417. XCTAssertEqual(error.code, kGIDSignInErrorCodePreviousUser);
  418. }];
  419. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  420. [self waitForExpectationsWithTimeout:1 handler:nil];
  421. }
  422. #pragma mark - Helpers
  423. // Returns a GIDGoogleUser with different tokens expiresIn time. The token strings are constants.
  424. - (GIDGoogleUser *)googleUserWithAccessTokenExpiresIn:(NSTimeInterval)accessTokenExpiresIn
  425. idTokenExpiresIn:(NSTimeInterval)idTokenExpiresIn {
  426. NSString *idToken = [self idTokenWithExpiresIn:idTokenExpiresIn];
  427. OIDAuthState *authState = [OIDAuthState testInstanceWithIDToken:idToken
  428. accessToken:kAccessToken
  429. accessTokenExpiresIn:accessTokenExpiresIn
  430. refreshToken:kRefreshToken];
  431. return [[GIDGoogleUser alloc] initWithAuthState:authState profileData:nil];
  432. }
  433. - (NSString *)idTokenWithExpiresIn:(NSTimeInterval)expiresIn {
  434. // The expireTime should be based on 1970.
  435. NSTimeInterval expireTime = [[NSDate date] timeIntervalSince1970] + expiresIn;
  436. return [OIDTokenResponse idTokenWithSub:kUserID exp:@(expireTime)];
  437. }
  438. - (void)verifyUser:(GIDGoogleUser *)user accessTokenExpiresIn:(NSTimeInterval)expiresIn {
  439. NSDate *expectedAccessTokenExpirationDate = [[NSDate date] dateByAddingTimeInterval:expiresIn];
  440. XCTAssertEqualWithAccuracy([user.accessToken.expirationDate timeIntervalSince1970],
  441. [expectedAccessTokenExpirationDate timeIntervalSince1970],
  442. kTimeAccuracy);
  443. }
  444. - (void)verifyUser:(GIDGoogleUser *)user idTokenExpiresIn:(NSTimeInterval)expiresIn {
  445. NSDate *expectedIDTokenExpirationDate = [[NSDate date] dateByAddingTimeInterval:expiresIn];
  446. XCTAssertEqualWithAccuracy([user.idToken.expirationDate timeIntervalSince1970],
  447. [expectedIDTokenExpirationDate timeIntervalSince1970], kTimeAccuracy);
  448. }
  449. - (NSError *)fakeError {
  450. return [NSError errorWithDomain:@"fake.domain" code:-1 userInfo:nil];
  451. }
  452. @end