GIDSignInTest.m 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444
  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 _completionCalled;
  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 completion to be used when testing |GIDSignIn|.
  193. GIDUserAuthCompletion _completion;
  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. _completionCalled = 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. _completion = ^(GIDUserAuth *_Nullable userAuth, NSError * _Nullable error) {
  283. GIDSignInTest *strongSelf = weakSelf;
  284. if (!userAuth) {
  285. XCTAssertNotNil(error, @"should have an error if the userAuth is nil");
  286. }
  287. XCTAssertFalse(strongSelf->_completionCalled, @"callback already called");
  288. strongSelf->_completionCalled = 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. id idTokenDecoded = OCMClassMock([OIDIDToken class]);
  325. OCMStub([idTokenDecoded alloc]).andReturn(idTokenDecoded);
  326. OCMStub([idTokenDecoded initWithIDTokenString:OCMOCK_ANY]).andReturn(idTokenDecoded);
  327. OCMStub([idTokenDecoded subject]).andReturn(kFakeGaiaID);
  328. // Mock generating a GIDConfiguration when initializing GIDGoogleUser.
  329. OIDAuthorizationResponse *authResponse =
  330. [OIDAuthorizationResponse testInstanceWithAdditionalParameters:nil
  331. errorString:nil];
  332. OCMStub([_authState lastAuthorizationResponse]).andReturn(authResponse);
  333. OCMStub([_tokenResponse idToken]).andReturn(kFakeIDToken);
  334. OCMStub([_tokenResponse request]).andReturn(_tokenRequest);
  335. OCMStub([_tokenRequest additionalParameters]).andReturn(nil);
  336. [_signIn restorePreviousSignInNoRefresh];
  337. [_authorization verify];
  338. [_authState verify];
  339. [_tokenResponse verify];
  340. [_tokenRequest verify];
  341. [idTokenDecoded verify];
  342. XCTAssertEqual(_signIn.currentUser.userID, kFakeGaiaID);
  343. [idTokenDecoded stopMocking];
  344. }
  345. - (void)testRestoredPreviousSignInNoRefresh_hasNoPreviousUser {
  346. [[[_authorization expect] andReturn:nil] authState];
  347. [_signIn restorePreviousSignInNoRefresh];
  348. [_authorization verify];
  349. XCTAssertNil(_signIn.currentUser);
  350. }
  351. - (void)testHasPreviousSignIn_HasBeenAuthenticated {
  352. [[[_authorization expect] andReturn:_authState] authState];
  353. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:YES]] isAuthorized];
  354. XCTAssertTrue([_signIn hasPreviousSignIn], @"should return |YES|");
  355. [_authorization verify];
  356. [_authState verify];
  357. XCTAssertFalse(_keychainRemoved, @"should not remove keychain");
  358. XCTAssertFalse(_completionCalled, @"should not call delegate");
  359. XCTAssertNil(_authError, @"should have no error");
  360. }
  361. - (void)testHasPreviousSignIn_HasNotBeenAuthenticated {
  362. [[[_authorization expect] andReturn:_authState] authState];
  363. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:NO]] isAuthorized];
  364. XCTAssertFalse([_signIn hasPreviousSignIn], @"should return |NO|");
  365. [_authorization verify];
  366. [_authState verify];
  367. XCTAssertFalse(_keychainRemoved, @"should not remove keychain");
  368. XCTAssertFalse(_completionCalled, @"should not call delegate");
  369. }
  370. - (void)testRestorePreviousSignInWhenSignedOut {
  371. [[[_authorization expect] andReturn:_authState] authState];
  372. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:NO]] isAuthorized];
  373. _completionCalled = NO;
  374. _authError = nil;
  375. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called."];
  376. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser *_Nullable user,
  377. NSError * _Nullable error) {
  378. [expectation fulfill];
  379. XCTAssertNotNil(error, @"error should not have been nil");
  380. XCTAssertEqual(error.domain,
  381. kGIDSignInErrorDomain,
  382. @"error domain should have been the sign-in error domain.");
  383. XCTAssertEqual(error.code,
  384. kGIDSignInErrorCodeHasNoAuthInKeychain,
  385. @"error code should have been the 'NoAuthInKeychain' error code.");
  386. }];
  387. [self waitForExpectationsWithTimeout:1 handler:nil];
  388. [_authorization verify];
  389. [_authState verify];
  390. }
  391. - (void)testOAuthLogin {
  392. [self OAuthLoginWithAddScopesFlow:NO
  393. authError:nil
  394. tokenError:nil
  395. emmPasscodeInfoRequired:NO
  396. keychainError:NO
  397. restoredSignIn:NO
  398. oldAccessToken:NO
  399. modalCancel:NO];
  400. }
  401. - (void)testOAuthLogin_RestoredSignIn {
  402. [self OAuthLoginWithAddScopesFlow:NO
  403. authError:nil
  404. tokenError:nil
  405. emmPasscodeInfoRequired:NO
  406. keychainError:NO
  407. restoredSignIn:YES
  408. oldAccessToken:NO
  409. modalCancel:NO];
  410. }
  411. - (void)testOAuthLogin_RestoredSignInOldAccessToken {
  412. [self OAuthLoginWithAddScopesFlow:NO
  413. authError:nil
  414. tokenError:nil
  415. emmPasscodeInfoRequired:NO
  416. keychainError:NO
  417. restoredSignIn:YES
  418. oldAccessToken:YES
  419. modalCancel:NO];
  420. }
  421. - (void)testOAuthLogin_AdditionalScopes {
  422. NSString *expectedScopeString;
  423. [self OAuthLoginWithAddScopesFlow:NO
  424. authError:nil
  425. tokenError:nil
  426. emmPasscodeInfoRequired:NO
  427. keychainError:NO
  428. restoredSignIn:NO
  429. oldAccessToken:NO
  430. modalCancel:NO
  431. useAdditionalScopes:YES
  432. additionalScopes:nil];
  433. expectedScopeString = [@[ @"email", @"profile" ] componentsJoinedByString:@" "];
  434. XCTAssertEqualObjects(_savedAuthorizationRequest.scope, expectedScopeString);
  435. [self OAuthLoginWithAddScopesFlow:NO
  436. authError:nil
  437. tokenError:nil
  438. emmPasscodeInfoRequired:NO
  439. keychainError:NO
  440. restoredSignIn:NO
  441. oldAccessToken:NO
  442. modalCancel:NO
  443. useAdditionalScopes:YES
  444. additionalScopes:@[ kScope ]];
  445. expectedScopeString = [@[ kScope, @"email", @"profile" ] componentsJoinedByString:@" "];
  446. XCTAssertEqualObjects(_savedAuthorizationRequest.scope, expectedScopeString);
  447. [self OAuthLoginWithAddScopesFlow:NO
  448. authError:nil
  449. tokenError:nil
  450. emmPasscodeInfoRequired:NO
  451. keychainError:NO
  452. restoredSignIn:NO
  453. oldAccessToken:NO
  454. modalCancel:NO
  455. useAdditionalScopes:YES
  456. additionalScopes:@[ kScope, kScope2 ]];
  457. expectedScopeString = [@[ kScope, kScope2, @"email", @"profile" ] componentsJoinedByString:@" "];
  458. XCTAssertEqualObjects(_savedAuthorizationRequest.scope, expectedScopeString);
  459. }
  460. - (void)testAddScopes {
  461. // Restore the previous sign-in account. This is the preparation for adding scopes.
  462. [self OAuthLoginWithAddScopesFlow:NO
  463. authError:nil
  464. tokenError:nil
  465. emmPasscodeInfoRequired:NO
  466. keychainError:NO
  467. restoredSignIn:YES
  468. oldAccessToken:NO
  469. modalCancel:NO];
  470. XCTAssertNotNil(_signIn.currentUser);
  471. id profile = OCMStrictClassMock([GIDProfileData class]);
  472. OCMStub([profile email]).andReturn(kUserEmail);
  473. OCMStub([_user authentication]).andReturn(_authentication);
  474. // Mock for the method `addScopes`.
  475. OCMStub([_user configuration]).andReturn(_configuration);
  476. OCMStub([_user profile]).andReturn(profile);
  477. OCMStub([_user grantedScopes]).andReturn(@[kGrantedScope]);
  478. [self OAuthLoginWithAddScopesFlow:YES
  479. authError:nil
  480. tokenError:nil
  481. emmPasscodeInfoRequired:NO
  482. keychainError:NO
  483. restoredSignIn:NO
  484. oldAccessToken:NO
  485. modalCancel:NO];
  486. NSArray<NSString *> *grantedScopes;
  487. NSString *grantedScopeString = _savedAuthorizationRequest.scope;
  488. if (grantedScopeString) {
  489. grantedScopeString = [grantedScopeString stringByTrimmingCharactersInSet:
  490. [NSCharacterSet whitespaceCharacterSet]];
  491. // Tokenize with space as a delimiter.
  492. NSMutableArray<NSString *> *parsedScopes =
  493. [[grantedScopeString componentsSeparatedByString:@" "] mutableCopy];
  494. // Remove empty strings.
  495. [parsedScopes removeObject:@""];
  496. grantedScopes = [parsedScopes copy];
  497. }
  498. NSArray<NSString *> *expectedScopes = @[kNewScope, kGrantedScope];
  499. XCTAssertEqualObjects(grantedScopes, expectedScopes);
  500. [_user verify];
  501. [profile verify];
  502. [profile stopMocking];
  503. }
  504. - (void)testOpenIDRealm {
  505. _configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  506. serverClientID:nil
  507. hostedDomain:nil
  508. openIDRealm:kOpenIDRealm];
  509. [self OAuthLoginWithAddScopesFlow:NO
  510. authError:nil
  511. tokenError:nil
  512. emmPasscodeInfoRequired:NO
  513. keychainError:NO
  514. restoredSignIn:NO
  515. oldAccessToken:NO
  516. modalCancel:NO];
  517. NSDictionary<NSString *, NSString *> *params = _savedTokenRequest.additionalParameters;
  518. XCTAssertEqual(params[kOpenIDRealmKey], kOpenIDRealm, @"OpenID Realm should match.");
  519. }
  520. - (void)testOAuthLogin_LoginHint {
  521. _hint = kUserEmail;
  522. [self OAuthLoginWithAddScopesFlow:NO
  523. authError:nil
  524. tokenError:nil
  525. emmPasscodeInfoRequired:NO
  526. keychainError:NO
  527. restoredSignIn:NO
  528. oldAccessToken:NO
  529. modalCancel:NO];
  530. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  531. XCTAssertEqualObjects(params[@"login_hint"], kUserEmail, @"login hint should match");
  532. }
  533. - (void)testOAuthLogin_HostedDomain {
  534. _configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  535. serverClientID:nil
  536. hostedDomain:kHostedDomain
  537. openIDRealm:nil];
  538. [self OAuthLoginWithAddScopesFlow:NO
  539. authError:nil
  540. tokenError:nil
  541. emmPasscodeInfoRequired:NO
  542. keychainError:NO
  543. restoredSignIn:NO
  544. oldAccessToken:NO
  545. modalCancel:NO];
  546. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  547. XCTAssertEqualObjects(params[@"hd"], kHostedDomain, @"hosted domain should match");
  548. }
  549. - (void)testOAuthLogin_ConsentCanceled {
  550. [self OAuthLoginWithAddScopesFlow:NO
  551. authError:@"access_denied"
  552. tokenError:nil
  553. emmPasscodeInfoRequired:NO
  554. keychainError:NO
  555. restoredSignIn:NO
  556. oldAccessToken:NO
  557. modalCancel:NO];
  558. [self waitForExpectationsWithTimeout:1 handler:nil];
  559. XCTAssertTrue(_completionCalled, @"should call delegate");
  560. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeCanceled);
  561. }
  562. - (void)testOAuthLogin_ModalCanceled {
  563. [self OAuthLoginWithAddScopesFlow:NO
  564. authError:nil
  565. tokenError:nil
  566. emmPasscodeInfoRequired:NO
  567. keychainError:NO
  568. restoredSignIn:NO
  569. oldAccessToken:NO
  570. modalCancel:YES];
  571. [self waitForExpectationsWithTimeout:1 handler:nil];
  572. XCTAssertTrue(_completionCalled, @"should call delegate");
  573. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeCanceled);
  574. }
  575. - (void)testOAuthLogin_KeychainError {
  576. [self OAuthLoginWithAddScopesFlow:NO
  577. authError:nil
  578. tokenError:nil
  579. emmPasscodeInfoRequired:NO
  580. keychainError:YES
  581. restoredSignIn:NO
  582. oldAccessToken:NO
  583. modalCancel:NO];
  584. [self waitForExpectationsWithTimeout:1 handler:nil];
  585. XCTAssertFalse(_keychainSaved, @"should save to keychain");
  586. XCTAssertTrue(_completionCalled, @"should call delegate");
  587. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  588. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeKeychain);
  589. }
  590. - (void)testSignOut {
  591. // Sign in a user so that we can then sign them out.
  592. [self OAuthLoginWithAddScopesFlow:NO
  593. authError:nil
  594. tokenError:nil
  595. emmPasscodeInfoRequired:NO
  596. keychainError:NO
  597. restoredSignIn:YES
  598. oldAccessToken:NO
  599. modalCancel:NO];
  600. XCTAssertNotNil(_signIn.currentUser);
  601. [_signIn signOut];
  602. XCTAssertNil(_signIn.currentUser, @"should not have a current user");
  603. XCTAssertTrue(_keychainRemoved, @"should remove keychain");
  604. XCTAssertTrue([_changedKeyPaths containsObject:NSStringFromSelector(@selector(currentUser))],
  605. @"should notify observers that signed in user changed");
  606. OCMVerify([_authorization removeAuthorizationFromKeychainForName:kKeychainName
  607. useDataProtectionKeychain:YES]);
  608. }
  609. - (void)testNotHandleWrongScheme {
  610. XCTAssertFalse([_signIn handleURL:[NSURL URLWithString:kWrongSchemeURL]],
  611. @"should not handle URL");
  612. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  613. XCTAssertFalse(_completionCalled, @"should not call delegate");
  614. }
  615. - (void)testNotHandleWrongPath {
  616. XCTAssertFalse([_signIn handleURL:[NSURL URLWithString:kWrongPathURL]], @"should not handle URL");
  617. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  618. XCTAssertFalse(_completionCalled, @"should not call delegate");
  619. }
  620. #pragma mark - Tests - disconnectWithCallback:
  621. // Verifies disconnect calls callback with no errors if access token is present.
  622. - (void)testDisconnect_accessToken {
  623. [[[_authorization expect] andReturn:_authState] authState];
  624. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  625. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  626. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  627. XCTestExpectation *expectation =
  628. [self expectationWithDescription:@"Callback called with nil error"];
  629. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  630. if (error == nil) {
  631. [expectation fulfill];
  632. }
  633. }];
  634. [self verifyAndRevokeToken:kAccessToken hasCallback:YES];
  635. [_authorization verify];
  636. [_authState verify];
  637. [_tokenResponse verify];
  638. }
  639. // Verifies disconnect if access token is present.
  640. - (void)testDisconnectNoCallback_accessToken {
  641. [[[_authorization expect] andReturn:_authState] authState];
  642. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  643. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  644. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  645. [_signIn disconnectWithCompletion:nil];
  646. [self verifyAndRevokeToken:kAccessToken hasCallback:NO];
  647. [_authorization verify];
  648. [_authState verify];
  649. [_tokenResponse verify];
  650. }
  651. // Verifies disconnect calls callback with no errors if refresh token is present.
  652. - (void)testDisconnect_refreshToken {
  653. [[[_authorization expect] andReturn:_authState] authState];
  654. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  655. [[[_tokenResponse expect] andReturn:nil] accessToken];
  656. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  657. [[[_tokenResponse expect] andReturn:kRefreshToken] refreshToken];
  658. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  659. XCTestExpectation *expectation =
  660. [self expectationWithDescription:@"Callback called with nil error"];
  661. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  662. if (error == nil) {
  663. [expectation fulfill];
  664. }
  665. }];
  666. [self verifyAndRevokeToken:kRefreshToken hasCallback:YES];
  667. [_authorization verify];
  668. [_authState verify];
  669. [_tokenResponse verify];
  670. }
  671. // Verifies disconnect errors are passed along to the callback.
  672. - (void)testDisconnect_errors {
  673. [[[_authorization expect] andReturn:_authState] authState];
  674. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  675. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  676. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  677. XCTestExpectation *expectation =
  678. [self expectationWithDescription:@"Callback called with an error"];
  679. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  680. if (error != nil) {
  681. [expectation fulfill];
  682. }
  683. }];
  684. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  685. // Emulate result back from server.
  686. NSError *error = [self error];
  687. [self didFetch:nil error:error];
  688. [self waitForExpectationsWithTimeout:1 handler:nil];
  689. [_authorization verify];
  690. [_authState verify];
  691. [_tokenResponse verify];
  692. }
  693. // Verifies disconnect with errors
  694. - (void)testDisconnectNoCallback_errors {
  695. [[[_authorization expect] andReturn:_authState] authState];
  696. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  697. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  698. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  699. [_signIn disconnectWithCompletion:nil];
  700. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  701. // Emulate result back from server.
  702. NSError *error = [self error];
  703. [self didFetch:nil error:error];
  704. [_authorization verify];
  705. [_authState verify];
  706. [_tokenResponse verify];
  707. }
  708. // Verifies disconnect calls callback with no errors and clears keychain if no tokens are present.
  709. - (void)testDisconnect_noTokens {
  710. [[[_authorization expect] andReturn:_authState] authState];
  711. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  712. [[[_tokenResponse expect] andReturn:nil] accessToken];
  713. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  714. [[[_tokenResponse expect] andReturn:nil] refreshToken];
  715. XCTestExpectation *expectation =
  716. [self expectationWithDescription:@"Callback called with nil error"];
  717. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  718. if (error == nil) {
  719. [expectation fulfill];
  720. }
  721. }];
  722. [self waitForExpectationsWithTimeout:1 handler:nil];
  723. XCTAssertFalse([self isFetcherStarted], @"should not fetch");
  724. XCTAssertTrue(_keychainRemoved, @"keychain should be removed");
  725. [_authorization verify];
  726. [_authState verify];
  727. [_tokenResponse verify];
  728. }
  729. // Verifies disconnect clears keychain if no tokens are present.
  730. - (void)testDisconnectNoCallback_noTokens {
  731. [[[_authorization expect] andReturn:_authState] authState];
  732. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  733. [[[_tokenResponse expect] andReturn:nil] accessToken];
  734. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  735. [[[_tokenResponse expect] andReturn:nil] refreshToken];
  736. [_signIn disconnectWithCompletion:nil];
  737. XCTAssertFalse([self isFetcherStarted], @"should not fetch");
  738. XCTAssertTrue(_keychainRemoved, @"keychain should be removed");
  739. [_authorization verify];
  740. [_authState verify];
  741. [_tokenResponse verify];
  742. }
  743. - (void)testPresentingViewControllerException {
  744. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  745. _presentingViewController = nil;
  746. #elif TARGET_OS_OSX
  747. _presentingWindow = nil;
  748. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  749. XCTAssertThrows([_signIn signInWithConfiguration:_configuration
  750. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  751. presentingViewController:_presentingViewController
  752. #elif TARGET_OS_OSX
  753. presentingWindow:_presentingWindow
  754. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  755. hint:_hint
  756. completion:_completion]);
  757. }
  758. - (void)testClientIDMissingException {
  759. #pragma GCC diagnostic push
  760. #pragma GCC diagnostic ignored "-Wnonnull"
  761. GIDConfiguration *configuration = [[GIDConfiguration alloc] initWithClientID:nil];
  762. #pragma GCC diagnostic pop
  763. BOOL threw = NO;
  764. @try {
  765. [_signIn signInWithConfiguration:configuration
  766. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  767. presentingViewController:_presentingViewController
  768. #elif TARGET_OS_OSX
  769. presentingWindow:_presentingWindow
  770. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  771. completion:nil];
  772. } @catch (NSException *exception) {
  773. threw = YES;
  774. XCTAssertEqualObjects(exception.description,
  775. @"You must specify |clientID| in |GIDConfiguration|");
  776. } @finally {
  777. }
  778. XCTAssert(threw);
  779. }
  780. - (void)testSchemesNotSupportedException {
  781. [_fakeMainBundle fakeMissingAllSchemes];
  782. BOOL threw = NO;
  783. @try {
  784. [_signIn signInWithConfiguration:_configuration
  785. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  786. presentingViewController:_presentingViewController
  787. #elif TARGET_OS_OSX
  788. presentingWindow:_presentingWindow
  789. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  790. hint:_hint
  791. completion:_completion];
  792. } @catch (NSException *exception) {
  793. threw = YES;
  794. XCTAssertEqualObjects(exception.description,
  795. @"Your app is missing support for the following URL schemes: "
  796. "fakeclientid");
  797. } @finally {
  798. }
  799. XCTAssert(threw);
  800. }
  801. #pragma mark - Restarting Authentication Tests
  802. // Verifies that URL is not handled if there is no pending sign-in
  803. - (void)testRequiringPendingSignIn {
  804. BOOL result = [_signIn handleURL:[NSURL URLWithString:kEMMRestartAuthURL]];
  805. XCTAssertFalse(result);
  806. }
  807. #pragma mark - EMM tests
  808. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  809. - (void)testEmmSupportRequestParameters {
  810. [self OAuthLoginWithAddScopesFlow:NO
  811. authError:nil
  812. tokenError:nil
  813. emmPasscodeInfoRequired:NO
  814. keychainError:NO
  815. restoredSignIn:NO
  816. oldAccessToken:NO
  817. modalCancel:NO];
  818. NSString *systemName = [UIDevice currentDevice].systemName;
  819. if ([systemName isEqualToString:@"iPhone OS"]) {
  820. systemName = @"iOS";
  821. }
  822. NSString *expectedOSVersion = [NSString stringWithFormat:@"%@ %@",
  823. systemName, [UIDevice currentDevice].systemVersion];
  824. NSDictionary<NSString *, NSObject *> *authParams =
  825. _savedAuthorizationRequest.additionalParameters;
  826. NSDictionary<NSString *, NSString *> *tokenParams = _savedTokenRequest.additionalParameters;
  827. if (_isEligibleForEMM) {
  828. XCTAssertEqualObjects(authParams[@"emm_support"], kEMMSupport,
  829. @"EMM support should match in auth request");
  830. XCTAssertEqualObjects(authParams[@"device_os"], expectedOSVersion,
  831. @"OS version should match in auth request");
  832. XCTAssertEqualObjects(tokenParams[@"emm_support"], kEMMSupport,
  833. @"EMM support should match in token request");
  834. XCTAssertEqualObjects(tokenParams[@"device_os"],
  835. expectedOSVersion,
  836. @"OS version should match in token request");
  837. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  838. @"no passcode info should be in token request");
  839. } else {
  840. XCTAssertNil(authParams[@"emm_support"],
  841. @"EMM support should not be in auth request for unsupported OS");
  842. XCTAssertNil(authParams[@"device_os"],
  843. @"OS version should not be in auth request for unsupported OS");
  844. XCTAssertNil(tokenParams[@"emm_support"],
  845. @"EMM support should not be in token request for unsupported OS");
  846. XCTAssertNil(tokenParams[@"device_os"],
  847. @"OS version should not be in token request for unsupported OS");
  848. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  849. @"passcode info should not be in token request for unsupported OS");
  850. }
  851. }
  852. - (void)testEmmPasscodeInfo {
  853. [self OAuthLoginWithAddScopesFlow:NO
  854. authError:nil
  855. tokenError:nil
  856. emmPasscodeInfoRequired:YES
  857. keychainError:NO
  858. restoredSignIn:NO
  859. oldAccessToken:NO
  860. modalCancel:NO];
  861. NSDictionary<NSString *, NSString *> *tokenParams = _savedTokenRequest.additionalParameters;
  862. if (_isEligibleForEMM) {
  863. XCTAssertNotNil(tokenParams[@"emm_passcode_info"],
  864. @"passcode info should be in token request");
  865. } else {
  866. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  867. @"passcode info should not be in token request for unsupported OS");
  868. }
  869. }
  870. - (void)testAuthEndpointEMMError {
  871. if (!_isEligibleForEMM) {
  872. return;
  873. }
  874. id mockEMMErrorHandler = OCMStrictClassMock([GIDEMMErrorHandler class]);
  875. [[[mockEMMErrorHandler stub] andReturn:mockEMMErrorHandler] sharedInstance];
  876. __block void (^completion)(void);
  877. NSDictionary<NSString *, NSString *> *callbackParams = @{ @"error" : @"EMM Specific Error" };
  878. [[[mockEMMErrorHandler expect] andReturnValue:@YES]
  879. handleErrorFromResponse:callbackParams completion:SAVE_TO_ARG_BLOCK(completion)];
  880. [self OAuthLoginWithAddScopesFlow:NO
  881. authError:callbackParams[@"error"]
  882. tokenError:nil
  883. emmPasscodeInfoRequired:NO
  884. keychainError:NO
  885. restoredSignIn:NO
  886. oldAccessToken:NO
  887. modalCancel:NO];
  888. [mockEMMErrorHandler verify];
  889. [mockEMMErrorHandler stopMocking];
  890. completion();
  891. [self waitForExpectationsWithTimeout:1 handler:nil];
  892. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  893. XCTAssertTrue(_completionCalled, @"should call delegate");
  894. XCTAssertNotNil(_authError, @"should have error");
  895. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  896. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  897. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  898. }
  899. - (void)testTokenEndpointEMMError {
  900. if (!_isEligibleForEMM) {
  901. return;
  902. }
  903. __block void (^completion)(NSError *);
  904. NSDictionary *errorJSON = @{ @"error" : @"EMM Specific Error" };
  905. NSError *emmError = [NSError errorWithDomain:@"anydomain"
  906. code:12345
  907. userInfo:@{ OIDOAuthErrorFieldError : errorJSON }];
  908. [[_authentication expect] handleTokenFetchEMMError:emmError
  909. completion:SAVE_TO_ARG_BLOCK(completion)];
  910. [self OAuthLoginWithAddScopesFlow:NO
  911. authError:nil
  912. tokenError:emmError
  913. emmPasscodeInfoRequired:NO
  914. keychainError:NO
  915. restoredSignIn:NO
  916. oldAccessToken:NO
  917. modalCancel:NO];
  918. NSError *handledError = [NSError errorWithDomain:kGIDSignInErrorDomain
  919. code:kGIDSignInErrorCodeEMM
  920. userInfo:emmError.userInfo];
  921. completion(handledError);
  922. [self waitForExpectationsWithTimeout:1 handler:nil];
  923. [_authentication verify];
  924. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  925. XCTAssertTrue(_completionCalled, @"should call delegate");
  926. XCTAssertNotNil(_authError, @"should have error");
  927. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  928. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  929. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  930. }
  931. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  932. #pragma mark - Helpers
  933. // Whether or not a fetcher has been started.
  934. - (BOOL)isFetcherStarted {
  935. NSUInteger count = _fetcherService.fetchers.count;
  936. XCTAssertTrue(count <= 1, @"Only one fetcher is supported");
  937. return !!count;
  938. }
  939. // Gets the URL being fetched.
  940. - (NSURL *)fetchedURL {
  941. return [_fetcherService.fetchers[0] requestURL];
  942. }
  943. // Emulates server returning the data as in JSON.
  944. - (void)didFetch:(id)dataObject error:(NSError *)error {
  945. NSData *data = nil;
  946. if (dataObject) {
  947. NSError *jsonError = nil;
  948. data = [NSJSONSerialization dataWithJSONObject:dataObject
  949. options:0
  950. error:&jsonError];
  951. XCTAssertNil(jsonError, @"must provide valid data");
  952. }
  953. [_fetcherService.fetchers[0] didFinishWithData:data error:error];
  954. }
  955. - (NSError *)error {
  956. return [NSError errorWithDomain:kErrorDomain code:kErrorCode userInfo:nil];
  957. }
  958. // Verifies a fetcher has started for revoking token and emulates a server response.
  959. - (void)verifyAndRevokeToken:(NSString *)token hasCallback:(BOOL)hasCallback {
  960. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  961. NSURL *url = [self fetchedURL];
  962. XCTAssertEqualObjects([url scheme], @"https", @"scheme must match");
  963. XCTAssertEqualObjects([url host], @"accounts.google.com", @"host must match");
  964. XCTAssertEqualObjects([url path], @"/o/oauth2/revoke", @"path must match");
  965. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  966. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  967. XCTAssertEqualObjects([params valueForKey:@"token"], token,
  968. @"token parameter should match");
  969. XCTAssertEqualObjects([params valueForKey:kSDKVersionLoggingParameter], GIDVersion(),
  970. @"SDK version logging parameter should match");
  971. XCTAssertEqualObjects([params valueForKey:kEnvironmentLoggingParameter], GIDEnvironment(),
  972. @"Environment logging parameter should match");
  973. // Emulate result back from server.
  974. [self didFetch:nil error:nil];
  975. if (hasCallback) {
  976. [self waitForExpectationsWithTimeout:1 handler:nil];
  977. }
  978. XCTAssertTrue(_keychainRemoved, @"should clear saved keychain name");
  979. }
  980. - (void)OAuthLoginWithAddScopesFlow:(BOOL)addScopesFlow
  981. authError:(NSString *)authError
  982. tokenError:(NSError *)tokenError
  983. emmPasscodeInfoRequired:(BOOL)emmPasscodeInfoRequired
  984. keychainError:(BOOL)keychainError
  985. restoredSignIn:(BOOL)restoredSignIn
  986. oldAccessToken:(BOOL)oldAccessToken
  987. modalCancel:(BOOL)modalCancel {
  988. [self OAuthLoginWithAddScopesFlow:addScopesFlow
  989. authError:authError
  990. tokenError:tokenError
  991. emmPasscodeInfoRequired:emmPasscodeInfoRequired
  992. keychainError:keychainError
  993. restoredSignIn:restoredSignIn
  994. oldAccessToken:oldAccessToken
  995. modalCancel:modalCancel
  996. useAdditionalScopes:NO
  997. additionalScopes:nil];
  998. }
  999. // The authorization flow with parameters to control which branches to take.
  1000. - (void)OAuthLoginWithAddScopesFlow:(BOOL)addScopesFlow
  1001. authError:(NSString *)authError
  1002. tokenError:(NSError *)tokenError
  1003. emmPasscodeInfoRequired:(BOOL)emmPasscodeInfoRequired
  1004. keychainError:(BOOL)keychainError
  1005. restoredSignIn:(BOOL)restoredSignIn
  1006. oldAccessToken:(BOOL)oldAccessToken
  1007. modalCancel:(BOOL)modalCancel
  1008. useAdditionalScopes:(BOOL)useAdditionalScopes
  1009. additionalScopes:(NSArray *)additionalScopes {
  1010. if (restoredSignIn) {
  1011. // clearAndAuthenticateWithOptions
  1012. [[[_authorization expect] andReturn:_authState] authState];
  1013. BOOL isAuthorized = restoredSignIn ? YES : NO;
  1014. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:isAuthorized]] isAuthorized];
  1015. }
  1016. NSDictionary<NSString *, NSString *> *additionalParameters = emmPasscodeInfoRequired ?
  1017. @{ @"emm_passcode_info_required" : @"1" } : nil;
  1018. OIDAuthorizationResponse *authResponse =
  1019. [OIDAuthorizationResponse testInstanceWithAdditionalParameters:additionalParameters
  1020. errorString:authError];
  1021. OIDTokenResponse *tokenResponse =
  1022. [OIDTokenResponse testInstanceWithIDToken:[OIDTokenResponse fatIDToken]
  1023. accessToken:restoredSignIn ? kAccessToken : nil
  1024. expiresIn:oldAccessToken ? @(300) : nil
  1025. tokenRequest:nil];
  1026. OIDTokenRequest *tokenRequest = [[OIDTokenRequest alloc]
  1027. initWithConfiguration:authResponse.request.configuration
  1028. grantType:OIDGrantTypeRefreshToken
  1029. authorizationCode:nil
  1030. redirectURL:nil
  1031. clientID:authResponse.request.clientID
  1032. clientSecret:authResponse.request.clientSecret
  1033. scope:nil
  1034. refreshToken:kRefreshToken
  1035. codeVerifier:nil
  1036. additionalParameters:tokenResponse.request.additionalParameters];
  1037. if (restoredSignIn) {
  1038. // maybeFetchToken
  1039. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1040. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1041. if (oldAccessToken) {
  1042. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1043. // Corresponds to EMM support
  1044. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1045. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1046. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1047. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1048. [[[_authState expect] andReturn:tokenRequest]
  1049. tokenRefreshRequestWithAdditionalParameters:[OCMArg any]];
  1050. }
  1051. } else {
  1052. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback called"];
  1053. void (^completion)(GIDUserAuth *_Nullable userAuth, NSError *_Nullable error) =
  1054. ^(GIDUserAuth *_Nullable userAuth, NSError * _Nullable error) {
  1055. [expectation fulfill];
  1056. if (userAuth) {
  1057. XCTAssertEqualObjects(userAuth.serverAuthCode, kServerAuthCode);
  1058. } else {
  1059. XCTAssertNotNil(error, @"Should have an error if the userAuth is nil");
  1060. }
  1061. XCTAssertFalse(self->_completionCalled, @"callback already called");
  1062. self->_completionCalled = YES;
  1063. self->_authError = error;
  1064. };
  1065. if (addScopesFlow) {
  1066. [_signIn addScopes:@[kNewScope]
  1067. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1068. presentingViewController:_presentingViewController
  1069. #elif TARGET_OS_OSX
  1070. presentingWindow:_presentingWindow
  1071. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1072. completion:completion];
  1073. } else {
  1074. if (useAdditionalScopes) {
  1075. [_signIn signInWithConfiguration:_configuration
  1076. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1077. presentingViewController:_presentingViewController
  1078. #elif TARGET_OS_OSX
  1079. presentingWindow:_presentingWindow
  1080. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1081. hint:_hint
  1082. additionalScopes:additionalScopes
  1083. completion:completion];
  1084. } else {
  1085. [_signIn signInWithConfiguration:_configuration
  1086. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1087. presentingViewController:_presentingViewController
  1088. #elif TARGET_OS_OSX
  1089. presentingWindow:_presentingWindow
  1090. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1091. hint:_hint
  1092. completion:completion];
  1093. }
  1094. }
  1095. [_authorization verify];
  1096. [_authState verify];
  1097. XCTAssertNotNil(_savedAuthorizationRequest);
  1098. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  1099. XCTAssertEqualObjects(params[@"include_granted_scopes"], @"true");
  1100. XCTAssertEqualObjects(params[kSDKVersionLoggingParameter], GIDVersion());
  1101. XCTAssertEqualObjects(params[kEnvironmentLoggingParameter], GIDEnvironment());
  1102. XCTAssertNotNil(_savedAuthorizationCallback);
  1103. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1104. XCTAssertEqual(_savedPresentingViewController, _presentingViewController);
  1105. #elif TARGET_OS_OSX
  1106. XCTAssertEqual(_savedPresentingWindow, _presentingWindow);
  1107. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1108. // maybeFetchToken
  1109. if (!(authError || modalCancel)) {
  1110. [[[_authState expect] andReturn:nil] lastTokenResponse];
  1111. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1112. // Corresponds to EMM support
  1113. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1114. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1115. [[[_authState expect] andReturn:nil] lastTokenResponse];
  1116. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1117. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1118. }
  1119. // Simulate auth endpoint response
  1120. if (modalCancel) {
  1121. NSError *error = [NSError errorWithDomain:OIDGeneralErrorDomain
  1122. code:OIDErrorCodeUserCanceledAuthorizationFlow
  1123. userInfo:nil];
  1124. _savedAuthorizationCallback(nil, error);
  1125. } else {
  1126. _savedAuthorizationCallback(authResponse, nil);
  1127. }
  1128. if (authError || modalCancel) {
  1129. return;
  1130. }
  1131. [_authState verify];
  1132. }
  1133. if (restoredSignIn && oldAccessToken) {
  1134. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  1135. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
  1136. NSError * _Nullable error) {
  1137. [expectation fulfill];
  1138. XCTAssertNil(error, @"should have no error");
  1139. }];
  1140. }
  1141. if (!restoredSignIn || (restoredSignIn && oldAccessToken)) {
  1142. XCTAssertNotNil(_savedTokenRequest);
  1143. XCTAssertNotNil(_savedTokenCallback);
  1144. // OIDTokenCallback
  1145. if (tokenError) {
  1146. [[_authState expect] updateWithTokenResponse:nil error:tokenError];
  1147. } else {
  1148. [[_authState expect] updateWithTokenResponse:[OCMArg any] error:nil];
  1149. }
  1150. }
  1151. if (tokenError) {
  1152. _savedTokenCallback(nil, tokenError);
  1153. return;
  1154. }
  1155. // DecodeIdTokenCallback
  1156. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1157. // SaveAuthCallback
  1158. __block OIDAuthState *authState;
  1159. __block GIDProfileData *profileData;
  1160. if (keychainError) {
  1161. _saveAuthorizationReturnValue = NO;
  1162. } else {
  1163. if (addScopesFlow) {
  1164. [[_user expect] updateAuthState:SAVE_TO_ARG_BLOCK(authState)
  1165. profileData:SAVE_TO_ARG_BLOCK(profileData)];
  1166. } else {
  1167. [[[_user stub] andReturn:_user] alloc];
  1168. (void)[[[_user expect] andReturn:_user] initWithAuthState:SAVE_TO_ARG_BLOCK(authState)
  1169. profileData:SAVE_TO_ARG_BLOCK(profileData)];
  1170. }
  1171. }
  1172. // CompletionCallback - mock server auth code parsing
  1173. if (!keychainError) {
  1174. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1175. }
  1176. if (restoredSignIn && !oldAccessToken) {
  1177. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  1178. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
  1179. NSError * _Nullable error) {
  1180. [expectation fulfill];
  1181. XCTAssertNil(error, @"should have no error");
  1182. }];
  1183. } else {
  1184. // Simulate token endpoint response.
  1185. _savedTokenCallback(tokenResponse, nil);
  1186. }
  1187. if (keychainError) {
  1188. return;
  1189. }
  1190. [self waitForExpectationsWithTimeout:1 handler:nil];
  1191. [_authState verify];
  1192. XCTAssertTrue(_keychainSaved, @"should save to keychain");
  1193. XCTAssertNotNil(authState);
  1194. // Check fat ID token decoding
  1195. XCTAssertEqualObjects(profileData.name, kFatName);
  1196. XCTAssertEqualObjects(profileData.givenName, kFatGivenName);
  1197. XCTAssertEqualObjects(profileData.familyName, kFatFamilyName);
  1198. XCTAssertTrue(profileData.hasImage);
  1199. // If attempt to authenticate again, will reuse existing auth object.
  1200. _completionCalled = NO;
  1201. _keychainRemoved = NO;
  1202. _keychainSaved = NO;
  1203. _authError = nil;
  1204. if (!addScopesFlow) {
  1205. [[[_user expect] andReturn:_authentication] authentication];
  1206. [[[_user expect] andReturn:_authentication] authentication];
  1207. }
  1208. __block GIDAuthenticationCompletion completion;
  1209. [[_authentication expect] doWithFreshTokens:SAVE_TO_ARG_BLOCK(completion)];
  1210. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  1211. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
  1212. NSError * _Nullable error) {
  1213. [expectation fulfill];
  1214. XCTAssertNil(error, @"should have no error");
  1215. }];
  1216. completion(_authentication, nil);
  1217. [self waitForExpectationsWithTimeout:1 handler:nil];
  1218. XCTAssertFalse(_keychainRemoved, @"should not remove keychain");
  1219. XCTAssertFalse(_keychainSaved, @"should not save to keychain again");
  1220. if (restoredSignIn) {
  1221. OCMVerify([_authorization authorizationFromKeychainForName:kKeychainName
  1222. useDataProtectionKeychain:YES]);
  1223. OCMVerify([_authorization saveAuthorization:OCMOCK_ANY
  1224. toKeychainForName:kKeychainName
  1225. useDataProtectionKeychain:YES]);
  1226. }
  1227. }
  1228. #pragma mark - Key Value Observing
  1229. - (void)observeValueForKeyPath:(NSString *)keyPath
  1230. ofObject:(id)object
  1231. change:(NSDictionary<NSKeyValueChangeKey, id> *)change
  1232. context:(void *)context {
  1233. if (context == kTestObserverContext && object == _signIn) {
  1234. [_changedKeyPaths addObject:keyPath];
  1235. }
  1236. }
  1237. @end