GIDSignInTest.m 67 KB

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