GIDSignInTest.m 58 KB

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