GIDSignInTest.m 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426
  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 <TargetConditionals.h>
  15. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  16. #import <UIKit/UIKit.h>
  17. #elif TARGET_OS_OSX
  18. #import <AppKit/AppKit.h>
  19. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  20. #import <SafariServices/SafariServices.h>
  21. #import <XCTest/XCTest.h>
  22. // Test module imports
  23. @import GoogleSignIn;
  24. #import "GoogleSignIn/Sources/GIDGoogleUser_Private.h"
  25. #import "GoogleSignIn/Sources/GIDSignIn_Private.h"
  26. #import "GoogleSignIn/Sources/GIDSignInPreferences.h"
  27. #import "GoogleSignIn/Sources/GIDAuthentication_Private.h"
  28. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  29. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  30. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  31. #import "GoogleSignIn/Tests/Unit/GIDFakeFetcher.h"
  32. #import "GoogleSignIn/Tests/Unit/GIDFakeFetcherService.h"
  33. #import "GoogleSignIn/Tests/Unit/GIDFakeMainBundle.h"
  34. #import "GoogleSignIn/Tests/Unit/OIDAuthorizationResponse+Testing.h"
  35. #import "GoogleSignIn/Tests/Unit/OIDTokenResponse+Testing.h"
  36. #ifdef SWIFT_PACKAGE
  37. @import AppAuth;
  38. @import GTMAppAuth;
  39. @import GTMSessionFetcherCore;
  40. @import OCMock;
  41. #else
  42. #import <AppAuth/OIDAuthState.h>
  43. #import <AppAuth/OIDAuthorizationRequest.h>
  44. #import <AppAuth/OIDAuthorizationResponse.h>
  45. #import <AppAuth/OIDAuthorizationService.h>
  46. #import <AppAuth/OIDError.h>
  47. #import <AppAuth/OIDGrantTypes.h>
  48. #import <AppAuth/OIDTokenRequest.h>
  49. #import <AppAuth/OIDTokenResponse.h>
  50. #import <AppAuth/OIDURLQueryComponent.h>
  51. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  52. #import <AppAuth/OIDAuthorizationService+IOS.h>
  53. #elif TARGET_OS_OSX
  54. #import <AppAuth/OIDAuthorizationService+Mac.h>
  55. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  56. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization+Keychain.h>
  57. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization.h>
  58. #import <GTMSessionFetcher/GTMSessionFetcher.h>
  59. #import <OCMock/OCMock.h>
  60. #endif
  61. // Create a BLOCK to store the actual address for arg in param.
  62. #define SAVE_TO_ARG_BLOCK(param) [OCMArg checkWithBlock:^(id arg) {\
  63. param = arg;\
  64. return YES;\
  65. }]
  66. #define COPY_TO_ARG_BLOCK(param) [OCMArg checkWithBlock:^(id arg) {\
  67. param = [arg copy];\
  68. return YES;\
  69. }]
  70. static NSString * const kFakeGaiaID = @"123456789";
  71. static NSString * const kFakeIDToken = @"FakeIDToken";
  72. static NSString * const kClientId = @"FakeClientID";
  73. static NSString * const kDotReversedClientId = @"FakeClientID";
  74. static NSString * const kClientId2 = @"FakeClientID2";
  75. static NSString * const kAppBundleId = @"FakeBundleID";
  76. static NSString * const kLanguage = @"FakeLanguage";
  77. static NSString * const kScope = @"FakeScope";
  78. static NSString * const kScope2 = @"FakeScope2";
  79. static NSString * const kAuthCode = @"FakeAuthCode";
  80. static NSString * const kKeychainName = @"auth";
  81. static NSString * const kUserEmail = @"FakeUserEmail";
  82. static NSString * const kVerifier = @"FakeVerifier";
  83. static NSString * const kOpenIDRealm = @"FakeRealm";
  84. static NSString * const kFakeHostedDomain = @"fakehosteddomain.com";
  85. static NSString * const kFakeUserName = @"fake username";
  86. static NSString * const kFakeUserGivenName = @"fake";
  87. static NSString * const kFakeUserFamilyName = @"username";
  88. static NSString * const kFakeUserPictureURL = @"fake_user_picture_url";
  89. static NSString * const kContinueURL = @"com.google.UnitTests:/oauth2callback";
  90. static NSString * const kContinueURLWithClientID = @"FakeClientID:/oauth2callback";
  91. static NSString * const kWrongSchemeURL = @"wrong.app:/oauth2callback";
  92. static NSString * const kWrongPathURL = @"com.google.UnitTests:/wrong_path";
  93. static NSString * const kEMMRestartAuthURL =
  94. @"com.google.UnitTests:///emmcallback?action=restart_auth";
  95. static NSString * const kEMMWrongPathURL =
  96. @"com.google.UnitTests:///unknowcallback?action=restart_auth";
  97. static NSString * const kEMMWrongActionURL =
  98. @"com.google.UnitTests:///emmcallback?action=unrecognized";
  99. static NSString * const kDevicePolicyAppBundleID = @"com.google.DevicePolicy";
  100. static NSString * const kAppHasRunBeforeKey = @"GPP_AppHasRunBefore";
  101. static NSString * const kFingerprintKeychainName = @"fingerprint";
  102. static NSString * const kVerifierKeychainName = @"verifier";
  103. static NSString * const kVerifierKey = @"verifier";
  104. static NSString * const kOpenIDRealmKey = @"openid.realm";
  105. static NSString * const kSavedKeychainServiceName = @"saved-keychain";
  106. static NSString * const kKeychainAccountName = @"GooglePlus";
  107. static NSString * const kUserNameKey = @"name";
  108. static NSString * const kUserGivenNameKey = @"givenName";
  109. static NSString * const kUserFamilyNameKey = @"familyName";
  110. static NSString * const kUserImageKey = @"picture";
  111. static NSString * const kAppName = @"UnitTests";
  112. static NSString * const kUserIDKey = @"userID";
  113. static NSString * const kHostedDomainKey = @"hostedDomain";
  114. static NSString * const kIDTokenExpirationKey = @"idTokenExp";
  115. static NSString * const kScopeKey = @"scope";
  116. // Basic profile (Fat ID Token / userinfo endpoint) keys
  117. static NSString *const kBasicProfilePictureKey = @"picture";
  118. static NSString *const kBasicProfileNameKey = @"name";
  119. static NSString *const kBasicProfileGivenNameKey = @"given_name";
  120. static NSString *const kBasicProfileFamilyNameKey = @"family_name";
  121. static NSString * const kCustomKeychainName = @"CUSTOM_KEYCHAIN_NAME";
  122. static NSString * const kAddActivity = @"http://schemas.google.com/AddActivity";
  123. static NSString * const kErrorDomain = @"ERROR_DOMAIN";
  124. static NSInteger const kErrorCode = 212;
  125. static NSString *const kDriveScope = @"https://www.googleapis.com/auth/drive";
  126. static NSString *const kTokenURL = @"https://oauth2.googleapis.com/token";
  127. static NSString *const kFakeURL = @"http://foo.com";
  128. static NSString *const kEMMSupport = @"1";
  129. static NSString *const kGrantedScope = @"grantedScope";
  130. static NSString *const kNewScope = @"newScope";
  131. /// Unique pointer value for KVO tests.
  132. static void *kTestObserverContext = &kTestObserverContext;
  133. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  134. // This category is used to allow the test to swizzle a private method.
  135. @interface UIViewController (Testing)
  136. // This private method provides access to the window. It's declared here to avoid a warning about
  137. // an unrecognized selector in the test.
  138. - (UIWindow *)_window;
  139. @end
  140. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  141. // This class extension exposes GIDSignIn methods to our tests.
  142. @interface GIDSignIn ()
  143. // Exposing private method so we can call it to disambiguate between interactive and non-interactive
  144. // sign-in attempts for the purposes of testing the GIDSignInUIDelegate (which should not be
  145. // called in the case of a non-interactive sign in).
  146. - (void)authenticateMaybeInteractively:(BOOL)interactive withParams:(NSDictionary *)params;
  147. - (BOOL)assertValidPresentingViewContoller;
  148. @end
  149. @interface GIDSignInTest : XCTestCase {
  150. @private
  151. // Whether or not the OS version is eligible for EMM.
  152. BOOL _isEligibleForEMM;
  153. // Mock |OIDAuthState|.
  154. id _authState;
  155. // Mock |OIDTokenResponse|.
  156. id _tokenResponse;
  157. // Mock |OIDTokenRequest|.
  158. id _tokenRequest;
  159. // Mock |GTMAppAuthFetcherAuthorization|.
  160. id _authorization;
  161. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  162. // Mock |UIViewController|.
  163. id _presentingViewController;
  164. #elif TARGET_OS_OSX
  165. // Mock |NSWindow|.
  166. id _presentingWindow;
  167. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  168. // Mock for |GIDGoogleUser|.
  169. id _user;
  170. // Mock for |GIDAuthentication|.
  171. id _authentication;
  172. // Mock for |OIDAuthorizationService|
  173. id _oidAuthorizationService;
  174. // Parameter saved from delegate call.
  175. NSError *_authError;
  176. // Whether callback block has been called.
  177. BOOL _callbackCalled;
  178. // Fake fetcher service to emulate network requests.
  179. GIDFakeFetcherService *_fetcherService;
  180. // Fake [NSBundle mainBundle];
  181. GIDFakeMainBundle *_fakeMainBundle;
  182. // Whether |saveParamsToKeychainForName:authentication:| has been called.
  183. BOOL _keychainSaved;
  184. // Whether |removeAuthFromKeychainForName:| has been called.
  185. BOOL _keychainRemoved;
  186. // The |GIDSignIn| object being tested.
  187. GIDSignIn *_signIn;
  188. // The configuration to be used when testing |GIDSignIn|.
  189. GIDConfiguration *_configuration;
  190. // The login hint to be used when testing |GIDSignIn|.
  191. NSString *_hint;
  192. // The callback to be used when testing |GIDSignIn|.
  193. GIDSignInCallback _callback;
  194. // The saved authorization request.
  195. OIDAuthorizationRequest *_savedAuthorizationRequest;
  196. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  197. // The saved presentingViewController from the authorization request.
  198. UIViewController *_savedPresentingViewController;
  199. #elif TARGET_OS_OSX
  200. // The saved presentingWindow from the authorization request.
  201. NSWindow *_savedPresentingWindow;
  202. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  203. // The saved authorization callback.
  204. OIDAuthorizationCallback _savedAuthorizationCallback;
  205. // The saved token request.
  206. OIDTokenRequest *_savedTokenRequest;
  207. // The saved token request callback.
  208. OIDTokenCallback _savedTokenCallback;
  209. // Set of all |GIDSignIn| key paths which were observed to change.
  210. NSMutableSet *_changedKeyPaths;
  211. // Status returned by saveAuthorization:toKeychainForName:
  212. BOOL _saveAuthorizationReturnValue;
  213. }
  214. @end
  215. @implementation GIDSignInTest
  216. #pragma mark - Lifecycle
  217. - (void)setUp {
  218. [super setUp];
  219. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  220. _isEligibleForEMM = [UIDevice currentDevice].systemVersion.integerValue >= 9;
  221. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  222. _saveAuthorizationReturnValue = YES;
  223. // States
  224. _callbackCalled = NO;
  225. _keychainSaved = NO;
  226. _keychainRemoved = NO;
  227. _changedKeyPaths = [[NSMutableSet alloc] init];
  228. // Mocks
  229. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  230. _presentingViewController = OCMStrictClassMock([UIViewController class]);
  231. #elif TARGET_OS_OSX
  232. _presentingWindow = OCMStrictClassMock([NSWindow class]);
  233. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  234. _authState = OCMStrictClassMock([OIDAuthState class]);
  235. OCMStub([_authState alloc]).andReturn(_authState);
  236. OCMStub([_authState initWithAuthorizationResponse:OCMOCK_ANY]).andReturn(_authState);
  237. _tokenResponse = OCMStrictClassMock([OIDTokenResponse class]);
  238. _tokenRequest = OCMStrictClassMock([OIDTokenRequest class]);
  239. _authorization = OCMStrictClassMock([GTMAppAuthFetcherAuthorization class]);
  240. OCMStub([_authorization authorizationFromKeychainForName:OCMOCK_ANY
  241. useDataProtectionKeychain:YES]).andReturn(_authorization);
  242. OCMStub([_authorization alloc]).andReturn(_authorization);
  243. OCMStub([_authorization initWithAuthState:OCMOCK_ANY]).andReturn(_authorization);
  244. OCMStub([_authorization saveAuthorization:OCMOCK_ANY
  245. toKeychainForName:OCMOCK_ANY
  246. useDataProtectionKeychain:YES])
  247. .andDo(^(NSInvocation *invocation) {
  248. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  249. [invocation setReturnValue:&self->_saveAuthorizationReturnValue];
  250. });
  251. OCMStub([_authorization removeAuthorizationFromKeychainForName:OCMOCK_ANY
  252. useDataProtectionKeychain:YES])
  253. .andDo(^(NSInvocation *invocation) {
  254. self->_keychainRemoved = YES;
  255. });
  256. _user = OCMStrictClassMock([GIDGoogleUser class]);
  257. _authentication = OCMStrictClassMock([GIDAuthentication class]);
  258. _oidAuthorizationService = OCMStrictClassMock([OIDAuthorizationService class]);
  259. OCMStub([_oidAuthorizationService
  260. presentAuthorizationRequest:SAVE_TO_ARG_BLOCK(self->_savedAuthorizationRequest)
  261. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  262. presentingViewController:SAVE_TO_ARG_BLOCK(self->_savedPresentingViewController)
  263. #elif TARGET_OS_OSX
  264. presentingWindow:SAVE_TO_ARG_BLOCK(self->_savedPresentingWindow)
  265. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  266. callback:COPY_TO_ARG_BLOCK(self->_savedAuthorizationCallback)]);
  267. OCMStub([self->_oidAuthorizationService
  268. performTokenRequest:SAVE_TO_ARG_BLOCK(self->_savedTokenRequest)
  269. callback:COPY_TO_ARG_BLOCK(self->_savedTokenCallback)]);
  270. // Fakes
  271. _fetcherService = [[GIDFakeFetcherService alloc] init];
  272. _fakeMainBundle = [[GIDFakeMainBundle alloc] init];
  273. [_fakeMainBundle startFakingWithBundleId:kAppBundleId clientId:kClientId];
  274. [_fakeMainBundle fakeAllSchemesSupported];
  275. // Object under test
  276. [[NSUserDefaults standardUserDefaults] setBool:YES
  277. forKey:kAppHasRunBeforeKey];
  278. _signIn = [[GIDSignIn alloc] initPrivate];
  279. _configuration = [[GIDConfiguration alloc] initWithClientID:kClientId];
  280. _hint = nil;
  281. __weak GIDSignInTest *weakSelf = self;
  282. _callback = ^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) {
  283. GIDSignInTest *strongSelf = weakSelf;
  284. if (!user) {
  285. XCTAssertNotNil(error, @"should have an error if user is nil");
  286. }
  287. XCTAssertFalse(strongSelf->_callbackCalled, @"callback already called");
  288. strongSelf->_callbackCalled = YES;
  289. strongSelf->_authError = error;
  290. };
  291. [_signIn addObserver:self
  292. forKeyPath:NSStringFromSelector(@selector(currentUser))
  293. options:0
  294. context:kTestObserverContext];
  295. }
  296. - (void)tearDown {
  297. OCMVerifyAll(_authState);
  298. OCMVerifyAll(_tokenResponse);
  299. OCMVerifyAll(_tokenRequest);
  300. OCMVerifyAll(_authorization);
  301. OCMVerifyAll(_user);
  302. OCMVerifyAll(_authentication);
  303. OCMVerifyAll(_oidAuthorizationService);
  304. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  305. OCMVerifyAll(_presentingViewController);
  306. #elif TARGET_OS_OSX
  307. OCMVerifyAll(_presentingWindow);
  308. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  309. [_fakeMainBundle stopFaking];
  310. [super tearDown];
  311. [_signIn removeObserver:self
  312. forKeyPath:NSStringFromSelector(@selector(currentUser))
  313. context:kTestObserverContext];
  314. }
  315. #pragma mark - Tests
  316. - (void)testShareInstance {
  317. GIDSignIn *signIn1 = GIDSignIn.sharedInstance;
  318. GIDSignIn *signIn2 = GIDSignIn.sharedInstance;
  319. XCTAssertTrue(signIn1 == signIn2, @"shared instance must be singleton");
  320. }
  321. - (void)testRestorePreviousSignInNoRefresh_hasPreviousUser {
  322. [[[_authorization expect] andReturn:_authState] authState];
  323. OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
  324. OCMStub([_tokenResponse scope]).andReturn(nil);
  325. OCMStub([_tokenResponse additionalParameters]).andReturn(nil);
  326. OCMStub([_tokenResponse idToken]).andReturn(kFakeIDToken);
  327. OCMStub([_tokenResponse request]).andReturn(_tokenRequest);
  328. OCMStub([_tokenRequest additionalParameters]).andReturn(nil);
  329. id idTokenDecoded = OCMClassMock([OIDIDToken class]);
  330. OCMStub([idTokenDecoded alloc]).andReturn(idTokenDecoded);
  331. OCMStub([idTokenDecoded initWithIDTokenString:OCMOCK_ANY]).andReturn(idTokenDecoded);
  332. OCMStub([idTokenDecoded subject]).andReturn(kFakeGaiaID);
  333. [_signIn restorePreviousSignInNoRefresh];
  334. [_authorization verify];
  335. [_authState verify];
  336. [_tokenResponse verify];
  337. XCTAssertEqual(_signIn.currentUser.userID, kFakeGaiaID);
  338. [idTokenDecoded stopMocking];
  339. }
  340. - (void)testRestoredPreviousSignInNoRefresh_hasNoPreviousUser {
  341. [[[_authorization expect] andReturn:nil] authState];
  342. [_signIn restorePreviousSignInNoRefresh];
  343. [_authorization verify];
  344. XCTAssertNil(_signIn.currentUser);
  345. }
  346. - (void)testHasPreviousSignIn_HasBeenAuthenticated {
  347. [[[_authorization expect] andReturn:_authState] authState];
  348. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:YES]] isAuthorized];
  349. XCTAssertTrue([_signIn hasPreviousSignIn], @"should return |YES|");
  350. [_authorization verify];
  351. [_authState verify];
  352. XCTAssertFalse(_keychainRemoved, @"should not remove keychain");
  353. XCTAssertFalse(_callbackCalled, @"should not call delegate");
  354. XCTAssertNil(_authError, @"should have no error");
  355. }
  356. - (void)testHasPreviousSignIn_HasNotBeenAuthenticated {
  357. [[[_authorization expect] andReturn:_authState] authState];
  358. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:NO]] isAuthorized];
  359. XCTAssertFalse([_signIn hasPreviousSignIn], @"should return |NO|");
  360. [_authorization verify];
  361. [_authState verify];
  362. XCTAssertFalse(_keychainRemoved, @"should not remove keychain");
  363. XCTAssertFalse(_callbackCalled, @"should not call delegate");
  364. }
  365. - (void)testRestorePreviousSignInWhenSignedOut {
  366. [[[_authorization expect] andReturn:_authState] authState];
  367. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:NO]] isAuthorized];
  368. _callbackCalled = NO;
  369. _authError = nil;
  370. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called."];
  371. [_signIn restorePreviousSignInWithCallback:^(GIDGoogleUser * _Nullable user,
  372. NSError * _Nullable error) {
  373. [expectation fulfill];
  374. XCTAssertNotNil(error, @"error should not have been nil");
  375. XCTAssertEqual(error.domain,
  376. kGIDSignInErrorDomain,
  377. @"error domain should have been the sign-in error domain.");
  378. XCTAssertEqual(error.code,
  379. kGIDSignInErrorCodeHasNoAuthInKeychain,
  380. @"error code should have been the 'NoAuthInKeychain' error code.");
  381. }];
  382. [self waitForExpectationsWithTimeout:1 handler:nil];
  383. [_authorization verify];
  384. [_authState verify];
  385. }
  386. - (void)testOAuthLogin {
  387. [self OAuthLoginWithAddScopesFlow:NO
  388. authError:nil
  389. tokenError:nil
  390. emmPasscodeInfoRequired:NO
  391. keychainError:NO
  392. restoredSignIn:NO
  393. oldAccessToken:NO
  394. modalCancel:NO];
  395. }
  396. - (void)testOAuthLogin_RestoredSignIn {
  397. [self OAuthLoginWithAddScopesFlow:NO
  398. authError:nil
  399. tokenError:nil
  400. emmPasscodeInfoRequired:NO
  401. keychainError:NO
  402. restoredSignIn:YES
  403. oldAccessToken:NO
  404. modalCancel:NO];
  405. }
  406. - (void)testOAuthLogin_RestoredSignInOldAccessToken {
  407. [self OAuthLoginWithAddScopesFlow:NO
  408. authError:nil
  409. tokenError:nil
  410. emmPasscodeInfoRequired:NO
  411. keychainError:NO
  412. restoredSignIn:YES
  413. oldAccessToken:YES
  414. modalCancel:NO];
  415. }
  416. - (void)testOAuthLogin_AdditionalScopes {
  417. NSString *expectedScopeString;
  418. [self OAuthLoginWithAddScopesFlow:NO
  419. authError:nil
  420. tokenError:nil
  421. emmPasscodeInfoRequired:NO
  422. keychainError:NO
  423. restoredSignIn:NO
  424. oldAccessToken:NO
  425. modalCancel:NO
  426. useAdditionalScopes:YES
  427. additionalScopes:nil];
  428. expectedScopeString = [@[ @"email", @"profile" ] componentsJoinedByString:@" "];
  429. XCTAssertEqualObjects(_savedAuthorizationRequest.scope, expectedScopeString);
  430. [self OAuthLoginWithAddScopesFlow:NO
  431. authError:nil
  432. tokenError:nil
  433. emmPasscodeInfoRequired:NO
  434. keychainError:NO
  435. restoredSignIn:NO
  436. oldAccessToken:NO
  437. modalCancel:NO
  438. useAdditionalScopes:YES
  439. additionalScopes:@[ kScope ]];
  440. expectedScopeString = [@[ kScope, @"email", @"profile" ] componentsJoinedByString:@" "];
  441. XCTAssertEqualObjects(_savedAuthorizationRequest.scope, expectedScopeString);
  442. [self OAuthLoginWithAddScopesFlow:NO
  443. authError:nil
  444. tokenError:nil
  445. emmPasscodeInfoRequired:NO
  446. keychainError:NO
  447. restoredSignIn:NO
  448. oldAccessToken:NO
  449. modalCancel:NO
  450. useAdditionalScopes:YES
  451. additionalScopes:@[ kScope, kScope2 ]];
  452. expectedScopeString = [@[ kScope, kScope2, @"email", @"profile" ] componentsJoinedByString:@" "];
  453. XCTAssertEqualObjects(_savedAuthorizationRequest.scope, expectedScopeString);
  454. }
  455. - (void)testAddScopes {
  456. // Restore the previous sign-in account. This is the preparation for adding scopes.
  457. [self OAuthLoginWithAddScopesFlow:NO
  458. authError:nil
  459. tokenError:nil
  460. emmPasscodeInfoRequired:NO
  461. keychainError:NO
  462. restoredSignIn:YES
  463. oldAccessToken:NO
  464. modalCancel:NO];
  465. XCTAssertNotNil(_signIn.currentUser);
  466. id profile = OCMStrictClassMock([GIDProfileData class]);
  467. OCMStub([profile email]).andReturn(kUserEmail);
  468. OCMStub([_user authentication]).andReturn(_authentication);
  469. OCMStub([_authentication clientID]).andReturn(kClientId);
  470. OCMStub([_user serverClientID]).andReturn(nil);
  471. OCMStub([_user hostedDomain]).andReturn(nil);
  472. OCMStub([_user openIDRealm]).andReturn(kOpenIDRealm);
  473. OCMStub([_user profile]).andReturn(profile);
  474. OCMStub([_user grantedScopes]).andReturn(@[kGrantedScope]);
  475. [self OAuthLoginWithAddScopesFlow:YES
  476. authError:nil
  477. tokenError:nil
  478. emmPasscodeInfoRequired:NO
  479. keychainError:NO
  480. restoredSignIn:NO
  481. oldAccessToken:NO
  482. modalCancel:NO];
  483. NSArray<NSString *> *grantedScopes;
  484. NSString *grantedScopeString = _savedAuthorizationRequest.scope;
  485. if (grantedScopeString) {
  486. grantedScopeString = [grantedScopeString stringByTrimmingCharactersInSet:
  487. [NSCharacterSet whitespaceCharacterSet]];
  488. // Tokenize with space as a delimiter.
  489. NSMutableArray<NSString *> *parsedScopes =
  490. [[grantedScopeString componentsSeparatedByString:@" "] mutableCopy];
  491. // Remove empty strings.
  492. [parsedScopes removeObject:@""];
  493. grantedScopes = [parsedScopes copy];
  494. }
  495. NSArray<NSString *> *expectedScopes = @[kNewScope, kGrantedScope];
  496. XCTAssertEqualObjects(grantedScopes, expectedScopes);
  497. [profile stopMocking];
  498. }
  499. - (void)testOpenIDRealm {
  500. _configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  501. serverClientID:nil
  502. hostedDomain:nil
  503. openIDRealm:kOpenIDRealm];
  504. [self OAuthLoginWithAddScopesFlow:NO
  505. authError:nil
  506. tokenError:nil
  507. emmPasscodeInfoRequired:NO
  508. keychainError:NO
  509. restoredSignIn:NO
  510. oldAccessToken:NO
  511. modalCancel:NO];
  512. NSDictionary<NSString *, NSString *> *params = _savedTokenRequest.additionalParameters;
  513. XCTAssertEqual(params[kOpenIDRealmKey], kOpenIDRealm, @"OpenID Realm should match.");
  514. }
  515. - (void)testOAuthLogin_LoginHint {
  516. _hint = kUserEmail;
  517. [self OAuthLoginWithAddScopesFlow:NO
  518. authError:nil
  519. tokenError:nil
  520. emmPasscodeInfoRequired:NO
  521. keychainError:NO
  522. restoredSignIn:NO
  523. oldAccessToken:NO
  524. modalCancel:NO];
  525. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  526. XCTAssertEqualObjects(params[@"login_hint"], kUserEmail, @"login hint should match");
  527. }
  528. - (void)testOAuthLogin_HostedDomain {
  529. _configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  530. serverClientID:nil
  531. hostedDomain:kHostedDomain
  532. openIDRealm:nil];
  533. [self OAuthLoginWithAddScopesFlow:NO
  534. authError:nil
  535. tokenError:nil
  536. emmPasscodeInfoRequired:NO
  537. keychainError:NO
  538. restoredSignIn:NO
  539. oldAccessToken:NO
  540. modalCancel:NO];
  541. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  542. XCTAssertEqualObjects(params[@"hd"], kHostedDomain, @"hosted domain should match");
  543. }
  544. - (void)testOAuthLogin_ConsentCanceled {
  545. [self OAuthLoginWithAddScopesFlow:NO
  546. authError:@"access_denied"
  547. tokenError:nil
  548. emmPasscodeInfoRequired:NO
  549. keychainError:NO
  550. restoredSignIn:NO
  551. oldAccessToken:NO
  552. modalCancel:NO];
  553. [self waitForExpectationsWithTimeout:1 handler:nil];
  554. XCTAssertTrue(_callbackCalled, @"should call delegate");
  555. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeCanceled);
  556. }
  557. - (void)testOAuthLogin_ModalCanceled {
  558. [self OAuthLoginWithAddScopesFlow:NO
  559. authError:nil
  560. tokenError:nil
  561. emmPasscodeInfoRequired:NO
  562. keychainError:NO
  563. restoredSignIn:NO
  564. oldAccessToken:NO
  565. modalCancel:YES];
  566. [self waitForExpectationsWithTimeout:1 handler:nil];
  567. XCTAssertTrue(_callbackCalled, @"should call delegate");
  568. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeCanceled);
  569. }
  570. - (void)testOAuthLogin_KeychainError {
  571. [self OAuthLoginWithAddScopesFlow:NO
  572. authError:nil
  573. tokenError:nil
  574. emmPasscodeInfoRequired:NO
  575. keychainError:YES
  576. restoredSignIn:NO
  577. oldAccessToken:NO
  578. modalCancel:NO];
  579. [self waitForExpectationsWithTimeout:1 handler:nil];
  580. XCTAssertFalse(_keychainSaved, @"should save to keychain");
  581. XCTAssertTrue(_callbackCalled, @"should call delegate");
  582. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  583. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeKeychain);
  584. }
  585. - (void)testSignOut {
  586. // Sign in a user so that we can then sign them out.
  587. [self OAuthLoginWithAddScopesFlow:NO
  588. authError:nil
  589. tokenError:nil
  590. emmPasscodeInfoRequired:NO
  591. keychainError:NO
  592. restoredSignIn:YES
  593. oldAccessToken:NO
  594. modalCancel:NO];
  595. XCTAssertNotNil(_signIn.currentUser);
  596. [_signIn signOut];
  597. XCTAssertNil(_signIn.currentUser, @"should not have a current user");
  598. XCTAssertTrue(_keychainRemoved, @"should remove keychain");
  599. XCTAssertTrue([_changedKeyPaths containsObject:NSStringFromSelector(@selector(currentUser))],
  600. @"should notify observers that signed in user changed");
  601. OCMVerify([_authorization removeAuthorizationFromKeychainForName:kKeychainName
  602. useDataProtectionKeychain:YES]);
  603. }
  604. - (void)testNotHandleWrongScheme {
  605. XCTAssertFalse([_signIn handleURL:[NSURL URLWithString:kWrongSchemeURL]],
  606. @"should not handle URL");
  607. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  608. XCTAssertFalse(_callbackCalled, @"should not call delegate");
  609. }
  610. - (void)testNotHandleWrongPath {
  611. XCTAssertFalse([_signIn handleURL:[NSURL URLWithString:kWrongPathURL]], @"should not handle URL");
  612. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  613. XCTAssertFalse(_callbackCalled, @"should not call delegate");
  614. }
  615. #pragma mark - Tests - disconnectWithCallback:
  616. // Verifies disconnect calls callback with no errors if access token is present.
  617. - (void)testDisconnect_accessToken {
  618. [[[_authorization expect] andReturn:_authState] authState];
  619. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  620. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  621. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  622. XCTestExpectation *expectation =
  623. [self expectationWithDescription:@"Callback called with nil error"];
  624. [_signIn disconnectWithCallback:^(NSError * _Nullable error) {
  625. if (error == nil) {
  626. [expectation fulfill];
  627. }
  628. }];
  629. [self verifyAndRevokeToken:kAccessToken hasCallback:YES];
  630. [_authorization verify];
  631. [_authState verify];
  632. [_tokenResponse verify];
  633. }
  634. // Verifies disconnect if access token is present.
  635. - (void)testDisconnectNoCallback_accessToken {
  636. [[[_authorization expect] andReturn:_authState] authState];
  637. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  638. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  639. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  640. [_signIn disconnectWithCallback:nil];
  641. [self verifyAndRevokeToken:kAccessToken hasCallback:NO];
  642. [_authorization verify];
  643. [_authState verify];
  644. [_tokenResponse verify];
  645. }
  646. // Verifies disconnect calls callback with no errors if refresh token is present.
  647. - (void)testDisconnect_refreshToken {
  648. [[[_authorization expect] andReturn:_authState] authState];
  649. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  650. [[[_tokenResponse expect] andReturn:nil] accessToken];
  651. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  652. [[[_tokenResponse expect] andReturn:kRefreshToken] refreshToken];
  653. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  654. XCTestExpectation *expectation =
  655. [self expectationWithDescription:@"Callback called with nil error"];
  656. [_signIn disconnectWithCallback:^(NSError * _Nullable error) {
  657. if (error == nil) {
  658. [expectation fulfill];
  659. }
  660. }];
  661. [self verifyAndRevokeToken:kRefreshToken hasCallback:YES];
  662. [_authorization verify];
  663. [_authState verify];
  664. [_tokenResponse verify];
  665. }
  666. // Verifies disconnect errors are passed along to the callback.
  667. - (void)testDisconnect_errors {
  668. [[[_authorization expect] andReturn:_authState] authState];
  669. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  670. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  671. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  672. XCTestExpectation *expectation =
  673. [self expectationWithDescription:@"Callback called with an error"];
  674. [_signIn disconnectWithCallback:^(NSError * _Nullable error) {
  675. if (error != nil) {
  676. [expectation fulfill];
  677. }
  678. }];
  679. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  680. // Emulate result back from server.
  681. NSError *error = [self error];
  682. [self didFetch:nil error:error];
  683. [self waitForExpectationsWithTimeout:1 handler:nil];
  684. [_authorization verify];
  685. [_authState verify];
  686. [_tokenResponse verify];
  687. }
  688. // Verifies disconnect with errors
  689. - (void)testDisconnectNoCallback_errors {
  690. [[[_authorization expect] andReturn:_authState] authState];
  691. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  692. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  693. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  694. [_signIn disconnectWithCallback:nil];
  695. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  696. // Emulate result back from server.
  697. NSError *error = [self error];
  698. [self didFetch:nil error:error];
  699. [_authorization verify];
  700. [_authState verify];
  701. [_tokenResponse verify];
  702. }
  703. // Verifies disconnect calls callback with no errors and clears keychain if no tokens are present.
  704. - (void)testDisconnect_noTokens {
  705. [[[_authorization expect] andReturn:_authState] authState];
  706. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  707. [[[_tokenResponse expect] andReturn:nil] accessToken];
  708. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  709. [[[_tokenResponse expect] andReturn:nil] refreshToken];
  710. XCTestExpectation *expectation =
  711. [self expectationWithDescription:@"Callback called with nil error"];
  712. [_signIn disconnectWithCallback:^(NSError * _Nullable error) {
  713. if (error == nil) {
  714. [expectation fulfill];
  715. }
  716. }];
  717. [self waitForExpectationsWithTimeout:1 handler:nil];
  718. XCTAssertFalse([self isFetcherStarted], @"should not fetch");
  719. XCTAssertTrue(_keychainRemoved, @"keychain should be removed");
  720. [_authorization verify];
  721. [_authState verify];
  722. [_tokenResponse verify];
  723. }
  724. // Verifies disconnect clears keychain if no tokens are present.
  725. - (void)testDisconnectNoCallback_noTokens {
  726. [[[_authorization expect] andReturn:_authState] authState];
  727. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  728. [[[_tokenResponse expect] andReturn:nil] accessToken];
  729. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  730. [[[_tokenResponse expect] andReturn:nil] refreshToken];
  731. [_signIn disconnectWithCallback:nil];
  732. XCTAssertFalse([self isFetcherStarted], @"should not fetch");
  733. XCTAssertTrue(_keychainRemoved, @"keychain should be removed");
  734. [_authorization verify];
  735. [_authState verify];
  736. [_tokenResponse verify];
  737. }
  738. - (void)testPresentingViewControllerException {
  739. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  740. _presentingViewController = nil;
  741. #elif TARGET_OS_OSX
  742. _presentingWindow = nil;
  743. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  744. XCTAssertThrows([_signIn signInWithConfiguration:_configuration
  745. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  746. presentingViewController:_presentingViewController
  747. #elif TARGET_OS_OSX
  748. presentingWindow:_presentingWindow
  749. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  750. hint:_hint
  751. callback:_callback]);
  752. }
  753. - (void)testClientIDMissingException {
  754. #pragma GCC diagnostic push
  755. #pragma GCC diagnostic ignored "-Wnonnull"
  756. GIDConfiguration *configuration = [[GIDConfiguration alloc] initWithClientID:nil];
  757. #pragma GCC diagnostic pop
  758. BOOL threw = NO;
  759. @try {
  760. [_signIn signInWithConfiguration:configuration
  761. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  762. presentingViewController:_presentingViewController
  763. #elif TARGET_OS_OSX
  764. presentingWindow:_presentingWindow
  765. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  766. callback:nil];
  767. } @catch (NSException *exception) {
  768. threw = YES;
  769. XCTAssertEqualObjects(exception.description,
  770. @"You must specify |clientID| in |GIDConfiguration|");
  771. } @finally {
  772. }
  773. XCTAssert(threw);
  774. }
  775. - (void)testSchemesNotSupportedException {
  776. [_fakeMainBundle fakeMissingAllSchemes];
  777. BOOL threw = NO;
  778. @try {
  779. [_signIn signInWithConfiguration:_configuration
  780. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  781. presentingViewController:_presentingViewController
  782. #elif TARGET_OS_OSX
  783. presentingWindow:_presentingWindow
  784. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  785. hint:_hint
  786. callback:_callback];
  787. } @catch (NSException *exception) {
  788. threw = YES;
  789. XCTAssertEqualObjects(exception.description,
  790. @"Your app is missing support for the following URL schemes: "
  791. "fakeclientid");
  792. } @finally {
  793. }
  794. XCTAssert(threw);
  795. }
  796. #pragma mark - Restarting Authentication Tests
  797. // Verifies that URL is not handled if there is no pending sign-in
  798. - (void)testRequiringPendingSignIn {
  799. BOOL result = [_signIn handleURL:[NSURL URLWithString:kEMMRestartAuthURL]];
  800. XCTAssertFalse(result);
  801. }
  802. #pragma mark - EMM tests
  803. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  804. - (void)testEmmSupportRequestParameters {
  805. [self OAuthLoginWithAddScopesFlow:NO
  806. authError:nil
  807. tokenError:nil
  808. emmPasscodeInfoRequired:NO
  809. keychainError:NO
  810. restoredSignIn:NO
  811. oldAccessToken:NO
  812. modalCancel:NO];
  813. NSString *systemName = [UIDevice currentDevice].systemName;
  814. if ([systemName isEqualToString:@"iPhone OS"]) {
  815. systemName = @"iOS";
  816. }
  817. NSString *expectedOSVersion = [NSString stringWithFormat:@"%@ %@",
  818. systemName, [UIDevice currentDevice].systemVersion];
  819. NSDictionary<NSString *, NSObject *> *authParams =
  820. _savedAuthorizationRequest.additionalParameters;
  821. NSDictionary<NSString *, NSString *> *tokenParams = _savedTokenRequest.additionalParameters;
  822. if (_isEligibleForEMM) {
  823. XCTAssertEqualObjects(authParams[@"emm_support"], kEMMSupport,
  824. @"EMM support should match in auth request");
  825. XCTAssertEqualObjects(authParams[@"device_os"], expectedOSVersion,
  826. @"OS version should match in auth request");
  827. XCTAssertEqualObjects(tokenParams[@"emm_support"], kEMMSupport,
  828. @"EMM support should match in token request");
  829. XCTAssertEqualObjects(tokenParams[@"device_os"],
  830. expectedOSVersion,
  831. @"OS version should match in token request");
  832. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  833. @"no passcode info should be in token request");
  834. } else {
  835. XCTAssertNil(authParams[@"emm_support"],
  836. @"EMM support should not be in auth request for unsupported OS");
  837. XCTAssertNil(authParams[@"device_os"],
  838. @"OS version should not be in auth request for unsupported OS");
  839. XCTAssertNil(tokenParams[@"emm_support"],
  840. @"EMM support should not be in token request for unsupported OS");
  841. XCTAssertNil(tokenParams[@"device_os"],
  842. @"OS version should not be in token request for unsupported OS");
  843. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  844. @"passcode info should not be in token request for unsupported OS");
  845. }
  846. }
  847. - (void)testEmmPasscodeInfo {
  848. [self OAuthLoginWithAddScopesFlow:NO
  849. authError:nil
  850. tokenError:nil
  851. emmPasscodeInfoRequired:YES
  852. keychainError:NO
  853. restoredSignIn:NO
  854. oldAccessToken:NO
  855. modalCancel:NO];
  856. NSDictionary<NSString *, NSString *> *tokenParams = _savedTokenRequest.additionalParameters;
  857. if (_isEligibleForEMM) {
  858. XCTAssertNotNil(tokenParams[@"emm_passcode_info"],
  859. @"passcode info should be in token request");
  860. } else {
  861. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  862. @"passcode info should not be in token request for unsupported OS");
  863. }
  864. }
  865. - (void)testAuthEndpointEMMError {
  866. if (!_isEligibleForEMM) {
  867. return;
  868. }
  869. id mockEMMErrorHandler = OCMStrictClassMock([GIDEMMErrorHandler class]);
  870. [[[mockEMMErrorHandler stub] andReturn:mockEMMErrorHandler] sharedInstance];
  871. __block void (^completion)(void);
  872. NSDictionary<NSString *, NSString *> *callbackParams = @{ @"error" : @"EMM Specific Error" };
  873. [[[mockEMMErrorHandler expect] andReturnValue:@YES]
  874. handleErrorFromResponse:callbackParams completion:SAVE_TO_ARG_BLOCK(completion)];
  875. [self OAuthLoginWithAddScopesFlow:NO
  876. authError:callbackParams[@"error"]
  877. tokenError:nil
  878. emmPasscodeInfoRequired:NO
  879. keychainError:NO
  880. restoredSignIn:NO
  881. oldAccessToken:NO
  882. modalCancel:NO];
  883. [mockEMMErrorHandler verify];
  884. [mockEMMErrorHandler stopMocking];
  885. completion();
  886. [self waitForExpectationsWithTimeout:1 handler:nil];
  887. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  888. XCTAssertTrue(_callbackCalled, @"should call delegate");
  889. XCTAssertNotNil(_authError, @"should have error");
  890. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  891. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  892. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  893. }
  894. - (void)testTokenEndpointEMMError {
  895. if (!_isEligibleForEMM) {
  896. return;
  897. }
  898. __block void (^completion)(NSError *);
  899. NSDictionary *errorJSON = @{ @"error" : @"EMM Specific Error" };
  900. NSError *emmError = [NSError errorWithDomain:@"anydomain"
  901. code:12345
  902. userInfo:@{ OIDOAuthErrorFieldError : errorJSON }];
  903. [[_authentication expect] handleTokenFetchEMMError:emmError
  904. completion:SAVE_TO_ARG_BLOCK(completion)];
  905. [self OAuthLoginWithAddScopesFlow:NO
  906. authError:nil
  907. tokenError:emmError
  908. emmPasscodeInfoRequired:NO
  909. keychainError:NO
  910. restoredSignIn:NO
  911. oldAccessToken:NO
  912. modalCancel:NO];
  913. NSError *handledError = [NSError errorWithDomain:kGIDSignInErrorDomain
  914. code:kGIDSignInErrorCodeEMM
  915. userInfo:emmError.userInfo];
  916. completion(handledError);
  917. [self waitForExpectationsWithTimeout:1 handler:nil];
  918. [_authentication verify];
  919. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  920. XCTAssertTrue(_callbackCalled, @"should call delegate");
  921. XCTAssertNotNil(_authError, @"should have error");
  922. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  923. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  924. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  925. }
  926. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  927. #pragma mark - Helpers
  928. // Whether or not a fetcher has been started.
  929. - (BOOL)isFetcherStarted {
  930. NSUInteger count = _fetcherService.fetchers.count;
  931. XCTAssertTrue(count <= 1, @"Only one fetcher is supported");
  932. return !!count;
  933. }
  934. // Gets the URL being fetched.
  935. - (NSURL *)fetchedURL {
  936. return [_fetcherService.fetchers[0] requestURL];
  937. }
  938. // Emulates server returning the data as in JSON.
  939. - (void)didFetch:(id)dataObject error:(NSError *)error {
  940. NSData *data = nil;
  941. if (dataObject) {
  942. NSError *jsonError = nil;
  943. data = [NSJSONSerialization dataWithJSONObject:dataObject
  944. options:0
  945. error:&jsonError];
  946. XCTAssertNil(jsonError, @"must provide valid data");
  947. }
  948. [_fetcherService.fetchers[0] didFinishWithData:data error:error];
  949. }
  950. - (NSError *)error {
  951. return [NSError errorWithDomain:kErrorDomain code:kErrorCode userInfo:nil];
  952. }
  953. // Verifies a fetcher has started for revoking token and emulates a server response.
  954. - (void)verifyAndRevokeToken:(NSString *)token hasCallback:(BOOL)hasCallback {
  955. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  956. NSURL *url = [self fetchedURL];
  957. XCTAssertEqualObjects([url scheme], @"https", @"scheme must match");
  958. XCTAssertEqualObjects([url host], @"accounts.google.com", @"host must match");
  959. XCTAssertEqualObjects([url path], @"/o/oauth2/revoke", @"path must match");
  960. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  961. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  962. XCTAssertEqualObjects([params valueForKey:@"token"], token,
  963. @"token parameter should match");
  964. XCTAssertEqualObjects([params valueForKey:kSDKVersionLoggingParameter], GIDVersion(),
  965. @"SDK version logging parameter should match");
  966. XCTAssertEqualObjects([params valueForKey:kEnvironmentLoggingParameter], GIDEnvironment(),
  967. @"Environment logging parameter should match");
  968. // Emulate result back from server.
  969. [self didFetch:nil error:nil];
  970. if (hasCallback) {
  971. [self waitForExpectationsWithTimeout:1 handler:nil];
  972. }
  973. XCTAssertTrue(_keychainRemoved, @"should clear saved keychain name");
  974. }
  975. - (void)OAuthLoginWithAddScopesFlow:(BOOL)addScopesFlow
  976. authError:(NSString *)authError
  977. tokenError:(NSError *)tokenError
  978. emmPasscodeInfoRequired:(BOOL)emmPasscodeInfoRequired
  979. keychainError:(BOOL)keychainError
  980. restoredSignIn:(BOOL)restoredSignIn
  981. oldAccessToken:(BOOL)oldAccessToken
  982. modalCancel:(BOOL)modalCancel {
  983. [self OAuthLoginWithAddScopesFlow:addScopesFlow
  984. authError:authError
  985. tokenError:tokenError
  986. emmPasscodeInfoRequired:emmPasscodeInfoRequired
  987. keychainError:keychainError
  988. restoredSignIn:restoredSignIn
  989. oldAccessToken:oldAccessToken
  990. modalCancel:modalCancel
  991. useAdditionalScopes:NO
  992. additionalScopes:nil];
  993. }
  994. // The authorization flow with parameters to control which branches to take.
  995. - (void)OAuthLoginWithAddScopesFlow:(BOOL)addScopesFlow
  996. authError:(NSString *)authError
  997. tokenError:(NSError *)tokenError
  998. emmPasscodeInfoRequired:(BOOL)emmPasscodeInfoRequired
  999. keychainError:(BOOL)keychainError
  1000. restoredSignIn:(BOOL)restoredSignIn
  1001. oldAccessToken:(BOOL)oldAccessToken
  1002. modalCancel:(BOOL)modalCancel
  1003. useAdditionalScopes:(BOOL)useAdditionalScopes
  1004. additionalScopes:(NSArray *)additionalScopes {
  1005. if (restoredSignIn) {
  1006. // clearAndAuthenticateWithOptions
  1007. [[[_authorization expect] andReturn:_authState] authState];
  1008. BOOL isAuthorized = restoredSignIn ? YES : NO;
  1009. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:isAuthorized]] isAuthorized];
  1010. }
  1011. NSDictionary<NSString *, NSString *> *additionalParameters = emmPasscodeInfoRequired ?
  1012. @{ @"emm_passcode_info_required" : @"1" } : nil;
  1013. OIDAuthorizationResponse *authResponse =
  1014. [OIDAuthorizationResponse testInstanceWithAdditionalParameters:additionalParameters
  1015. errorString:authError];
  1016. OIDTokenResponse *tokenResponse =
  1017. [OIDTokenResponse testInstanceWithIDToken:[OIDTokenResponse fatIDToken]
  1018. accessToken:restoredSignIn ? kAccessToken : nil
  1019. expiresIn:oldAccessToken ? @(300) : nil
  1020. tokenRequest:nil];
  1021. OIDTokenRequest *tokenRequest = [[OIDTokenRequest alloc]
  1022. initWithConfiguration:authResponse.request.configuration
  1023. grantType:OIDGrantTypeRefreshToken
  1024. authorizationCode:nil
  1025. redirectURL:nil
  1026. clientID:authResponse.request.clientID
  1027. clientSecret:authResponse.request.clientSecret
  1028. scope:nil
  1029. refreshToken:kRefreshToken
  1030. codeVerifier:nil
  1031. additionalParameters:tokenResponse.request.additionalParameters];
  1032. if (restoredSignIn) {
  1033. // maybeFetchToken
  1034. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1035. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1036. if (oldAccessToken) {
  1037. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1038. // Corresponds to EMM support
  1039. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1040. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1041. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1042. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1043. [[[_authState expect] andReturn:tokenRequest]
  1044. tokenRefreshRequestWithAdditionalParameters:[OCMArg any]];
  1045. }
  1046. } else {
  1047. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback called"];
  1048. GIDSignInCallback callback = ^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) {
  1049. [expectation fulfill];
  1050. if (!user) {
  1051. XCTAssertNotNil(error, @"should have an error if user is nil");
  1052. }
  1053. XCTAssertFalse(self->_callbackCalled, @"callback already called");
  1054. self->_callbackCalled = YES;
  1055. self->_authError = error;
  1056. };
  1057. if (addScopesFlow) {
  1058. [_signIn addScopes:@[kNewScope]
  1059. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1060. presentingViewController:_presentingViewController
  1061. #elif TARGET_OS_OSX
  1062. presentingWindow:_presentingWindow
  1063. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1064. callback:callback];
  1065. } else {
  1066. if (useAdditionalScopes) {
  1067. [_signIn signInWithConfiguration:_configuration
  1068. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1069. presentingViewController:_presentingViewController
  1070. #elif TARGET_OS_OSX
  1071. presentingWindow:_presentingWindow
  1072. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1073. hint:_hint
  1074. additionalScopes:additionalScopes
  1075. callback:callback];
  1076. } else {
  1077. [_signIn signInWithConfiguration:_configuration
  1078. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1079. presentingViewController:_presentingViewController
  1080. #elif TARGET_OS_OSX
  1081. presentingWindow:_presentingWindow
  1082. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1083. hint:_hint
  1084. callback:callback];
  1085. }
  1086. }
  1087. [_authorization verify];
  1088. [_authState verify];
  1089. XCTAssertNotNil(_savedAuthorizationRequest);
  1090. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  1091. XCTAssertEqualObjects(params[@"include_granted_scopes"], @"true");
  1092. XCTAssertEqualObjects(params[kSDKVersionLoggingParameter], GIDVersion());
  1093. XCTAssertEqualObjects(params[kEnvironmentLoggingParameter], GIDEnvironment());
  1094. XCTAssertNotNil(_savedAuthorizationCallback);
  1095. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1096. XCTAssertEqual(_savedPresentingViewController, _presentingViewController);
  1097. #elif TARGET_OS_OSX
  1098. XCTAssertEqual(_savedPresentingWindow, _presentingWindow);
  1099. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1100. // maybeFetchToken
  1101. if (!(authError || modalCancel)) {
  1102. [[[_authState expect] andReturn:nil] lastTokenResponse];
  1103. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1104. // Corresponds to EMM support
  1105. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1106. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1107. [[[_authState expect] andReturn:nil] lastTokenResponse];
  1108. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1109. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1110. }
  1111. // Simulate auth endpoint response
  1112. if (modalCancel) {
  1113. NSError *error = [NSError errorWithDomain:OIDGeneralErrorDomain
  1114. code:OIDErrorCodeUserCanceledAuthorizationFlow
  1115. userInfo:nil];
  1116. _savedAuthorizationCallback(nil, error);
  1117. } else {
  1118. _savedAuthorizationCallback(authResponse, nil);
  1119. }
  1120. if (authError || modalCancel) {
  1121. return;
  1122. }
  1123. [_authState verify];
  1124. }
  1125. if (restoredSignIn && oldAccessToken) {
  1126. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  1127. [_signIn restorePreviousSignInWithCallback:^(GIDGoogleUser * _Nullable user,
  1128. NSError * _Nullable error) {
  1129. [expectation fulfill];
  1130. XCTAssertNil(error, @"should have no error");
  1131. }];
  1132. }
  1133. if (!restoredSignIn || (restoredSignIn && oldAccessToken)) {
  1134. XCTAssertNotNil(_savedTokenRequest);
  1135. XCTAssertNotNil(_savedTokenCallback);
  1136. // OIDTokenCallback
  1137. if (tokenError) {
  1138. [[_authState expect] updateWithTokenResponse:nil error:tokenError];
  1139. } else {
  1140. [[_authState expect] updateWithTokenResponse:[OCMArg any] error:nil];
  1141. }
  1142. }
  1143. if (tokenError) {
  1144. _savedTokenCallback(nil, tokenError);
  1145. return;
  1146. }
  1147. // DecodeIdTokenCallback
  1148. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1149. // SaveAuthCallback
  1150. __block OIDAuthState *authState;
  1151. __block GIDProfileData *profileData;
  1152. if (keychainError) {
  1153. _saveAuthorizationReturnValue = NO;
  1154. } else {
  1155. if (addScopesFlow) {
  1156. [[_user expect] updateAuthState:SAVE_TO_ARG_BLOCK(authState)
  1157. profileData:SAVE_TO_ARG_BLOCK(profileData)];
  1158. } else {
  1159. [[[_user stub] andReturn:_user] alloc];
  1160. (void)[[[_user expect] andReturn:_user] initWithAuthState:SAVE_TO_ARG_BLOCK(authState)
  1161. profileData:SAVE_TO_ARG_BLOCK(profileData)];
  1162. }
  1163. }
  1164. if (restoredSignIn && !oldAccessToken) {
  1165. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  1166. [_signIn restorePreviousSignInWithCallback:^(GIDGoogleUser * _Nullable user,
  1167. NSError * _Nullable error) {
  1168. [expectation fulfill];
  1169. XCTAssertNil(error, @"should have no error");
  1170. }];
  1171. } else {
  1172. // Simulate token endpoint response.
  1173. _savedTokenCallback(tokenResponse, nil);
  1174. }
  1175. [_authState verify];
  1176. if (keychainError) {
  1177. return;
  1178. }
  1179. [self waitForExpectationsWithTimeout:1 handler:nil];
  1180. XCTAssertTrue(_keychainSaved, @"should save to keychain");
  1181. XCTAssertNotNil(authState);
  1182. // Check fat ID token decoding
  1183. XCTAssertEqualObjects(profileData.name, kFatName);
  1184. XCTAssertEqualObjects(profileData.givenName, kFatGivenName);
  1185. XCTAssertEqualObjects(profileData.familyName, kFatFamilyName);
  1186. XCTAssertTrue(profileData.hasImage);
  1187. // If attempt to authenticate again, will reuse existing auth object.
  1188. _callbackCalled = NO;
  1189. _keychainRemoved = NO;
  1190. _keychainSaved = NO;
  1191. _authError = nil;
  1192. if (!addScopesFlow) {
  1193. [[[_user expect] andReturn:_authentication] authentication];
  1194. [[[_user expect] andReturn:_authentication] authentication];
  1195. }
  1196. __block GIDAuthenticationAction action;
  1197. [[_authentication expect] doWithFreshTokens:SAVE_TO_ARG_BLOCK(action)];
  1198. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  1199. [_signIn restorePreviousSignInWithCallback:^(GIDGoogleUser * _Nullable user,
  1200. NSError * _Nullable error) {
  1201. [expectation fulfill];
  1202. XCTAssertNil(error, @"should have no error");
  1203. }];
  1204. action(_authentication, nil);
  1205. [self waitForExpectationsWithTimeout:1 handler:nil];
  1206. XCTAssertFalse(_keychainRemoved, @"should not remove keychain");
  1207. XCTAssertFalse(_keychainSaved, @"should not save to keychain again");
  1208. if (restoredSignIn) {
  1209. OCMVerify([_authorization authorizationFromKeychainForName:kKeychainName
  1210. useDataProtectionKeychain:YES]);
  1211. OCMVerify([_authorization saveAuthorization:OCMOCK_ANY
  1212. toKeychainForName:kKeychainName
  1213. useDataProtectionKeychain:YES]);
  1214. }
  1215. }
  1216. #pragma mark - Key Value Observing
  1217. - (void)observeValueForKeyPath:(NSString *)keyPath
  1218. ofObject:(id)object
  1219. change:(NSDictionary<NSKeyValueChangeKey, id> *)change
  1220. context:(void *)context {
  1221. if (context == kTestObserverContext && object == _signIn) {
  1222. [_changedKeyPaths addObject:keyPath];
  1223. }
  1224. }
  1225. @end