GIDAuthenticationTest.m 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  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(self->_tokenFetchHandler); // only one on-going fetch allowed
  125. self->_tokenFetchHandler = [callback copy];
  126. self->_tokenRequest = [request copy];
  127. return nil;
  128. }];
  129. _observedAuths = [[NSMutableArray alloc] init];
  130. _changesObserved = 0;
  131. _fakeSystemName = kNewIOSName;
  132. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  133. [GULSwizzler swizzleClass:[UIDevice class]
  134. selector:@selector(systemName)
  135. isClassSelector:NO
  136. withBlock:^(id sender) { return self->_fakeSystemName; }];
  137. #endif
  138. }
  139. - (void)tearDown {
  140. [GULSwizzler unswizzleClass:[OIDAuthorizationService class]
  141. selector:@selector(performTokenRequest:originalAuthorizationResponse:callback:)
  142. isClassSelector:YES];
  143. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  144. [GULSwizzler unswizzleClass:[UIDevice class]
  145. selector:@selector(systemName)
  146. isClassSelector:NO];
  147. #endif
  148. for (GIDAuthentication *auth in _observedAuths) {
  149. for (unsigned int i = 0; i < kNumberOfObservedProperties; ++i) {
  150. [auth removeObserver:self forKeyPath:kObservedProperties[i]];
  151. }
  152. }
  153. _observedAuths = nil;
  154. }
  155. #pragma mark - Tests
  156. - (void)testInitWithAuthState {
  157. OIDAuthState *authState = [OIDAuthState testInstance];
  158. GIDAuthentication *auth = [[GIDAuthentication alloc] initWithAuthState:authState];
  159. XCTAssertEqualObjects(auth.clientID, authState.lastAuthorizationResponse.request.clientID);
  160. XCTAssertEqualObjects(auth.accessToken, authState.lastTokenResponse.accessToken);
  161. XCTAssertEqualObjects(auth.accessTokenExpirationDate,
  162. authState.lastTokenResponse.accessTokenExpirationDate);
  163. XCTAssertEqualObjects(auth.refreshToken, authState.refreshToken);
  164. XCTAssertEqualObjects(auth.idToken, authState.lastTokenResponse.idToken);
  165. OIDIDToken *idToken = [[OIDIDToken alloc]
  166. initWithIDTokenString:authState.lastTokenResponse.idToken];
  167. XCTAssertEqualObjects(auth.idTokenExpirationDate, [idToken expiresAt]);
  168. }
  169. - (void)testInitWithAuthStateNoIDToken {
  170. OIDAuthState *authState = [OIDAuthState testInstanceWithIDToken:nil];
  171. GIDAuthentication *auth = [[GIDAuthentication alloc] initWithAuthState:authState];
  172. XCTAssertEqualObjects(auth.clientID, authState.lastAuthorizationResponse.request.clientID);
  173. XCTAssertEqualObjects(auth.accessToken, authState.lastTokenResponse.accessToken);
  174. XCTAssertEqualObjects(auth.accessTokenExpirationDate,
  175. authState.lastTokenResponse.accessTokenExpirationDate);
  176. XCTAssertEqualObjects(auth.refreshToken, authState.refreshToken);
  177. XCTAssertNil(auth.idToken);
  178. XCTAssertNil(auth.idTokenExpirationDate);
  179. }
  180. - (void)testAuthState {
  181. OIDAuthState *authState = [OIDAuthState testInstance];
  182. GIDAuthentication *auth = [[GIDAuthentication alloc] initWithAuthState:authState];
  183. OIDAuthState *authStateReturned = auth.authState;
  184. XCTAssertEqual(authState, authStateReturned);
  185. }
  186. - (void)testCoding {
  187. if (@available(iOS 11, macOS 10.13, *)) {
  188. GIDAuthentication *auth = [self auth];
  189. NSData *data = [NSKeyedArchiver archivedDataWithRootObject:auth requiringSecureCoding:YES error:nil];
  190. GIDAuthentication *newAuth = [NSKeyedUnarchiver unarchivedObjectOfClass:[GIDAuthentication class]
  191. fromData:data
  192. error:nil];
  193. XCTAssertEqualObjects(auth, newAuth);
  194. XCTAssertTrue([GIDAuthentication supportsSecureCoding]);
  195. } else {
  196. XCTSkip(@"Required API is not available for this test.");
  197. }
  198. }
  199. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  200. // Deprecated in iOS 13 and moacOS 10.14
  201. - (void)testLegacyCoding {
  202. GIDAuthentication *auth = [self auth];
  203. NSData *data = [NSKeyedArchiver archivedDataWithRootObject:auth];
  204. GIDAuthentication *newAuth = [NSKeyedUnarchiver unarchiveObjectWithData:data];
  205. XCTAssertEqualObjects(auth, newAuth);
  206. XCTAssertTrue([GIDAuthentication supportsSecureCoding]);
  207. }
  208. #endif
  209. - (void)testFetcherAuthorizer {
  210. // This is really hard to test without assuming how GTMAppAuthFetcherAuthorization works
  211. // internally, so let's just take the shortcut here by asserting we get a
  212. // GTMAppAuthFetcherAuthorization object.
  213. GIDAuthentication *auth = [self auth];
  214. id<GTMFetcherAuthorizationProtocol> fetcherAuthroizer = auth.fetcherAuthorizer;
  215. XCTAssertTrue([fetcherAuthroizer isKindOfClass:[GTMAppAuthFetcherAuthorization class]]);
  216. XCTAssertTrue([fetcherAuthroizer canAuthorize]);
  217. }
  218. - (void)testDoWithFreshTokensWithBothExpired {
  219. // Both tokens expired 10 seconds ago.
  220. [self setExpireTimeForAccessToken:-10 IDToken:-10];
  221. [self verifyTokensRefreshedWithMethod:@selector(doWithFreshTokens:)];
  222. }
  223. - (void)testDoWithFreshTokensWithAccessTokenExpired {
  224. // Access token expired 10 seconds ago while ID token to expire in 10 minutes.
  225. [self setExpireTimeForAccessToken:-10 IDToken:10 * 60];
  226. [self verifyTokensRefreshedWithMethod:@selector(doWithFreshTokens:)];
  227. }
  228. - (void)testDoWithFreshTokensWithIDTokenToExpire {
  229. // Access token to expire in 10 minutes while ID token to expire in 10 seconds.
  230. [self setExpireTimeForAccessToken:10 * 60 IDToken:10];
  231. [self verifyTokensRefreshedWithMethod:@selector(doWithFreshTokens:)];
  232. }
  233. - (void)testDoWithFreshTokensWithBothFresh {
  234. // Both tokens to expire in 10 minutes.
  235. [self setExpireTimeForAccessToken:10 * 60 IDToken:10 * 60];
  236. [self verifyTokensNotRefreshedWithMethod:@selector(doWithFreshTokens:)];
  237. }
  238. - (void)testDoWithFreshTokensWithAccessTokenExpiredAndNoIDToken {
  239. _hasIDToken = NO;
  240. [self setExpireTimeForAccessToken:-10 IDToken:10 * 60]; // access token expired 10 seconds ago
  241. [self verifyTokensRefreshedWithMethod:@selector(doWithFreshTokens:)];
  242. }
  243. - (void)testDoWithFreshTokensWithAccessTokenFreshAndNoIDToken {
  244. _hasIDToken = NO;
  245. [self setExpireTimeForAccessToken:10 * 60 IDToken:-10]; // access token to expire in 10 minutes
  246. [self verifyTokensNotRefreshedWithMethod:@selector(doWithFreshTokens:)];
  247. }
  248. - (void)testDoWithFreshTokensError {
  249. [self setTokensExpireTime:-10]; // expired 10 seconds ago
  250. GIDAuthentication *auth = [self observedAuth];
  251. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback is called"];
  252. [auth doWithFreshTokens:^(GIDAuthentication *authentication, NSError *error) {
  253. [expectation fulfill];
  254. XCTAssertNil(authentication);
  255. XCTAssertNotNil(error);
  256. }];
  257. _tokenFetchHandler(nil, [self fakeError]);
  258. [self waitForExpectationsWithTimeout:1 handler:nil];
  259. [self assertOldTokensInAuth:auth];
  260. }
  261. - (void)testDoWithFreshTokensQueue {
  262. GIDAuthentication *auth = [self observedAuth];
  263. XCTestExpectation *firstExpectation =
  264. [self expectationWithDescription:@"First callback is called"];
  265. [auth doWithFreshTokens:^(GIDAuthentication *authentication, NSError *error) {
  266. [firstExpectation fulfill];
  267. [self assertNewTokensInAuth:authentication];
  268. XCTAssertNil(error);
  269. }];
  270. XCTestExpectation *secondExpectation =
  271. [self expectationWithDescription:@"Second callback is called"];
  272. [auth doWithFreshTokens:^(GIDAuthentication *authentication, NSError *error) {
  273. [secondExpectation fulfill];
  274. [self assertNewTokensInAuth:authentication];
  275. XCTAssertNil(error);
  276. }];
  277. _tokenFetchHandler([self tokenResponseWithNewTokens], nil);
  278. [self waitForExpectationsWithTimeout:1 handler:nil];
  279. [self assertNewTokensInAuth:auth];
  280. }
  281. #pragma mark - EMM Support
  282. #if TARGET_OS_IOS
  283. - (void)testEMMSupport {
  284. _additionalTokenRequestParameters = @{
  285. @"emm_support" : @"xyz",
  286. };
  287. GIDAuthentication *auth = [self auth];
  288. [auth doWithFreshTokens:^(GIDAuthentication * _Nonnull authentication,
  289. NSError * _Nullable error) {}];
  290. _tokenFetchHandler([self tokenResponseWithNewTokens], nil);
  291. NSDictionary *expectedParameters = @{
  292. @"emm_support" : @"xyz",
  293. @"device_os" : [NSString stringWithFormat:@"%@ %@",
  294. _fakeSystemName, [UIDevice currentDevice].systemVersion],
  295. kSDKVersionLoggingParameter : GIDVersion(),
  296. };
  297. XCTAssertEqualObjects(auth.authState.lastTokenResponse.request.additionalParameters,
  298. expectedParameters);
  299. }
  300. - (void)testSystemNameNormalization {
  301. _fakeSystemName = kOldIOSName;
  302. _additionalTokenRequestParameters = @{
  303. @"emm_support" : @"xyz",
  304. };
  305. GIDAuthentication *auth = [self auth];
  306. [auth doWithFreshTokens:^(GIDAuthentication * _Nonnull authentication,
  307. NSError * _Nullable error) {}];
  308. _tokenFetchHandler([self tokenResponseWithNewTokens], nil);
  309. NSDictionary *expectedParameters = @{
  310. @"emm_support" : @"xyz",
  311. @"device_os" : [NSString stringWithFormat:@"%@ %@",
  312. kNewIOSName, [UIDevice currentDevice].systemVersion],
  313. kSDKVersionLoggingParameter : GIDVersion(),
  314. };
  315. XCTAssertEqualObjects(auth.authState.lastTokenResponse.request.additionalParameters,
  316. expectedParameters);
  317. }
  318. - (void)testEMMPasscodeInfo {
  319. _additionalTokenRequestParameters = @{
  320. @"emm_support" : @"xyz",
  321. @"device_os" : @"old one",
  322. @"emm_passcode_info" : @"something",
  323. };
  324. GIDAuthentication *auth = [self auth];
  325. [auth doWithFreshTokens:^(GIDAuthentication * _Nonnull authentication,
  326. NSError * _Nullable error) {}];
  327. _tokenFetchHandler([self tokenResponseWithNewTokens], nil);
  328. NSDictionary *expectedParameters = @{
  329. @"emm_support" : @"xyz",
  330. @"device_os" : [NSString stringWithFormat:@"%@ %@",
  331. _fakeSystemName, [UIDevice currentDevice].systemVersion],
  332. @"emm_passcode_info" : [GIDMDMPasscodeState passcodeState].info,
  333. kSDKVersionLoggingParameter : GIDVersion(),
  334. };
  335. XCTAssertEqualObjects(auth.authState.lastTokenResponse.request.additionalParameters,
  336. expectedParameters);
  337. }
  338. - (void)testEMMError {
  339. // Set expectations.
  340. NSDictionary *errorJSON = @{ @"error" : @"EMM Specific Error" };
  341. NSError *emmError = [NSError errorWithDomain:@"anydomain"
  342. code:12345
  343. userInfo:@{ OIDOAuthErrorResponseErrorKey : errorJSON }];
  344. id mockEMMErrorHandler = OCMStrictClassMock([GIDEMMErrorHandler class]);
  345. [[[mockEMMErrorHandler stub] andReturn:mockEMMErrorHandler] sharedInstance];
  346. __block void (^completion)(void);
  347. [[[mockEMMErrorHandler expect] andReturnValue:@YES]
  348. handleErrorFromResponse:errorJSON completion:[OCMArg checkWithBlock:^(id arg) {
  349. completion = arg;
  350. return YES;
  351. }]];
  352. // Start testing.
  353. _additionalTokenRequestParameters = @{
  354. @"emm_support" : @"xyz",
  355. };
  356. GIDAuthentication *auth = [self auth];
  357. XCTestExpectation *notCalled = [self expectationWithDescription:@"Callback is not called"];
  358. notCalled.inverted = YES;
  359. XCTestExpectation *called = [self expectationWithDescription:@"Callback is called"];
  360. [auth doWithFreshTokens:^(GIDAuthentication *authentication, NSError *error) {
  361. [notCalled fulfill];
  362. [called fulfill];
  363. XCTAssertNil(authentication);
  364. XCTAssertEqualObjects(error.domain, kGIDSignInErrorDomain);
  365. XCTAssertEqual(error.code, kGIDSignInErrorCodeEMM);
  366. }];
  367. _tokenFetchHandler(nil, emmError);
  368. // Verify and clean up.
  369. [mockEMMErrorHandler verify];
  370. [mockEMMErrorHandler stopMocking];
  371. [self waitForExpectations:@[ notCalled ] timeout:1];
  372. completion();
  373. [self waitForExpectations:@[ called ] timeout:1];
  374. [self assertOldTokensInAuth:auth];
  375. }
  376. - (void)testNonEMMError {
  377. // Set expectations.
  378. NSDictionary *errorJSON = @{ @"error" : @"Not EMM Specific Error" };
  379. NSError *emmError = [NSError errorWithDomain:@"anydomain"
  380. code:12345
  381. userInfo:@{ OIDOAuthErrorResponseErrorKey : errorJSON }];
  382. id mockEMMErrorHandler = OCMStrictClassMock([GIDEMMErrorHandler class]);
  383. [[[mockEMMErrorHandler stub] andReturn:mockEMMErrorHandler] sharedInstance];
  384. __block void (^completion)(void);
  385. [[[mockEMMErrorHandler expect] andReturnValue:@NO]
  386. handleErrorFromResponse:errorJSON completion:[OCMArg checkWithBlock:^(id arg) {
  387. completion = arg;
  388. return YES;
  389. }]];
  390. // Start testing.
  391. _additionalTokenRequestParameters = @{
  392. @"emm_support" : @"xyz",
  393. };
  394. GIDAuthentication *auth = [self auth];
  395. XCTestExpectation *notCalled = [self expectationWithDescription:@"Callback is not called"];
  396. notCalled.inverted = YES;
  397. XCTestExpectation *called = [self expectationWithDescription:@"Callback is called"];
  398. [auth doWithFreshTokens:^(GIDAuthentication *authentication, NSError *error) {
  399. [notCalled fulfill];
  400. [called fulfill];
  401. XCTAssertNil(authentication);
  402. XCTAssertEqualObjects(error.domain, @"anydomain");
  403. XCTAssertEqual(error.code, 12345);
  404. }];
  405. _tokenFetchHandler(nil, emmError);
  406. // Verify and clean up.
  407. [mockEMMErrorHandler verify];
  408. [mockEMMErrorHandler stopMocking];
  409. [self waitForExpectations:@[ notCalled ] timeout:1];
  410. completion();
  411. [self waitForExpectations:@[ called ] timeout:1];
  412. [self assertOldTokensInAuth:auth];
  413. }
  414. - (void)testCodingPreserveEMMParameters {
  415. _additionalTokenRequestParameters = @{
  416. @"emm_support" : @"xyz",
  417. @"device_os" : @"old one",
  418. @"emm_passcode_info" : @"something",
  419. };
  420. NSData *data = [NSKeyedArchiver archivedDataWithRootObject:[self auth]];
  421. GIDAuthentication *auth = [NSKeyedUnarchiver unarchiveObjectWithData:data];
  422. [auth doWithFreshTokens:^(GIDAuthentication * _Nonnull authentication,
  423. NSError * _Nullable error) {}];
  424. _tokenFetchHandler([self tokenResponseWithNewTokens], nil);
  425. NSDictionary *expectedParameters = @{
  426. @"emm_support" : @"xyz",
  427. @"device_os" : [NSString stringWithFormat:@"%@ %@",
  428. [UIDevice currentDevice].systemName, [UIDevice currentDevice].systemVersion],
  429. @"emm_passcode_info" : [GIDMDMPasscodeState passcodeState].info,
  430. kSDKVersionLoggingParameter : GIDVersion(),
  431. };
  432. XCTAssertEqualObjects(auth.authState.lastTokenResponse.request.additionalParameters,
  433. expectedParameters);
  434. }
  435. #endif
  436. #pragma mark - NSKeyValueObserving
  437. - (void)observeValueForKeyPath:(NSString *)keyPath
  438. ofObject:(id)object
  439. change:(NSDictionary *)change
  440. context:(void *)context {
  441. GIDAuthentication *auth = (GIDAuthentication *)object;
  442. ChangeType changeType;
  443. if ([keyPath isEqualToString:@"accessToken"]) {
  444. if (change[NSKeyValueChangeNotificationIsPriorKey]) {
  445. XCTAssertEqualObjects(auth.accessToken, kAccessToken);
  446. changeType = kChangeTypeAccessTokenPrior;
  447. } else {
  448. XCTAssertEqualObjects(auth.accessToken, kNewAccessToken);
  449. changeType = kChangeTypeAccessToken;
  450. }
  451. } else if ([keyPath isEqualToString:@"accessTokenExpirationDate"]) {
  452. if (change[NSKeyValueChangeNotificationIsPriorKey]) {
  453. [self assertDate:auth.accessTokenExpirationDate equalTime:_accessTokenExpireTime];
  454. changeType = kChangeTypeAccessTokenExpirationDatePrior;
  455. } else {
  456. [self assertDate:auth.accessTokenExpirationDate equalTime:kNewExpireTime];
  457. changeType = kChangeTypeAccessTokenExpirationDate;
  458. }
  459. } else if ([keyPath isEqualToString:@"idToken"]) {
  460. if (change[NSKeyValueChangeNotificationIsPriorKey]) {
  461. XCTAssertEqualObjects(auth.idToken, [self idToken]);
  462. changeType = kChangeTypeIDTokenPrior;
  463. } else {
  464. XCTAssertEqualObjects(auth.idToken, [self idTokenNew]);
  465. changeType = kChangeTypeIDToken;
  466. }
  467. } else if ([keyPath isEqualToString:@"idTokenExpirationDate"]) {
  468. if (change[NSKeyValueChangeNotificationIsPriorKey]) {
  469. if (_hasIDToken) {
  470. [self assertDate:auth.idTokenExpirationDate equalTime:_idTokenExpireTime];
  471. }
  472. changeType = kChangeTypeIDTokenExpirationDatePrior;
  473. } else {
  474. if (_hasIDToken) {
  475. [self assertDate:auth.idTokenExpirationDate equalTime:kNewExpireTime2];
  476. }
  477. changeType = kChangeTypeIDTokenExpirationDate;
  478. }
  479. } else {
  480. XCTFail(@"unexpected keyPath");
  481. return; // so compiler knows |changeType| is always assigned
  482. }
  483. NSUInteger changeMask = 1u << changeType;
  484. XCTAssertFalse(_changesObserved & changeMask); // each change type should only fire once
  485. _changesObserved |= changeMask;
  486. }
  487. #pragma mark - Helpers
  488. - (GIDAuthentication *)auth {
  489. NSString *idToken = [self idToken];
  490. NSNumber *accessTokenExpiresIn =
  491. @(_accessTokenExpireTime - [[NSDate date] timeIntervalSinceReferenceDate]);
  492. OIDTokenRequest *tokenRequest =
  493. [OIDTokenRequest testInstanceWithAdditionalParameters:_additionalTokenRequestParameters];
  494. OIDTokenResponse *tokenResponse =
  495. [OIDTokenResponse testInstanceWithIDToken:idToken
  496. accessToken:kAccessToken
  497. expiresIn:accessTokenExpiresIn
  498. tokenRequest:tokenRequest];
  499. return [[GIDAuthentication alloc]
  500. initWithAuthState:[OIDAuthState testInstanceWithTokenResponse:tokenResponse]];
  501. }
  502. - (NSString *)idTokenWithExpireTime:(NSTimeInterval)expireTime {
  503. if (!_hasIDToken) {
  504. return nil;
  505. }
  506. return [OIDTokenResponse idTokenWithSub:kUserID exp:@(expireTime + NSTimeIntervalSince1970)];
  507. }
  508. - (NSString *)idToken {
  509. return [self idTokenWithExpireTime:_idTokenExpireTime];
  510. }
  511. - (NSString *)idTokenNew {
  512. return [self idTokenWithExpireTime:kNewExpireTime2];
  513. }
  514. // Return the auth object that has certain property changes observed.
  515. - (GIDAuthentication *)observedAuth {
  516. GIDAuthentication *auth = [self auth];
  517. for (unsigned int i = 0; i < kNumberOfObservedProperties; ++i) {
  518. [auth addObserver:self
  519. forKeyPath:kObservedProperties[i]
  520. options:NSKeyValueObservingOptionPrior
  521. context:NULL];
  522. }
  523. [_observedAuths addObject:auth];
  524. return auth;
  525. }
  526. - (OIDTokenResponse *)tokenResponseWithNewTokens {
  527. NSNumber *expiresIn = @(kNewExpireTime - [NSDate timeIntervalSinceReferenceDate]);
  528. return [OIDTokenResponse testInstanceWithIDToken:(_hasIDToken ? [self idTokenNew] : nil)
  529. accessToken:kNewAccessToken
  530. expiresIn:expiresIn
  531. tokenRequest:_tokenRequest ?: nil];
  532. }
  533. - (NSError *)fakeError {
  534. return [NSError errorWithDomain:@"fake.domain" code:-1 userInfo:nil];
  535. }
  536. - (void)assertDate:(NSDate *)date equalTime:(NSTimeInterval)time {
  537. XCTAssertEqualWithAccuracy([date timeIntervalSinceReferenceDate], time, kTimeAccuracy);
  538. }
  539. - (void)assertOldAccessTokenInAuth:(GIDAuthentication *)auth {
  540. XCTAssertEqualObjects(auth.accessToken, kAccessToken);
  541. [self assertDate:auth.accessTokenExpirationDate equalTime:_accessTokenExpireTime];
  542. XCTAssertEqual(_changesObserved, kChangeNone);
  543. }
  544. - (void)assertNewAccessTokenInAuth:(GIDAuthentication *)auth {
  545. XCTAssertEqualObjects(auth.accessToken, kNewAccessToken);
  546. [self assertDate:auth.accessTokenExpirationDate equalTime:kNewExpireTime];
  547. XCTAssertEqual(_changesObserved, kChangeAll);
  548. }
  549. - (void)assertOldTokensInAuth:(GIDAuthentication *)auth {
  550. [self assertOldAccessTokenInAuth:auth];
  551. XCTAssertEqualObjects(auth.idToken, [self idToken]);
  552. if (_hasIDToken) {
  553. [self assertDate:auth.idTokenExpirationDate equalTime:_idTokenExpireTime];
  554. }
  555. }
  556. - (void)assertNewTokensInAuth:(GIDAuthentication *)auth {
  557. [self assertNewAccessTokenInAuth:auth];
  558. XCTAssertEqualObjects(auth.idToken, [self idTokenNew]);
  559. if (_hasIDToken) {
  560. [self assertDate:auth.idTokenExpirationDate equalTime:kNewExpireTime2];
  561. }
  562. }
  563. - (void)setTokensExpireTime:(NSTimeInterval)fromNow {
  564. [self setExpireTimeForAccessToken:fromNow IDToken:fromNow];
  565. }
  566. - (void)setExpireTimeForAccessToken:(NSTimeInterval)accessExpire IDToken:(NSTimeInterval)idExpire {
  567. _accessTokenExpireTime = [[NSDate date] timeIntervalSinceReferenceDate] + accessExpire;
  568. _idTokenExpireTime = [[NSDate date] timeIntervalSinceReferenceDate] + idExpire;
  569. }
  570. - (void)verifyTokensRefreshedWithMethod:(SEL)sel {
  571. GIDAuthentication *auth = [self observedAuth];
  572. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback is called"];
  573. #pragma clang diagnostic push
  574. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  575. // We know the method doesn't return anything, so there is no risk of leaking.
  576. [auth performSelector:sel withObject:^(GIDAuthentication *authentication, NSError *error) {
  577. #pragma clang diagnostic pop
  578. [expectation fulfill];
  579. [self assertNewTokensInAuth:authentication];
  580. XCTAssertNil(error);
  581. }];
  582. _tokenFetchHandler([self tokenResponseWithNewTokens], nil);
  583. [self waitForExpectationsWithTimeout:1 handler:nil];
  584. [self assertNewTokensInAuth:auth];
  585. }
  586. - (void)verifyTokensNotRefreshedWithMethod:(SEL)sel {
  587. GIDAuthentication *auth = [self observedAuth];
  588. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback is called"];
  589. #pragma clang diagnostic push
  590. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  591. // We know the method doesn't return anything, so there is no risk of leaking.
  592. [auth performSelector:sel withObject:^(GIDAuthentication *authentication, NSError *error) {
  593. #pragma clang diagnostic pop
  594. [expectation fulfill];
  595. [self assertOldTokensInAuth:authentication];
  596. XCTAssertNil(error);
  597. }];
  598. XCTAssertNil(_tokenFetchHandler);
  599. [self waitForExpectationsWithTimeout:1 handler:nil];
  600. [self assertOldTokensInAuth:auth];
  601. }
  602. @end