GIDSignInTest.m 65 KB

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