GIDAuthenticationTest.m 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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 <XCTest/XCTest.h>
  15. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDAuthentication.h"
  16. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDSignIn.h"
  17. #import "GoogleSignIn/Sources/GIDAuthentication_Private.h"
  18. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  19. #import "GoogleSignIn/Sources/GIDMDMPasscodeState.h"
  20. #import "GoogleSignIn/Sources/GIDSignInPreferences.h"
  21. #import "GoogleSignIn/Tests/Unit/OIDAuthState+Testing.h"
  22. #import "GoogleSignIn/Tests/Unit/OIDTokenRequest+Testing.h"
  23. #import "GoogleSignIn/Tests/Unit/OIDTokenResponse+Testing.h"
  24. #ifdef SWIFT_PACKAGE
  25. @import AppAuth;
  26. @import GoogleUtilities_MethodSwizzler;
  27. @import GoogleUtilities_SwizzlerTestHelpers;
  28. @import GTMAppAuth;
  29. @import GTMSessionFetcherCore;
  30. @import OCMock;
  31. #else
  32. #import <AppAuth/OIDAuthState.h>
  33. #import <AppAuth/OIDAuthorizationRequest.h>
  34. #import <AppAuth/OIDAuthorizationResponse.h>
  35. #import <AppAuth/OIDAuthorizationService.h>
  36. #import <AppAuth/OIDError.h>
  37. #import <AppAuth/OIDIDToken.h>
  38. #import <AppAuth/OIDServiceConfiguration.h>
  39. #import <AppAuth/OIDTokenRequest.h>
  40. #import <AppAuth/OIDTokenResponse.h>
  41. #import <GoogleUtilities/GULSwizzler.h>
  42. #import <GoogleUtilities/GULSwizzler+Unswizzle.h>
  43. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization.h>
  44. #import <GTMSessionFetcher/GTMSessionFetcher.h>
  45. #import <OCMock/OCMock.h>
  46. #endif
  47. static NSString *const kClientID = @"87654321.googleusercontent.com";
  48. static NSString *const kNewAccessToken = @"new_access_token";
  49. static NSString *const kUserEmail = @"foo@gmail.com";
  50. static NSTimeInterval const kExpireTime = 442886117;
  51. static NSTimeInterval const kNewExpireTime = 442886123;
  52. static NSTimeInterval const kNewExpireTime2 = 442886124;
  53. static NSTimeInterval const kTimeAccuracy = 10;
  54. // The system name in old iOS versions.
  55. static NSString *const kOldIOSName = @"iPhone OS";
  56. // The system name in new iOS versions.
  57. static NSString *const kNewIOSName = @"iOS";
  58. // List of observed properties of the class being tested.
  59. static NSString *const kObservedProperties[] = {
  60. @"accessToken",
  61. @"accessTokenExpirationDate",
  62. @"idToken",
  63. @"idTokenExpirationDate"
  64. };
  65. static const NSUInteger kNumberOfObservedProperties =
  66. sizeof(kObservedProperties) / sizeof(*kObservedProperties);
  67. // Bit position for notification change type bitmask flags.
  68. // Must match the list of observed properties above.
  69. typedef NS_ENUM(NSUInteger, ChangeType) {
  70. kChangeTypeAccessTokenPrior,
  71. kChangeTypeAccessToken,
  72. kChangeTypeAccessTokenExpirationDatePrior,
  73. kChangeTypeAccessTokenExpirationDate,
  74. kChangeTypeIDTokenPrior,
  75. kChangeTypeIDToken,
  76. kChangeTypeIDTokenExpirationDatePrior,
  77. kChangeTypeIDTokenExpirationDate,
  78. kChangeTypeEnd // not a real change type but an end mark for calculating |kChangeAll|
  79. };
  80. static const NSUInteger kChangeNone = 0u;
  81. static const NSUInteger kChangeAll = (1u << kChangeTypeEnd) - 1u;
  82. #if __has_feature(c_static_assert) || __has_extension(c_static_assert)
  83. _Static_assert(kChangeTypeEnd == (sizeof(kObservedProperties) / sizeof(*kObservedProperties)) * 2,
  84. "List of observed properties must match list of change notification enums");
  85. #endif
  86. @interface GIDAuthenticationTest : XCTestCase
  87. @end
  88. @implementation GIDAuthenticationTest {
  89. // Whether the auth object has ID token or not.
  90. BOOL _hasIDToken;
  91. // Fake data used to generate the expiration date of the access token.
  92. NSTimeInterval _accessTokenExpireTime;
  93. // Fake data used to generate the expiration date of the ID token.
  94. NSTimeInterval _idTokenExpireTime;
  95. // Fake data used to generate the additional token request parameters.
  96. NSDictionary *_additionalTokenRequestParameters;
  97. // The saved token fetch handler.
  98. OIDTokenCallback _tokenFetchHandler;
  99. // The saved token request.
  100. OIDTokenRequest *_tokenRequest;
  101. // All GIDAuthentication objects that are observed.
  102. NSMutableArray *_observedAuths;
  103. // Bitmask flags for observed changes, as specified in |ChangeType|.
  104. NSUInteger _changesObserved;
  105. // The fake system name used for testing.
  106. NSString *_fakeSystemName;
  107. }
  108. - (void)setUp {
  109. _hasIDToken = YES;
  110. _accessTokenExpireTime = kAccessTokenExpiresIn;
  111. _idTokenExpireTime = kExpireTime;
  112. _additionalTokenRequestParameters = nil;
  113. _tokenFetchHandler = nil;
  114. _tokenRequest = nil;
  115. [GULSwizzler swizzleClass:[OIDAuthorizationService class]
  116. selector:@selector(performTokenRequest:originalAuthorizationResponse:callback:)
  117. isClassSelector:YES
  118. withBlock:^(id sender,
  119. OIDTokenRequest *request,
  120. OIDAuthorizationResponse *authorizationResponse,
  121. OIDTokenCallback callback) {
  122. XCTAssertNotNil(authorizationResponse.request.clientID);
  123. XCTAssertNotNil(authorizationResponse.request.configuration.tokenEndpoint);
  124. XCTAssertNil(_tokenFetchHandler); // only one on-going fetch allowed
  125. _tokenFetchHandler = [callback copy];
  126. _tokenRequest = [request copy];
  127. return nil;
  128. }];
  129. _observedAuths = [[NSMutableArray alloc] init];
  130. _changesObserved = 0;
  131. _fakeSystemName = kNewIOSName;
  132. [GULSwizzler swizzleClass:[UIDevice class]
  133. selector:@selector(systemName)
  134. isClassSelector:NO
  135. withBlock:^(id sender) { return _fakeSystemName; }];
  136. }
  137. - (void)tearDown {
  138. [GULSwizzler unswizzleClass:[OIDAuthorizationService class]
  139. selector:@selector(performTokenRequest:originalAuthorizationResponse:callback:)
  140. isClassSelector:YES];
  141. [GULSwizzler unswizzleClass:[UIDevice class]
  142. selector:@selector(systemName)
  143. isClassSelector:NO];
  144. for (GIDAuthentication *auth in _observedAuths) {
  145. for (unsigned int i = 0; i < kNumberOfObservedProperties; ++i) {
  146. [auth removeObserver:self forKeyPath:kObservedProperties[i]];
  147. }
  148. }
  149. _observedAuths = nil;
  150. }
  151. #pragma mark - Tests
  152. - (void)testInitWithAuthState {
  153. OIDAuthState *authState = [OIDAuthState testInstance];
  154. GIDAuthentication *auth = [[GIDAuthentication alloc] initWithAuthState:authState];
  155. XCTAssertEqualObjects(auth.clientID, authState.lastAuthorizationResponse.request.clientID);
  156. XCTAssertEqualObjects(auth.accessToken, authState.lastTokenResponse.accessToken);
  157. XCTAssertEqualObjects(auth.accessTokenExpirationDate,
  158. authState.lastTokenResponse.accessTokenExpirationDate);
  159. XCTAssertEqualObjects(auth.refreshToken, authState.refreshToken);
  160. XCTAssertEqualObjects(auth.idToken, authState.lastTokenResponse.idToken);
  161. OIDIDToken *idToken = [[OIDIDToken alloc]
  162. initWithIDTokenString:authState.lastTokenResponse.idToken];
  163. XCTAssertEqualObjects(auth.idTokenExpirationDate, [idToken expiresAt]);
  164. }
  165. - (void)testInitWithAuthStateNoIDToken {
  166. OIDAuthState *authState = [OIDAuthState testInstanceWithIDToken:nil];
  167. GIDAuthentication *auth = [[GIDAuthentication alloc] initWithAuthState:authState];
  168. XCTAssertEqualObjects(auth.clientID, authState.lastAuthorizationResponse.request.clientID);
  169. XCTAssertEqualObjects(auth.accessToken, authState.lastTokenResponse.accessToken);
  170. XCTAssertEqualObjects(auth.accessTokenExpirationDate,
  171. authState.lastTokenResponse.accessTokenExpirationDate);
  172. XCTAssertEqualObjects(auth.refreshToken, authState.refreshToken);
  173. XCTAssertNil(auth.idToken);
  174. XCTAssertNil(auth.idTokenExpirationDate);
  175. }
  176. - (void)testAuthState {
  177. OIDAuthState *authState = [OIDAuthState testInstance];
  178. GIDAuthentication *auth = [[GIDAuthentication alloc] initWithAuthState:authState];
  179. OIDAuthState *authStateReturned = auth.authState;
  180. XCTAssertEqual(authState, authStateReturned);
  181. }
  182. - (void)testCoding {
  183. GIDAuthentication *auth = [self auth];
  184. NSData *data = [NSKeyedArchiver archivedDataWithRootObject:auth];
  185. GIDAuthentication *newAuth = [NSKeyedUnarchiver unarchiveObjectWithData:data];
  186. XCTAssertEqualObjects(auth, newAuth);
  187. XCTAssertTrue([GIDAuthentication supportsSecureCoding]);
  188. }
  189. - (void)testFetcherAuthorizer {
  190. // This is really hard to test without assuming how GTMAppAuthFetcherAuthorization works
  191. // internally, so let's just take the shortcut here by asserting we get a
  192. // GTMAppAuthFetcherAuthorization object.
  193. GIDAuthentication *auth = [self auth];
  194. id<GTMFetcherAuthorizationProtocol> fetcherAuthroizer = auth.fetcherAuthorizer;
  195. XCTAssertTrue([fetcherAuthroizer isKindOfClass:[GTMAppAuthFetcherAuthorization class]]);
  196. XCTAssertTrue([fetcherAuthroizer canAuthorize]);
  197. }
  198. - (void)testDoWithFreshTokensWithBothExpired {
  199. // Both tokens expired 10 seconds ago.
  200. [self setExpireTimeForAccessToken:-10 IDToken:-10];
  201. [self verifyTokensRefreshedWithMethod:@selector(doWithFreshTokens:)];
  202. }
  203. - (void)testDoWithFreshTokensWithAccessTokenExpired {
  204. // Access token expired 10 seconds ago while ID token to expire in 10 minutes.
  205. [self setExpireTimeForAccessToken:-10 IDToken:10 * 60];
  206. [self verifyTokensRefreshedWithMethod:@selector(doWithFreshTokens:)];
  207. }
  208. - (void)testDoWithFreshTokensWithIDTokenToExpire {
  209. // Access token to expire in 10 minutes while ID token to expire in 10 seconds.
  210. [self setExpireTimeForAccessToken:10 * 60 IDToken:10];
  211. [self verifyTokensRefreshedWithMethod:@selector(doWithFreshTokens:)];
  212. }
  213. - (void)testDoWithFreshTokensWithBothFresh {
  214. // Both tokens to expire in 10 minutes.
  215. [self setExpireTimeForAccessToken:10 * 60 IDToken:10 * 60];
  216. [self verifyTokensNotRefreshedWithMethod:@selector(doWithFreshTokens:)];
  217. }
  218. - (void)testDoWithFreshTokensWithAccessTokenExpiredAndNoIDToken {
  219. _hasIDToken = NO;
  220. [self setExpireTimeForAccessToken:-10 IDToken:10 * 60]; // access token expired 10 seconds ago
  221. [self verifyTokensRefreshedWithMethod:@selector(doWithFreshTokens:)];
  222. }
  223. - (void)testDoWithFreshTokensWithAccessTokenFreshAndNoIDToken {
  224. _hasIDToken = NO;
  225. [self setExpireTimeForAccessToken:10 * 60 IDToken:-10]; // access token to expire in 10 minutes
  226. [self verifyTokensNotRefreshedWithMethod:@selector(doWithFreshTokens:)];
  227. }
  228. - (void)testDoWithFreshTokensError {
  229. [self setTokensExpireTime:-10]; // expired 10 seconds ago
  230. GIDAuthentication *auth = [self observedAuth];
  231. __block BOOL callbackCalled = NO;
  232. [auth doWithFreshTokens:^(GIDAuthentication *authentication, NSError *error) {
  233. callbackCalled = YES;
  234. XCTAssertNil(authentication);
  235. XCTAssertNotNil(error);
  236. }];
  237. _tokenFetchHandler(nil, [self fakeError]);
  238. XCTAssertTrue(callbackCalled);
  239. [self assertOldTokensInAuth:auth];
  240. }
  241. - (void)testDoWithFreshTokensQueue {
  242. GIDAuthentication *auth = [self observedAuth];
  243. __block BOOL firstCallbackCalled = NO;
  244. [auth doWithFreshTokens:^(GIDAuthentication *authentication, NSError *error) {
  245. firstCallbackCalled = YES;
  246. [self assertNewTokensInAuth:authentication];
  247. XCTAssertNil(error);
  248. }];
  249. __block BOOL secondCallbackCalled = NO;
  250. [auth doWithFreshTokens:^(GIDAuthentication *authentication, NSError *error) {
  251. secondCallbackCalled = YES;
  252. [self assertNewTokensInAuth:authentication];
  253. XCTAssertNil(error);
  254. }];
  255. _tokenFetchHandler([self tokenResponseWithNewTokens], nil);
  256. XCTAssertTrue(firstCallbackCalled);
  257. XCTAssertTrue(secondCallbackCalled);
  258. [self assertNewTokensInAuth:auth];
  259. }
  260. #pragma mark - EMM Support
  261. - (void)testEMMSupport {
  262. _additionalTokenRequestParameters = @{
  263. @"emm_support" : @"xyz",
  264. };
  265. GIDAuthentication *auth = [self auth];
  266. [auth doWithFreshTokens:^(GIDAuthentication * _Nonnull authentication,
  267. NSError * _Nullable error) {}];
  268. _tokenFetchHandler([self tokenResponseWithNewTokens], nil);
  269. NSDictionary *expectedParameters = @{
  270. @"emm_support" : @"xyz",
  271. @"device_os" : [NSString stringWithFormat:@"%@ %@",
  272. _fakeSystemName, [UIDevice currentDevice].systemVersion],
  273. kSDKVersionLoggingParameter : GIDVersion(),
  274. };
  275. XCTAssertEqualObjects(auth.authState.lastTokenResponse.request.additionalParameters,
  276. expectedParameters);
  277. }
  278. - (void)testSystemNameNormalization {
  279. _fakeSystemName = kOldIOSName;
  280. _additionalTokenRequestParameters = @{
  281. @"emm_support" : @"xyz",
  282. };
  283. GIDAuthentication *auth = [self auth];
  284. [auth doWithFreshTokens:^(GIDAuthentication * _Nonnull authentication,
  285. NSError * _Nullable error) {}];
  286. _tokenFetchHandler([self tokenResponseWithNewTokens], nil);
  287. NSDictionary *expectedParameters = @{
  288. @"emm_support" : @"xyz",
  289. @"device_os" : [NSString stringWithFormat:@"%@ %@",
  290. kNewIOSName, [UIDevice currentDevice].systemVersion],
  291. kSDKVersionLoggingParameter : GIDVersion(),
  292. };
  293. XCTAssertEqualObjects(auth.authState.lastTokenResponse.request.additionalParameters,
  294. expectedParameters);
  295. }
  296. - (void)testEMMPasscodeInfo {
  297. _additionalTokenRequestParameters = @{
  298. @"emm_support" : @"xyz",
  299. @"device_os" : @"old one",
  300. @"emm_passcode_info" : @"something",
  301. };
  302. GIDAuthentication *auth = [self auth];
  303. [auth doWithFreshTokens:^(GIDAuthentication * _Nonnull authentication,
  304. NSError * _Nullable error) {}];
  305. _tokenFetchHandler([self tokenResponseWithNewTokens], nil);
  306. NSDictionary *expectedParameters = @{
  307. @"emm_support" : @"xyz",
  308. @"device_os" : [NSString stringWithFormat:@"%@ %@",
  309. _fakeSystemName, [UIDevice currentDevice].systemVersion],
  310. @"emm_passcode_info" : [GIDMDMPasscodeState passcodeState].info,
  311. kSDKVersionLoggingParameter : GIDVersion(),
  312. };
  313. XCTAssertEqualObjects(auth.authState.lastTokenResponse.request.additionalParameters,
  314. expectedParameters);
  315. }
  316. - (void)testEMMError {
  317. // Set expectations.
  318. NSDictionary *errorJSON = @{ @"error" : @"EMM Specific Error" };
  319. NSError *emmError = [NSError errorWithDomain:@"anydomain"
  320. code:12345
  321. userInfo:@{ OIDOAuthErrorResponseErrorKey : errorJSON }];
  322. id mockEMMErrorHandler = OCMStrictClassMock([GIDEMMErrorHandler class]);
  323. [[[mockEMMErrorHandler stub] andReturn:mockEMMErrorHandler] sharedInstance];
  324. __block void (^completion)(void);
  325. [[[mockEMMErrorHandler expect] andReturnValue:@YES]
  326. handleErrorFromResponse:errorJSON completion:[OCMArg checkWithBlock:^(id arg) {
  327. completion = arg;
  328. return YES;
  329. }]];
  330. // Start testing.
  331. _additionalTokenRequestParameters = @{
  332. @"emm_support" : @"xyz",
  333. };
  334. GIDAuthentication *auth = [self auth];
  335. __block BOOL callbackCalled = NO;
  336. [auth doWithFreshTokens:^(GIDAuthentication *authentication, NSError *error) {
  337. callbackCalled = YES;
  338. XCTAssertNil(authentication);
  339. XCTAssertEqualObjects(error.domain, kGIDSignInErrorDomain);
  340. XCTAssertEqual(error.code, kGIDSignInErrorCodeEMM);
  341. }];
  342. _tokenFetchHandler(nil, emmError);
  343. // Verify and clean up.
  344. [mockEMMErrorHandler verify];
  345. [mockEMMErrorHandler stopMocking];
  346. XCTAssertFalse(callbackCalled);
  347. completion();
  348. XCTAssertTrue(callbackCalled);
  349. [self assertOldTokensInAuth:auth];
  350. }
  351. - (void)testNonEMMError {
  352. // Set expectations.
  353. NSDictionary *errorJSON = @{ @"error" : @"Not EMM Specific Error" };
  354. NSError *emmError = [NSError errorWithDomain:@"anydomain"
  355. code:12345
  356. userInfo:@{ OIDOAuthErrorResponseErrorKey : errorJSON }];
  357. id mockEMMErrorHandler = OCMStrictClassMock([GIDEMMErrorHandler class]);
  358. [[[mockEMMErrorHandler stub] andReturn:mockEMMErrorHandler] sharedInstance];
  359. __block void (^completion)(void);
  360. [[[mockEMMErrorHandler expect] andReturnValue:@NO]
  361. handleErrorFromResponse:errorJSON completion:[OCMArg checkWithBlock:^(id arg) {
  362. completion = arg;
  363. return YES;
  364. }]];
  365. // Start testing.
  366. _additionalTokenRequestParameters = @{
  367. @"emm_support" : @"xyz",
  368. };
  369. GIDAuthentication *auth = [self auth];
  370. __block BOOL callbackCalled = NO;
  371. [auth doWithFreshTokens:^(GIDAuthentication *authentication, NSError *error) {
  372. callbackCalled = YES;
  373. XCTAssertNil(authentication);
  374. XCTAssertEqualObjects(error.domain, @"anydomain");
  375. XCTAssertEqual(error.code, 12345);
  376. }];
  377. _tokenFetchHandler(nil, emmError);
  378. // Verify and clean up.
  379. [mockEMMErrorHandler verify];
  380. [mockEMMErrorHandler stopMocking];
  381. XCTAssertFalse(callbackCalled);
  382. completion();
  383. XCTAssertTrue(callbackCalled);
  384. [self assertOldTokensInAuth:auth];
  385. }
  386. - (void)testCodingPreserveEMMParameters {
  387. _additionalTokenRequestParameters = @{
  388. @"emm_support" : @"xyz",
  389. @"device_os" : @"old one",
  390. @"emm_passcode_info" : @"something",
  391. };
  392. NSData *data = [NSKeyedArchiver archivedDataWithRootObject:[self auth]];
  393. GIDAuthentication *auth = [NSKeyedUnarchiver unarchiveObjectWithData:data];
  394. [auth doWithFreshTokens:^(GIDAuthentication * _Nonnull authentication,
  395. NSError * _Nullable error) {}];
  396. _tokenFetchHandler([self tokenResponseWithNewTokens], nil);
  397. NSDictionary *expectedParameters = @{
  398. @"emm_support" : @"xyz",
  399. @"device_os" : [NSString stringWithFormat:@"%@ %@",
  400. [UIDevice currentDevice].systemName, [UIDevice currentDevice].systemVersion],
  401. @"emm_passcode_info" : [GIDMDMPasscodeState passcodeState].info,
  402. kSDKVersionLoggingParameter : GIDVersion(),
  403. };
  404. XCTAssertEqualObjects(auth.authState.lastTokenResponse.request.additionalParameters,
  405. expectedParameters);
  406. }
  407. #pragma mark - NSKeyValueObserving
  408. - (void)observeValueForKeyPath:(NSString *)keyPath
  409. ofObject:(id)object
  410. change:(NSDictionary *)change
  411. context:(void *)context {
  412. GIDAuthentication *auth = (GIDAuthentication *)object;
  413. ChangeType changeType;
  414. if ([keyPath isEqualToString:@"accessToken"]) {
  415. if (change[NSKeyValueChangeNotificationIsPriorKey]) {
  416. XCTAssertEqualObjects(auth.accessToken, kAccessToken);
  417. changeType = kChangeTypeAccessTokenPrior;
  418. } else {
  419. XCTAssertEqualObjects(auth.accessToken, kNewAccessToken);
  420. changeType = kChangeTypeAccessToken;
  421. }
  422. } else if ([keyPath isEqualToString:@"accessTokenExpirationDate"]) {
  423. if (change[NSKeyValueChangeNotificationIsPriorKey]) {
  424. [self assertDate:auth.accessTokenExpirationDate equalTime:_accessTokenExpireTime];
  425. changeType = kChangeTypeAccessTokenExpirationDatePrior;
  426. } else {
  427. [self assertDate:auth.accessTokenExpirationDate equalTime:kNewExpireTime];
  428. changeType = kChangeTypeAccessTokenExpirationDate;
  429. }
  430. } else if ([keyPath isEqualToString:@"idToken"]) {
  431. if (change[NSKeyValueChangeNotificationIsPriorKey]) {
  432. XCTAssertEqualObjects(auth.idToken, [self idToken]);
  433. changeType = kChangeTypeIDTokenPrior;
  434. } else {
  435. XCTAssertEqualObjects(auth.idToken, [self idTokenNew]);
  436. changeType = kChangeTypeIDToken;
  437. }
  438. } else if ([keyPath isEqualToString:@"idTokenExpirationDate"]) {
  439. if (change[NSKeyValueChangeNotificationIsPriorKey]) {
  440. if (_hasIDToken) {
  441. [self assertDate:auth.idTokenExpirationDate equalTime:_idTokenExpireTime];
  442. }
  443. changeType = kChangeTypeIDTokenExpirationDatePrior;
  444. } else {
  445. if (_hasIDToken) {
  446. [self assertDate:auth.idTokenExpirationDate equalTime:kNewExpireTime2];
  447. }
  448. changeType = kChangeTypeIDTokenExpirationDate;
  449. }
  450. } else {
  451. XCTFail(@"unexpected keyPath");
  452. return; // so compiler knows |changeType| is always assigned
  453. }
  454. NSUInteger changeMask = 1u << changeType;
  455. XCTAssertFalse(_changesObserved & changeMask); // each change type should only fire once
  456. _changesObserved |= changeMask;
  457. }
  458. #pragma mark - Helpers
  459. - (GIDAuthentication *)auth {
  460. NSString *idToken = [self idToken];
  461. NSNumber *accessTokenExpiresIn =
  462. @(_accessTokenExpireTime - [[NSDate date] timeIntervalSinceReferenceDate]);
  463. OIDTokenRequest *tokenRequest =
  464. [OIDTokenRequest testInstanceWithAdditionalParameters:_additionalTokenRequestParameters];
  465. OIDTokenResponse *tokenResponse =
  466. [OIDTokenResponse testInstanceWithIDToken:idToken
  467. accessToken:kAccessToken
  468. expiresIn:accessTokenExpiresIn
  469. tokenRequest:tokenRequest];
  470. return [[GIDAuthentication alloc]
  471. initWithAuthState:[OIDAuthState testInstanceWithTokenResponse:tokenResponse]];
  472. }
  473. - (NSString *)idTokenWithExpireTime:(NSTimeInterval)expireTime {
  474. if (!_hasIDToken) {
  475. return nil;
  476. }
  477. return [OIDTokenResponse idTokenWithSub:kUserID exp:@(expireTime + NSTimeIntervalSince1970)];
  478. }
  479. - (NSString *)idToken {
  480. return [self idTokenWithExpireTime:_idTokenExpireTime];
  481. }
  482. - (NSString *)idTokenNew {
  483. return [self idTokenWithExpireTime:kNewExpireTime2];
  484. }
  485. // Return the auth object that has certain property changes observed.
  486. - (GIDAuthentication *)observedAuth {
  487. GIDAuthentication *auth = [self auth];
  488. for (unsigned int i = 0; i < kNumberOfObservedProperties; ++i) {
  489. [auth addObserver:self
  490. forKeyPath:kObservedProperties[i]
  491. options:NSKeyValueObservingOptionPrior
  492. context:NULL];
  493. }
  494. [_observedAuths addObject:auth];
  495. return auth;
  496. }
  497. - (OIDTokenResponse *)tokenResponseWithNewTokens {
  498. NSNumber *expiresIn = @(kNewExpireTime - [NSDate timeIntervalSinceReferenceDate]);
  499. return [OIDTokenResponse testInstanceWithIDToken:(_hasIDToken ? [self idTokenNew] : nil)
  500. accessToken:kNewAccessToken
  501. expiresIn:expiresIn
  502. tokenRequest:_tokenRequest ?: nil];
  503. }
  504. - (NSError *)fakeError {
  505. return [NSError errorWithDomain:@"fake.domain" code:-1 userInfo:nil];
  506. }
  507. - (void)assertDate:(NSDate *)date equalTime:(NSTimeInterval)time {
  508. XCTAssertEqualWithAccuracy([date timeIntervalSinceReferenceDate], time, kTimeAccuracy);
  509. }
  510. - (void)assertOldAccessTokenInAuth:(GIDAuthentication *)auth {
  511. XCTAssertEqualObjects(auth.accessToken, kAccessToken);
  512. [self assertDate:auth.accessTokenExpirationDate equalTime:_accessTokenExpireTime];
  513. XCTAssertEqual(_changesObserved, kChangeNone);
  514. }
  515. - (void)assertNewAccessTokenInAuth:(GIDAuthentication *)auth {
  516. XCTAssertEqualObjects(auth.accessToken, kNewAccessToken);
  517. [self assertDate:auth.accessTokenExpirationDate equalTime:kNewExpireTime];
  518. XCTAssertEqual(_changesObserved, kChangeAll);
  519. }
  520. - (void)assertOldTokensInAuth:(GIDAuthentication *)auth {
  521. [self assertOldAccessTokenInAuth:auth];
  522. XCTAssertEqualObjects(auth.idToken, [self idToken]);
  523. if (_hasIDToken) {
  524. [self assertDate:auth.idTokenExpirationDate equalTime:_idTokenExpireTime];
  525. }
  526. }
  527. - (void)assertNewTokensInAuth:(GIDAuthentication *)auth {
  528. [self assertNewAccessTokenInAuth:auth];
  529. XCTAssertEqualObjects(auth.idToken, [self idTokenNew]);
  530. if (_hasIDToken) {
  531. [self assertDate:auth.idTokenExpirationDate equalTime:kNewExpireTime2];
  532. }
  533. }
  534. - (void)setTokensExpireTime:(NSTimeInterval)fromNow {
  535. [self setExpireTimeForAccessToken:fromNow IDToken:fromNow];
  536. }
  537. - (void)setExpireTimeForAccessToken:(NSTimeInterval)accessExpire IDToken:(NSTimeInterval)idExpire {
  538. _accessTokenExpireTime = [[NSDate date] timeIntervalSinceReferenceDate] + accessExpire;
  539. _idTokenExpireTime = [[NSDate date] timeIntervalSinceReferenceDate] + idExpire;
  540. }
  541. - (void)verifyTokensRefreshedWithMethod:(SEL)sel {
  542. GIDAuthentication *auth = [self observedAuth];
  543. __block BOOL callbackCalled = NO;
  544. #pragma clang diagnostic push
  545. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  546. // We know the method doesn't return anything, so there is no risk of leaking.
  547. [auth performSelector:sel withObject:^(GIDAuthentication *authentication, NSError *error) {
  548. #pragma clang diagnostic pop
  549. callbackCalled = YES;
  550. [self assertNewTokensInAuth:authentication];
  551. XCTAssertNil(error);
  552. }];
  553. _tokenFetchHandler([self tokenResponseWithNewTokens], nil);
  554. XCTAssertTrue(callbackCalled);
  555. [self assertNewTokensInAuth:auth];
  556. }
  557. - (void)verifyTokensNotRefreshedWithMethod:(SEL)sel {
  558. GIDAuthentication *auth = [self observedAuth];
  559. __block BOOL callbackCalled = NO;
  560. #pragma clang diagnostic push
  561. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  562. // We know the method doesn't return anything, so there is no risk of leaking.
  563. [auth performSelector:sel withObject:^(GIDAuthentication *authentication, NSError *error) {
  564. #pragma clang diagnostic pop
  565. callbackCalled = YES;
  566. [self assertOldTokensInAuth:authentication];
  567. XCTAssertNil(error);
  568. }];
  569. XCTAssertNil(_tokenFetchHandler);
  570. XCTAssertTrue(callbackCalled);
  571. [self assertOldTokensInAuth:auth];
  572. }
  573. @end