GIDAuthenticationTest.m 27 KB

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