GIDSignInTest.m 73 KB

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