GIDAuthenticationTest.m 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback is called"];
  232. [auth doWithFreshTokens:^(GIDAuthentication *authentication, NSError *error) {
  233. [expectation fulfill];
  234. XCTAssertNil(authentication);
  235. XCTAssertNotNil(error);
  236. }];
  237. _tokenFetchHandler(nil, [self fakeError]);
  238. [self waitForExpectationsWithTimeout:1 handler:nil];
  239. [self assertOldTokensInAuth:auth];
  240. }
  241. - (void)testDoWithFreshTokensQueue {
  242. GIDAuthentication *auth = [self observedAuth];
  243. XCTestExpectation *firstExpectation =
  244. [self expectationWithDescription:@"First callback is called"];
  245. [auth doWithFreshTokens:^(GIDAuthentication *authentication, NSError *error) {
  246. [firstExpectation fulfill];
  247. [self assertNewTokensInAuth:authentication];
  248. XCTAssertNil(error);
  249. }];
  250. XCTestExpectation *secondExpectation =
  251. [self expectationWithDescription:@"Second callback is called"];
  252. [auth doWithFreshTokens:^(GIDAuthentication *authentication, NSError *error) {
  253. [secondExpectation fulfill];
  254. [self assertNewTokensInAuth:authentication];
  255. XCTAssertNil(error);
  256. }];
  257. _tokenFetchHandler([self tokenResponseWithNewTokens], nil);
  258. [self waitForExpectationsWithTimeout:1 handler:nil];
  259. [self assertNewTokensInAuth:auth];
  260. }
  261. #pragma mark - EMM Support
  262. - (void)testEMMSupport {
  263. _additionalTokenRequestParameters = @{
  264. @"emm_support" : @"xyz",
  265. };
  266. GIDAuthentication *auth = [self auth];
  267. [auth doWithFreshTokens:^(GIDAuthentication * _Nonnull authentication,
  268. NSError * _Nullable error) {}];
  269. _tokenFetchHandler([self tokenResponseWithNewTokens], nil);
  270. NSDictionary *expectedParameters = @{
  271. @"emm_support" : @"xyz",
  272. @"device_os" : [NSString stringWithFormat:@"%@ %@",
  273. _fakeSystemName, [UIDevice currentDevice].systemVersion],
  274. kSDKVersionLoggingParameter : GIDVersion(),
  275. };
  276. XCTAssertEqualObjects(auth.authState.lastTokenResponse.request.additionalParameters,
  277. expectedParameters);
  278. }
  279. - (void)testSystemNameNormalization {
  280. _fakeSystemName = kOldIOSName;
  281. _additionalTokenRequestParameters = @{
  282. @"emm_support" : @"xyz",
  283. };
  284. GIDAuthentication *auth = [self auth];
  285. [auth doWithFreshTokens:^(GIDAuthentication * _Nonnull authentication,
  286. NSError * _Nullable error) {}];
  287. _tokenFetchHandler([self tokenResponseWithNewTokens], nil);
  288. NSDictionary *expectedParameters = @{
  289. @"emm_support" : @"xyz",
  290. @"device_os" : [NSString stringWithFormat:@"%@ %@",
  291. kNewIOSName, [UIDevice currentDevice].systemVersion],
  292. kSDKVersionLoggingParameter : GIDVersion(),
  293. };
  294. XCTAssertEqualObjects(auth.authState.lastTokenResponse.request.additionalParameters,
  295. expectedParameters);
  296. }
  297. - (void)testEMMPasscodeInfo {
  298. _additionalTokenRequestParameters = @{
  299. @"emm_support" : @"xyz",
  300. @"device_os" : @"old one",
  301. @"emm_passcode_info" : @"something",
  302. };
  303. GIDAuthentication *auth = [self auth];
  304. [auth doWithFreshTokens:^(GIDAuthentication * _Nonnull authentication,
  305. NSError * _Nullable error) {}];
  306. _tokenFetchHandler([self tokenResponseWithNewTokens], nil);
  307. NSDictionary *expectedParameters = @{
  308. @"emm_support" : @"xyz",
  309. @"device_os" : [NSString stringWithFormat:@"%@ %@",
  310. _fakeSystemName, [UIDevice currentDevice].systemVersion],
  311. @"emm_passcode_info" : [GIDMDMPasscodeState passcodeState].info,
  312. kSDKVersionLoggingParameter : GIDVersion(),
  313. };
  314. XCTAssertEqualObjects(auth.authState.lastTokenResponse.request.additionalParameters,
  315. expectedParameters);
  316. }
  317. - (void)testEMMError {
  318. // Set expectations.
  319. NSDictionary *errorJSON = @{ @"error" : @"EMM Specific Error" };
  320. NSError *emmError = [NSError errorWithDomain:@"anydomain"
  321. code:12345
  322. userInfo:@{ OIDOAuthErrorResponseErrorKey : errorJSON }];
  323. id mockEMMErrorHandler = OCMStrictClassMock([GIDEMMErrorHandler class]);
  324. [[[mockEMMErrorHandler stub] andReturn:mockEMMErrorHandler] sharedInstance];
  325. __block void (^completion)(void);
  326. [[[mockEMMErrorHandler expect] andReturnValue:@YES]
  327. handleErrorFromResponse:errorJSON completion:[OCMArg checkWithBlock:^(id arg) {
  328. completion = arg;
  329. return YES;
  330. }]];
  331. // Start testing.
  332. _additionalTokenRequestParameters = @{
  333. @"emm_support" : @"xyz",
  334. };
  335. GIDAuthentication *auth = [self auth];
  336. XCTestExpectation *notCalled = [self expectationWithDescription:@"Callback is not called"];
  337. notCalled.inverted = YES;
  338. XCTestExpectation *called = [self expectationWithDescription:@"Callback is called"];
  339. [auth doWithFreshTokens:^(GIDAuthentication *authentication, NSError *error) {
  340. [notCalled fulfill];
  341. [called fulfill];
  342. XCTAssertNil(authentication);
  343. XCTAssertEqualObjects(error.domain, kGIDSignInErrorDomain);
  344. XCTAssertEqual(error.code, kGIDSignInErrorCodeEMM);
  345. }];
  346. _tokenFetchHandler(nil, emmError);
  347. // Verify and clean up.
  348. [mockEMMErrorHandler verify];
  349. [mockEMMErrorHandler stopMocking];
  350. [self waitForExpectations:@[ notCalled ] timeout:1];
  351. completion();
  352. [self waitForExpectations:@[ called ] timeout:1];
  353. [self assertOldTokensInAuth:auth];
  354. }
  355. - (void)testNonEMMError {
  356. // Set expectations.
  357. NSDictionary *errorJSON = @{ @"error" : @"Not EMM Specific Error" };
  358. NSError *emmError = [NSError errorWithDomain:@"anydomain"
  359. code:12345
  360. userInfo:@{ OIDOAuthErrorResponseErrorKey : errorJSON }];
  361. id mockEMMErrorHandler = OCMStrictClassMock([GIDEMMErrorHandler class]);
  362. [[[mockEMMErrorHandler stub] andReturn:mockEMMErrorHandler] sharedInstance];
  363. __block void (^completion)(void);
  364. [[[mockEMMErrorHandler expect] andReturnValue:@NO]
  365. handleErrorFromResponse:errorJSON completion:[OCMArg checkWithBlock:^(id arg) {
  366. completion = arg;
  367. return YES;
  368. }]];
  369. // Start testing.
  370. _additionalTokenRequestParameters = @{
  371. @"emm_support" : @"xyz",
  372. };
  373. GIDAuthentication *auth = [self auth];
  374. XCTestExpectation *notCalled = [self expectationWithDescription:@"Callback is not called"];
  375. notCalled.inverted = YES;
  376. XCTestExpectation *called = [self expectationWithDescription:@"Callback is called"];
  377. [auth doWithFreshTokens:^(GIDAuthentication *authentication, NSError *error) {
  378. [notCalled fulfill];
  379. [called fulfill];
  380. XCTAssertNil(authentication);
  381. XCTAssertEqualObjects(error.domain, @"anydomain");
  382. XCTAssertEqual(error.code, 12345);
  383. }];
  384. _tokenFetchHandler(nil, emmError);
  385. // Verify and clean up.
  386. [mockEMMErrorHandler verify];
  387. [mockEMMErrorHandler stopMocking];
  388. [self waitForExpectations:@[ notCalled ] timeout:1];
  389. completion();
  390. [self waitForExpectations:@[ called ] timeout:1];
  391. [self assertOldTokensInAuth:auth];
  392. }
  393. - (void)testCodingPreserveEMMParameters {
  394. _additionalTokenRequestParameters = @{
  395. @"emm_support" : @"xyz",
  396. @"device_os" : @"old one",
  397. @"emm_passcode_info" : @"something",
  398. };
  399. NSData *data = [NSKeyedArchiver archivedDataWithRootObject:[self auth]];
  400. GIDAuthentication *auth = [NSKeyedUnarchiver unarchiveObjectWithData:data];
  401. [auth doWithFreshTokens:^(GIDAuthentication * _Nonnull authentication,
  402. NSError * _Nullable error) {}];
  403. _tokenFetchHandler([self tokenResponseWithNewTokens], nil);
  404. NSDictionary *expectedParameters = @{
  405. @"emm_support" : @"xyz",
  406. @"device_os" : [NSString stringWithFormat:@"%@ %@",
  407. [UIDevice currentDevice].systemName, [UIDevice currentDevice].systemVersion],
  408. @"emm_passcode_info" : [GIDMDMPasscodeState passcodeState].info,
  409. kSDKVersionLoggingParameter : GIDVersion(),
  410. };
  411. XCTAssertEqualObjects(auth.authState.lastTokenResponse.request.additionalParameters,
  412. expectedParameters);
  413. }
  414. #pragma mark - NSKeyValueObserving
  415. - (void)observeValueForKeyPath:(NSString *)keyPath
  416. ofObject:(id)object
  417. change:(NSDictionary *)change
  418. context:(void *)context {
  419. GIDAuthentication *auth = (GIDAuthentication *)object;
  420. ChangeType changeType;
  421. if ([keyPath isEqualToString:@"accessToken"]) {
  422. if (change[NSKeyValueChangeNotificationIsPriorKey]) {
  423. XCTAssertEqualObjects(auth.accessToken, kAccessToken);
  424. changeType = kChangeTypeAccessTokenPrior;
  425. } else {
  426. XCTAssertEqualObjects(auth.accessToken, kNewAccessToken);
  427. changeType = kChangeTypeAccessToken;
  428. }
  429. } else if ([keyPath isEqualToString:@"accessTokenExpirationDate"]) {
  430. if (change[NSKeyValueChangeNotificationIsPriorKey]) {
  431. [self assertDate:auth.accessTokenExpirationDate equalTime:_accessTokenExpireTime];
  432. changeType = kChangeTypeAccessTokenExpirationDatePrior;
  433. } else {
  434. [self assertDate:auth.accessTokenExpirationDate equalTime:kNewExpireTime];
  435. changeType = kChangeTypeAccessTokenExpirationDate;
  436. }
  437. } else if ([keyPath isEqualToString:@"idToken"]) {
  438. if (change[NSKeyValueChangeNotificationIsPriorKey]) {
  439. XCTAssertEqualObjects(auth.idToken, [self idToken]);
  440. changeType = kChangeTypeIDTokenPrior;
  441. } else {
  442. XCTAssertEqualObjects(auth.idToken, [self idTokenNew]);
  443. changeType = kChangeTypeIDToken;
  444. }
  445. } else if ([keyPath isEqualToString:@"idTokenExpirationDate"]) {
  446. if (change[NSKeyValueChangeNotificationIsPriorKey]) {
  447. if (_hasIDToken) {
  448. [self assertDate:auth.idTokenExpirationDate equalTime:_idTokenExpireTime];
  449. }
  450. changeType = kChangeTypeIDTokenExpirationDatePrior;
  451. } else {
  452. if (_hasIDToken) {
  453. [self assertDate:auth.idTokenExpirationDate equalTime:kNewExpireTime2];
  454. }
  455. changeType = kChangeTypeIDTokenExpirationDate;
  456. }
  457. } else {
  458. XCTFail(@"unexpected keyPath");
  459. return; // so compiler knows |changeType| is always assigned
  460. }
  461. NSUInteger changeMask = 1u << changeType;
  462. XCTAssertFalse(_changesObserved & changeMask); // each change type should only fire once
  463. _changesObserved |= changeMask;
  464. }
  465. #pragma mark - Helpers
  466. - (GIDAuthentication *)auth {
  467. NSString *idToken = [self idToken];
  468. NSNumber *accessTokenExpiresIn =
  469. @(_accessTokenExpireTime - [[NSDate date] timeIntervalSinceReferenceDate]);
  470. OIDTokenRequest *tokenRequest =
  471. [OIDTokenRequest testInstanceWithAdditionalParameters:_additionalTokenRequestParameters];
  472. OIDTokenResponse *tokenResponse =
  473. [OIDTokenResponse testInstanceWithIDToken:idToken
  474. accessToken:kAccessToken
  475. expiresIn:accessTokenExpiresIn
  476. tokenRequest:tokenRequest];
  477. return [[GIDAuthentication alloc]
  478. initWithAuthState:[OIDAuthState testInstanceWithTokenResponse:tokenResponse]];
  479. }
  480. - (NSString *)idTokenWithExpireTime:(NSTimeInterval)expireTime {
  481. if (!_hasIDToken) {
  482. return nil;
  483. }
  484. return [OIDTokenResponse idTokenWithSub:kUserID exp:@(expireTime + NSTimeIntervalSince1970)];
  485. }
  486. - (NSString *)idToken {
  487. return [self idTokenWithExpireTime:_idTokenExpireTime];
  488. }
  489. - (NSString *)idTokenNew {
  490. return [self idTokenWithExpireTime:kNewExpireTime2];
  491. }
  492. // Return the auth object that has certain property changes observed.
  493. - (GIDAuthentication *)observedAuth {
  494. GIDAuthentication *auth = [self auth];
  495. for (unsigned int i = 0; i < kNumberOfObservedProperties; ++i) {
  496. [auth addObserver:self
  497. forKeyPath:kObservedProperties[i]
  498. options:NSKeyValueObservingOptionPrior
  499. context:NULL];
  500. }
  501. [_observedAuths addObject:auth];
  502. return auth;
  503. }
  504. - (OIDTokenResponse *)tokenResponseWithNewTokens {
  505. NSNumber *expiresIn = @(kNewExpireTime - [NSDate timeIntervalSinceReferenceDate]);
  506. return [OIDTokenResponse testInstanceWithIDToken:(_hasIDToken ? [self idTokenNew] : nil)
  507. accessToken:kNewAccessToken
  508. expiresIn:expiresIn
  509. tokenRequest:_tokenRequest ?: nil];
  510. }
  511. - (NSError *)fakeError {
  512. return [NSError errorWithDomain:@"fake.domain" code:-1 userInfo:nil];
  513. }
  514. - (void)assertDate:(NSDate *)date equalTime:(NSTimeInterval)time {
  515. XCTAssertEqualWithAccuracy([date timeIntervalSinceReferenceDate], time, kTimeAccuracy);
  516. }
  517. - (void)assertOldAccessTokenInAuth:(GIDAuthentication *)auth {
  518. XCTAssertEqualObjects(auth.accessToken, kAccessToken);
  519. [self assertDate:auth.accessTokenExpirationDate equalTime:_accessTokenExpireTime];
  520. XCTAssertEqual(_changesObserved, kChangeNone);
  521. }
  522. - (void)assertNewAccessTokenInAuth:(GIDAuthentication *)auth {
  523. XCTAssertEqualObjects(auth.accessToken, kNewAccessToken);
  524. [self assertDate:auth.accessTokenExpirationDate equalTime:kNewExpireTime];
  525. XCTAssertEqual(_changesObserved, kChangeAll);
  526. }
  527. - (void)assertOldTokensInAuth:(GIDAuthentication *)auth {
  528. [self assertOldAccessTokenInAuth:auth];
  529. XCTAssertEqualObjects(auth.idToken, [self idToken]);
  530. if (_hasIDToken) {
  531. [self assertDate:auth.idTokenExpirationDate equalTime:_idTokenExpireTime];
  532. }
  533. }
  534. - (void)assertNewTokensInAuth:(GIDAuthentication *)auth {
  535. [self assertNewAccessTokenInAuth:auth];
  536. XCTAssertEqualObjects(auth.idToken, [self idTokenNew]);
  537. if (_hasIDToken) {
  538. [self assertDate:auth.idTokenExpirationDate equalTime:kNewExpireTime2];
  539. }
  540. }
  541. - (void)setTokensExpireTime:(NSTimeInterval)fromNow {
  542. [self setExpireTimeForAccessToken:fromNow IDToken:fromNow];
  543. }
  544. - (void)setExpireTimeForAccessToken:(NSTimeInterval)accessExpire IDToken:(NSTimeInterval)idExpire {
  545. _accessTokenExpireTime = [[NSDate date] timeIntervalSinceReferenceDate] + accessExpire;
  546. _idTokenExpireTime = [[NSDate date] timeIntervalSinceReferenceDate] + idExpire;
  547. }
  548. - (void)verifyTokensRefreshedWithMethod:(SEL)sel {
  549. GIDAuthentication *auth = [self observedAuth];
  550. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback is called"];
  551. #pragma clang diagnostic push
  552. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  553. // We know the method doesn't return anything, so there is no risk of leaking.
  554. [auth performSelector:sel withObject:^(GIDAuthentication *authentication, NSError *error) {
  555. #pragma clang diagnostic pop
  556. [expectation fulfill];
  557. [self assertNewTokensInAuth:authentication];
  558. XCTAssertNil(error);
  559. }];
  560. _tokenFetchHandler([self tokenResponseWithNewTokens], nil);
  561. [self waitForExpectationsWithTimeout:1 handler:nil];
  562. [self assertNewTokensInAuth:auth];
  563. }
  564. - (void)verifyTokensNotRefreshedWithMethod:(SEL)sel {
  565. GIDAuthentication *auth = [self observedAuth];
  566. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback is called"];
  567. #pragma clang diagnostic push
  568. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  569. // We know the method doesn't return anything, so there is no risk of leaking.
  570. [auth performSelector:sel withObject:^(GIDAuthentication *authentication, NSError *error) {
  571. #pragma clang diagnostic pop
  572. [expectation fulfill];
  573. [self assertOldTokensInAuth:authentication];
  574. XCTAssertNil(error);
  575. }];
  576. XCTAssertNil(_tokenFetchHandler);
  577. [self waitForExpectationsWithTimeout:1 handler:nil];
  578. [self assertOldTokensInAuth:auth];
  579. }
  580. @end