GIDSignInTest.m 56 KB

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