AuthTests.swift 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456
  1. // Copyright 2023 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 Foundation
  15. import XCTest
  16. @testable import FirebaseAuth
  17. import FirebaseAuthInterop
  18. import FirebaseCore
  19. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  20. class AuthTests: RPCBaseTests {
  21. static let kAccessToken = "TEST_ACCESS_TOKEN"
  22. static let kNewAccessToken = "NEW_ACCESS_TOKEN"
  23. static let kFakeAPIKey = "FAKE_API_KEY"
  24. static let kFakeRecaptchaResponse = "RecaptchaResponse"
  25. static let kFakeRecaptchaVersion = "RecaptchaVersion"
  26. var auth: Auth!
  27. static var testNum = 0
  28. var authDispatcherCallback: (() -> Void)?
  29. override func setUp() {
  30. super.setUp()
  31. let options = FirebaseOptions(googleAppID: "0:0000000000000:ios:0000000000000000",
  32. gcmSenderID: "00000000000000000-00000000000-000000000")
  33. options.apiKey = AuthTests.kFakeAPIKey
  34. options.projectID = "myProjectID"
  35. let name = "test-AuthTests\(AuthTests.testNum)"
  36. AuthTests.testNum = AuthTests.testNum + 1
  37. FirebaseApp.configure(name: name, options: options)
  38. #if (os(macOS) && !FIREBASE_AUTH_TESTING_USE_MACOS_KEYCHAIN) || SWIFT_PACKAGE
  39. let keychainStorageProvider = FakeAuthKeychainStorage()
  40. #else
  41. let keychainStorageProvider = AuthKeychainStorageReal()
  42. #endif // (os(macOS) && !FIREBASE_AUTH_TESTING_USE_MACOS_KEYCHAIN) || SWIFT_PACKAGE
  43. auth = Auth(
  44. app: FirebaseApp.app(name: name)!,
  45. keychainStorageProvider: keychainStorageProvider
  46. )
  47. // Set authDispatcherCallback implementation in order to save the token refresh task for later
  48. // execution.
  49. AuthDispatcher.shared.dispatchAfterImplementation = { delay, queue, task in
  50. XCTAssertNotNil(task)
  51. XCTAssertGreaterThan(delay, 0)
  52. XCTAssertEqual(kAuthGlobalWorkQueue, queue)
  53. self.authDispatcherCallback = task
  54. }
  55. // Wait until Auth initialization completes
  56. waitForAuthGlobalWorkQueueDrain()
  57. }
  58. private func waitForAuthGlobalWorkQueueDrain() {
  59. let workerSemaphore = DispatchSemaphore(value: 0)
  60. kAuthGlobalWorkQueue.async {
  61. workerSemaphore.signal()
  62. }
  63. _ = workerSemaphore.wait(timeout: DispatchTime.distantFuture)
  64. }
  65. /** @fn testFetchSignInMethodsForEmailSuccess
  66. @brief Tests the flow of a successful @c fetchSignInMethodsForEmail:completion: call.
  67. */
  68. func testFetchSignInMethodsForEmailSuccess() throws {
  69. let allSignInMethods = ["emailLink", "facebook.com"]
  70. let expectation = self.expectation(description: #function)
  71. rpcIssuer.respondBlock = {
  72. let request = try XCTUnwrap(self.rpcIssuer.request as? CreateAuthURIRequest)
  73. XCTAssertEqual(request.identifier, self.kEmail)
  74. XCTAssertEqual(request.endpoint, "createAuthUri")
  75. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  76. try self.rpcIssuer.respond(withJSON: ["signinMethods": allSignInMethods])
  77. }
  78. auth?.fetchSignInMethods(forEmail: kEmail) { signInMethods, error in
  79. // 4. After the response triggers the callback, verify the returned signInMethods.
  80. XCTAssertTrue(Thread.isMainThread)
  81. XCTAssertEqual(signInMethods, allSignInMethods)
  82. XCTAssertNil(error)
  83. expectation.fulfill()
  84. }
  85. waitForExpectations(timeout: 5)
  86. }
  87. /** @fn testFetchSignInMethodsForEmailFailure
  88. @brief Tests the flow of a failed @c fetchSignInMethodsForEmail:completion: call.
  89. */
  90. func testFetchSignInMethodsForEmailFailure() throws {
  91. let expectation = self.expectation(description: #function)
  92. rpcIssuer.respondBlock = {
  93. let message = "TOO_MANY_ATTEMPTS_TRY_LATER"
  94. try self.rpcIssuer.respond(serverErrorMessage: message)
  95. }
  96. auth?.fetchSignInMethods(forEmail: kEmail) { signInMethods, error in
  97. XCTAssertTrue(Thread.isMainThread)
  98. XCTAssertNil(signInMethods)
  99. let rpcError = (error as? NSError)!
  100. XCTAssertEqual(rpcError.code, AuthErrorCode.tooManyRequests.rawValue)
  101. expectation.fulfill()
  102. }
  103. waitForExpectations(timeout: 5)
  104. }
  105. #if os(iOS)
  106. /** @fn testPhoneAuthSuccess
  107. @brief Tests the flow of a successful @c signInWithCredential:completion for phone auth.
  108. */
  109. func testPhoneAuthSuccess() throws {
  110. let kVerificationID = "55432"
  111. let kVerificationCode = "12345678"
  112. let expectation = self.expectation(description: #function)
  113. setFakeGetAccountProvider()
  114. setFakeSecureTokenService()
  115. // 1. Setup respond block to test and fake send request.
  116. rpcIssuer.respondBlock = {
  117. // 2. Validate the created Request instance.
  118. let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyPhoneNumberRequest)
  119. XCTAssertEqual(request.verificationCode, kVerificationCode)
  120. XCTAssertEqual(request.verificationID, kVerificationID)
  121. // 3. Send the response from the fake backend.
  122. try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken,
  123. "isNewUser": true,
  124. "refreshToken": self.kRefreshToken])
  125. }
  126. try auth?.signOut()
  127. let credential = PhoneAuthProvider.provider(auth: auth)
  128. .credential(withVerificationID: kVerificationID,
  129. verificationCode: kVerificationCode)
  130. auth?.signIn(with: credential) { authResult, error in
  131. // 4. After the response triggers the callback, verify the returned result.
  132. XCTAssertTrue(Thread.isMainThread)
  133. guard let user = authResult?.user,
  134. let additionalUserInfo = authResult?.additionalUserInfo else {
  135. XCTFail("authResult.user or additionalUserInfo is missing")
  136. return
  137. }
  138. XCTAssertEqual(user.refreshToken, self.kRefreshToken)
  139. XCTAssertFalse(user.isAnonymous)
  140. XCTAssertTrue(additionalUserInfo.isNewUser)
  141. XCTAssertNil(error)
  142. expectation.fulfill()
  143. }
  144. waitForExpectations(timeout: 5)
  145. assertUser(auth?.currentUser)
  146. }
  147. /** @fn testPhoneAuthMissingVerificationCode
  148. @brief Tests the flow of an unsuccessful @c signInWithCredential:completion for phone auth due
  149. to an empty verification code
  150. */
  151. func testPhoneAuthMissingVerificationCode() throws {
  152. let kVerificationID = "55432"
  153. let kVerificationCode = ""
  154. let expectation = self.expectation(description: #function)
  155. setFakeGetAccountProvider()
  156. setFakeSecureTokenService()
  157. try auth?.signOut()
  158. let credential = PhoneAuthProvider.provider(auth: auth)
  159. .credential(withVerificationID: kVerificationID,
  160. verificationCode: kVerificationCode)
  161. auth?.signIn(with: credential) { authResult, error in
  162. XCTAssertTrue(Thread.isMainThread)
  163. XCTAssertNil(authResult)
  164. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.missingVerificationCode.rawValue)
  165. expectation.fulfill()
  166. }
  167. waitForExpectations(timeout: 5)
  168. }
  169. /** @fn testPhoneAuthMissingVerificationID
  170. @brief Tests the flow of an unsuccessful @c signInWithCredential:completion for phone auth due
  171. to an empty verification ID.
  172. */
  173. func testPhoneAuthMissingVerificationID() throws {
  174. let kVerificationID = ""
  175. let kVerificationCode = "123"
  176. let expectation = self.expectation(description: #function)
  177. setFakeGetAccountProvider()
  178. setFakeSecureTokenService()
  179. try auth?.signOut()
  180. let credential = PhoneAuthProvider.provider(auth: auth)
  181. .credential(withVerificationID: kVerificationID,
  182. verificationCode: kVerificationCode)
  183. auth?.signIn(with: credential) { authResult, error in
  184. XCTAssertTrue(Thread.isMainThread)
  185. XCTAssertNil(authResult)
  186. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.missingVerificationID.rawValue)
  187. expectation.fulfill()
  188. }
  189. waitForExpectations(timeout: 5)
  190. }
  191. #endif
  192. /** @fn testSignInWithEmailLinkSuccess
  193. @brief Tests the flow of a successful @c signInWithEmail:link:completion: call.
  194. */
  195. func testSignInWithEmailLinkSuccess() throws {
  196. try signInWithEmailLinkSuccessWithLinkOrDeeplink(link: kFakeEmailSignInLink)
  197. }
  198. /** @fn testSignInWithEmailLinkSuccessDeeplink
  199. @brief Tests the flow of a successful @c signInWithEmail:link: call using a deep link.
  200. */
  201. func testSignInWithEmailLinkSuccessDeeplink() throws {
  202. try signInWithEmailLinkSuccessWithLinkOrDeeplink(link: kFakeEmailSignInDeeplink)
  203. }
  204. private func signInWithEmailLinkSuccessWithLinkOrDeeplink(link: String) throws {
  205. let fakeCode = "testoobcode"
  206. let expectation = self.expectation(description: #function)
  207. setFakeGetAccountProvider()
  208. setFakeSecureTokenService()
  209. // 1. Setup respond block to test and fake send request.
  210. rpcIssuer.respondBlock = {
  211. // 2. Validate the created Request instance.
  212. let request = try XCTUnwrap(self.rpcIssuer.request as? EmailLinkSignInRequest)
  213. XCTAssertEqual(request.email, self.kEmail)
  214. XCTAssertEqual(request.oobCode, fakeCode)
  215. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  216. try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken,
  217. "email": self.kEmail,
  218. "isNewUser": true,
  219. "refreshToken": self.kRefreshToken])
  220. }
  221. try auth?.signOut()
  222. auth?.signIn(withEmail: kEmail, link: link) { authResult, error in
  223. // 4. After the response triggers the callback, verify the returned result.
  224. XCTAssertTrue(Thread.isMainThread)
  225. guard let user = authResult?.user else {
  226. XCTFail("authResult.user is missing")
  227. return
  228. }
  229. XCTAssertEqual(user.refreshToken, self.kRefreshToken)
  230. XCTAssertFalse(user.isAnonymous)
  231. XCTAssertEqual(user.email, self.kEmail)
  232. XCTAssertNil(error)
  233. expectation.fulfill()
  234. }
  235. waitForExpectations(timeout: 5)
  236. assertUser(auth?.currentUser)
  237. }
  238. /** @fn testSignInWithEmailLinkFailure
  239. @brief Tests the flow of a failed @c signInWithEmail:link:completion: call.
  240. */
  241. func testSignInWithEmailLinkFailure() throws {
  242. let expectation = self.expectation(description: #function)
  243. // 1. Setup respond block to test and fake send request.
  244. rpcIssuer.respondBlock = {
  245. // 2. Send the response from the fake backend.
  246. try self.rpcIssuer.respond(serverErrorMessage: "INVALID_OOB_CODE")
  247. }
  248. try auth?.signOut()
  249. auth?.signIn(withEmail: kEmail, link: kFakeEmailSignInLink) { authResult, error in
  250. // 3. After the response triggers the callback, verify the returned result.
  251. XCTAssertTrue(Thread.isMainThread)
  252. XCTAssertNil(authResult)
  253. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.invalidActionCode.rawValue)
  254. expectation.fulfill()
  255. }
  256. waitForExpectations(timeout: 5)
  257. XCTAssertNil(auth?.currentUser)
  258. }
  259. #if os(iOS)
  260. /** @fn testSignInWithEmailPasswordWithRecaptchaSuccess
  261. @brief Tests the flow of a successful @c signInWithEmail:password:completion: call.
  262. */
  263. func testSignInWithEmailPasswordWithRecaptchaSuccess() throws {
  264. let kRefreshToken = "fakeRefreshToken"
  265. let expectation = self.expectation(description: #function)
  266. setFakeGetAccountProvider()
  267. setFakeSecureTokenService()
  268. // 1. Setup respond block to test and fake send request.
  269. rpcIssuer.respondBlock = {
  270. // 2. Validate the created Request instance.
  271. let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyPasswordRequest)
  272. XCTAssertEqual(request.email, self.kEmail)
  273. XCTAssertEqual(request.password, self.kFakePassword)
  274. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  275. XCTAssertTrue(request.returnSecureToken)
  276. request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
  277. recaptchaVersion: AuthTests.kFakeRecaptchaVersion)
  278. // 3. Send the response from the fake backend.
  279. try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken,
  280. "email": self.kEmail,
  281. "isNewUser": true,
  282. "refreshToken": kRefreshToken])
  283. }
  284. try auth?.signOut()
  285. auth?.signIn(withEmail: kEmail, password: kFakePassword) { authResult, error in
  286. // 4. After the response triggers the callback, verify the returned result.
  287. XCTAssertTrue(Thread.isMainThread)
  288. guard let user = authResult?.user else {
  289. XCTFail("authResult.user is missing")
  290. return
  291. }
  292. XCTAssertEqual(user.refreshToken, kRefreshToken)
  293. XCTAssertFalse(user.isAnonymous)
  294. XCTAssertEqual(user.email, self.kEmail)
  295. guard let additionalUserInfo = authResult?.additionalUserInfo else {
  296. XCTFail("authResult.additionalUserInfo is missing")
  297. return
  298. }
  299. XCTAssertFalse(additionalUserInfo.isNewUser)
  300. XCTAssertEqual(additionalUserInfo.providerID, EmailAuthProvider.id)
  301. XCTAssertNil(error)
  302. expectation.fulfill()
  303. }
  304. waitForExpectations(timeout: 5)
  305. assertUser(auth?.currentUser)
  306. }
  307. /** @fn testSignInWithEmailPasswordWithRecaptchaFallbackSuccess
  308. @brief Tests the flow of a successful @c signInWithEmail:password:completion: call.
  309. */
  310. func testSignInWithEmailPasswordWithRecaptchaFallbackSuccess() throws {
  311. let kRefreshToken = "fakeRefreshToken"
  312. let expectation = self.expectation(description: #function)
  313. setFakeGetAccountProvider()
  314. setFakeSecureTokenService()
  315. let kTestRecaptchaKey = "projects/123/keys/456"
  316. rpcIssuer.recaptchaSiteKey = kTestRecaptchaKey
  317. // 1. Setup respond block to test and fake send request.
  318. rpcIssuer.respondBlock = {
  319. // 2. Validate the created Request instance.
  320. let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyPasswordRequest)
  321. XCTAssertEqual(request.email, self.kEmail)
  322. XCTAssertEqual(request.password, self.kFakePassword)
  323. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  324. XCTAssertTrue(request.returnSecureToken)
  325. request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
  326. recaptchaVersion: AuthTests.kFakeRecaptchaVersion)
  327. // 3. Send the response from the fake backend.
  328. try self.rpcIssuer.respond(serverErrorMessage: "MISSING_RECAPTCHA_TOKEN")
  329. }
  330. rpcIssuer.nextRespondBlock = {
  331. // 4. Validate again the created Request instance after the recaptcha retry.
  332. let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyPasswordRequest)
  333. XCTAssertEqual(request.email, self.kEmail)
  334. XCTAssertEqual(request.password, self.kFakePassword)
  335. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  336. XCTAssertTrue(request.returnSecureToken)
  337. request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
  338. recaptchaVersion: AuthTests.kFakeRecaptchaVersion)
  339. // 5. Send the response from the fake backend.
  340. try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken,
  341. "email": self.kEmail,
  342. "isNewUser": true,
  343. "refreshToken": kRefreshToken])
  344. }
  345. try auth?.signOut()
  346. auth?.signIn(withEmail: kEmail, password: kFakePassword) { authResult, error in
  347. // 6. After the response triggers the callback, verify the returned result.
  348. XCTAssertTrue(Thread.isMainThread)
  349. XCTAssertNil(error)
  350. guard let user = authResult?.user else {
  351. XCTFail("authResult.user is missing")
  352. return
  353. }
  354. XCTAssertEqual(user.refreshToken, kRefreshToken)
  355. XCTAssertFalse(user.isAnonymous)
  356. XCTAssertEqual(user.email, self.kEmail)
  357. guard let additionalUserInfo = authResult?.additionalUserInfo else {
  358. XCTFail("authResult.additionalUserInfo is missing")
  359. return
  360. }
  361. XCTAssertFalse(additionalUserInfo.isNewUser)
  362. XCTAssertEqual(additionalUserInfo.providerID, EmailAuthProvider.id)
  363. expectation.fulfill()
  364. }
  365. waitForExpectations(timeout: 5)
  366. assertUser(auth?.currentUser)
  367. }
  368. #endif
  369. /** @fn testSignInAndRetrieveDataWithEmailPasswordSuccess
  370. @brief Tests the flow of a successful @c signInAndRetrieveDataWithEmail:password:completion:
  371. call. Superset of historical testSignInWithEmailPasswordSuccess.
  372. */
  373. func testSignInAndRetrieveDataWithEmailPasswordSuccess() throws {
  374. let kRefreshToken = "fakeRefreshToken"
  375. let expectation = self.expectation(description: #function)
  376. setFakeGetAccountProvider()
  377. setFakeSecureTokenService()
  378. // 1. Setup respond block to test and fake send request.
  379. rpcIssuer.respondBlock = {
  380. // 2. Validate the created Request instance.
  381. let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyPasswordRequest)
  382. XCTAssertEqual(request.email, self.kEmail)
  383. XCTAssertEqual(request.password, self.kFakePassword)
  384. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  385. XCTAssertTrue(request.returnSecureToken)
  386. // 3. Send the response from the fake backend.
  387. try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken,
  388. "email": self.kEmail,
  389. "isNewUser": true,
  390. "refreshToken": kRefreshToken])
  391. }
  392. try auth?.signOut()
  393. auth?.signIn(withEmail: kEmail, password: kFakePassword) { authResult, error in
  394. // 4. After the response triggers the callback, verify the returned result.
  395. XCTAssertTrue(Thread.isMainThread)
  396. guard let user = authResult?.user else {
  397. XCTFail("authResult.user is missing")
  398. return
  399. }
  400. XCTAssertEqual(user.refreshToken, kRefreshToken)
  401. XCTAssertFalse(user.isAnonymous)
  402. XCTAssertEqual(user.email, self.kEmail)
  403. guard let additionalUserInfo = authResult?.additionalUserInfo else {
  404. XCTFail("authResult.additionalUserInfo is missing")
  405. return
  406. }
  407. XCTAssertFalse(additionalUserInfo.isNewUser)
  408. XCTAssertEqual(additionalUserInfo.providerID, EmailAuthProvider.id)
  409. XCTAssertNil(error)
  410. expectation.fulfill()
  411. }
  412. waitForExpectations(timeout: 5)
  413. assertUser(auth?.currentUser)
  414. }
  415. /** @fn testSignInWithEmailPasswordFailure
  416. @brief Tests the flow of a failed @c signInWithEmail:password:completion: call.
  417. */
  418. func testSignInWithEmailPasswordFailure() throws {
  419. let expectation = self.expectation(description: #function)
  420. rpcIssuer.respondBlock = {
  421. // 2. Send the response from the fake backend.
  422. try self.rpcIssuer.respond(serverErrorMessage: "INVALID_PASSWORD")
  423. }
  424. try auth?.signOut()
  425. auth?.signIn(withEmail: kEmail, password: kFakePassword) { authResult, error in
  426. // 3. After the response triggers the callback, verify the returned result.
  427. XCTAssertTrue(Thread.isMainThread)
  428. XCTAssertNil(authResult)
  429. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.wrongPassword.rawValue)
  430. XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
  431. expectation.fulfill()
  432. }
  433. waitForExpectations(timeout: 5)
  434. XCTAssertNil(auth?.currentUser)
  435. }
  436. /** @fn testResetPasswordSuccess
  437. @brief Tests the flow of a successful @c confirmPasswordResetWithCode:newPassword:completion:
  438. call.
  439. */
  440. func testResetPasswordSuccess() throws {
  441. let expectation = self.expectation(description: #function)
  442. // 1. Setup respond block to test and fake send request.
  443. rpcIssuer.respondBlock = {
  444. // 2. Validate the created Request instance.
  445. let request = try XCTUnwrap(self.rpcIssuer.request as? ResetPasswordRequest)
  446. XCTAssertEqual(request.oobCode, self.kFakeOobCode)
  447. XCTAssertEqual(request.updatedPassword, self.kFakePassword)
  448. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  449. // 3. Send the response from the fake backend.
  450. try self.rpcIssuer.respond(withJSON: [:])
  451. }
  452. try auth?.signOut()
  453. auth?
  454. .confirmPasswordReset(withCode: kFakeOobCode, newPassword: kFakePassword) { error in
  455. // 4. After the response triggers the callback, verify the returned result.
  456. XCTAssertTrue(Thread.isMainThread)
  457. XCTAssertNil(error)
  458. expectation.fulfill()
  459. }
  460. waitForExpectations(timeout: 5)
  461. }
  462. /** @fn testResetPasswordFailure
  463. @brief Tests the flow of a failed @c confirmPasswordResetWithCode:newPassword:completion:
  464. call.
  465. */
  466. func testResetPasswordFailure() throws {
  467. let expectation = self.expectation(description: #function)
  468. rpcIssuer.respondBlock = {
  469. // 2. Send the response from the fake backend.
  470. try self.rpcIssuer.respond(serverErrorMessage: "INVALID_OOB_CODE")
  471. }
  472. try auth?.signOut()
  473. auth?
  474. .confirmPasswordReset(withCode: kFakeOobCode, newPassword: kFakePassword) { error in
  475. // 3. After the response triggers the callback, verify the returned result.
  476. XCTAssertTrue(Thread.isMainThread)
  477. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.invalidActionCode.rawValue)
  478. XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
  479. expectation.fulfill()
  480. }
  481. waitForExpectations(timeout: 5)
  482. XCTAssertNil(auth?.currentUser)
  483. }
  484. /** @fn testCheckActionCodeSuccess
  485. @brief Tests the flow of a successful @c checkActionCode:completion call.
  486. */
  487. func testCheckActionCodeSuccess() throws {
  488. let kNewEmail = "newEmail@example.com"
  489. let verifyEmailRequestType = "VERIFY_EMAIL"
  490. let expectation = self.expectation(description: #function)
  491. // 1. Setup respond block to test and fake send request.
  492. rpcIssuer.respondBlock = {
  493. // 2. Validate the created Request instance.
  494. let request = try XCTUnwrap(self.rpcIssuer.request as? ResetPasswordRequest)
  495. XCTAssertEqual(request.oobCode, self.kFakeOobCode)
  496. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  497. // 3. Send the response from the fake backend.
  498. try self.rpcIssuer.respond(withJSON: ["email": self.kEmail,
  499. "requestType": verifyEmailRequestType,
  500. "newEmail": kNewEmail])
  501. }
  502. try auth?.signOut()
  503. auth?.checkActionCode(kFakeOobCode) { info, error in
  504. // 4. After the response triggers the callback, verify the returned result.
  505. XCTAssertTrue(Thread.isMainThread)
  506. XCTAssertNil(error)
  507. XCTAssertEqual(info?.email, kNewEmail)
  508. XCTAssertEqual(info?.operation, ActionCodeOperation.verifyEmail)
  509. expectation.fulfill()
  510. }
  511. waitForExpectations(timeout: 5)
  512. }
  513. /** @fn testCheckActionCodeFailure
  514. @brief Tests the flow of a failed @c checkActionCode:completion call.
  515. */
  516. func testCheckActionCodeFailure() throws {
  517. let expectation = self.expectation(description: #function)
  518. // 1. Setup respond block to test and fake send request.
  519. rpcIssuer.respondBlock = {
  520. // 2. Send the response from the fake backend.
  521. try self.rpcIssuer.respond(serverErrorMessage: "EXPIRED_OOB_CODE")
  522. }
  523. try auth?.signOut()
  524. auth?.checkActionCode(kFakeOobCode) { info, error in
  525. // 3. After the response triggers the callback, verify the returned result.
  526. XCTAssertTrue(Thread.isMainThread)
  527. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.expiredActionCode.rawValue)
  528. XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
  529. expectation.fulfill()
  530. }
  531. waitForExpectations(timeout: 5)
  532. XCTAssertNil(auth?.currentUser)
  533. }
  534. /** @fn testApplyActionCodeSuccess
  535. @brief Tests the flow of a successful @c applyActionCode:completion call.
  536. */
  537. func testApplyActionCodeSuccess() throws {
  538. let expectation = self.expectation(description: #function)
  539. // 1. Setup respond block to test and fake send request.
  540. rpcIssuer.respondBlock = {
  541. // 2. Validate the created Request instance.
  542. let request = try XCTUnwrap(self.rpcIssuer.request as? SetAccountInfoRequest)
  543. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  544. // 3. Send the response from the fake backend.
  545. try self.rpcIssuer.respond(withJSON: [:])
  546. }
  547. try auth?.signOut()
  548. auth?.applyActionCode(kFakeOobCode) { error in
  549. // 4. After the response triggers the callback, verify the returned result.
  550. XCTAssertTrue(Thread.isMainThread)
  551. XCTAssertNil(error)
  552. expectation.fulfill()
  553. }
  554. waitForExpectations(timeout: 5)
  555. }
  556. /** @fn testApplyActionCodeFailure
  557. @brief Tests the flow of a failed @c checkActionCode:completion call.
  558. */
  559. func testApplyActionCodeFailure() throws {
  560. let expectation = self.expectation(description: #function)
  561. // 1. Setup respond block to test and fake send request.
  562. rpcIssuer.respondBlock = {
  563. // 2. Send the response from the fake backend.
  564. try self.rpcIssuer.respond(serverErrorMessage: "INVALID_OOB_CODE")
  565. }
  566. try auth?.signOut()
  567. auth?.applyActionCode(kFakeOobCode) { error in
  568. // 3. After the response triggers the callback, verify the returned result.
  569. XCTAssertTrue(Thread.isMainThread)
  570. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.invalidActionCode.rawValue)
  571. XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
  572. expectation.fulfill()
  573. }
  574. waitForExpectations(timeout: 5)
  575. XCTAssertNil(auth?.currentUser)
  576. }
  577. /** @fn testVerifyPasswordResetCodeSuccess
  578. @brief Tests the flow of a successful @c verifyPasswordResetCode:completion call.
  579. */
  580. func testVerifyPasswordResetCodeSuccess() throws {
  581. let expectation = self.expectation(description: #function)
  582. // 1. Setup respond block to test and fake send request.
  583. rpcIssuer.respondBlock = {
  584. // 2. Validate the created Request instance.
  585. let request = try XCTUnwrap(self.rpcIssuer.request as? ResetPasswordRequest)
  586. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  587. XCTAssertEqual(request.oobCode, self.kFakeOobCode)
  588. // 3. Send the response from the fake backend.
  589. try self.rpcIssuer.respond(withJSON: ["email": self.kEmail])
  590. }
  591. try auth?.signOut()
  592. auth?.verifyPasswordResetCode(kFakeOobCode) { email, error in
  593. // 4. After the response triggers the callback, verify the returned result.
  594. XCTAssertTrue(Thread.isMainThread)
  595. XCTAssertEqual(email, self.kEmail)
  596. XCTAssertNil(error)
  597. expectation.fulfill()
  598. }
  599. waitForExpectations(timeout: 5)
  600. }
  601. /** @fn testVerifyPasswordResetCodeFailure
  602. @brief Tests the flow of a failed @c verifyPasswordResetCode:completion call.
  603. */
  604. func testVerifyPasswordResetCodeFailure() throws {
  605. let expectation = self.expectation(description: #function)
  606. // 1. Setup respond block to test and fake send request.
  607. rpcIssuer.respondBlock = {
  608. // 2. Send the response from the fake backend.
  609. try self.rpcIssuer.respond(serverErrorMessage: "INVALID_OOB_CODE")
  610. }
  611. try auth?.signOut()
  612. auth?.verifyPasswordResetCode(kFakeOobCode) { email, error in
  613. // 3. After the response triggers the callback, verify the returned result.
  614. XCTAssertTrue(Thread.isMainThread)
  615. XCTAssertNil(email)
  616. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.invalidActionCode.rawValue)
  617. XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
  618. expectation.fulfill()
  619. }
  620. waitForExpectations(timeout: 5)
  621. XCTAssertNil(auth?.currentUser)
  622. }
  623. /** @fn testSignInWithEmailLinkCredentialSuccess
  624. @brief Tests the flow of a successfully @c signInWithCredential:completion: call with an
  625. email sign-in link credential using FIREmailAuthProvider.
  626. */
  627. func testSignInWithEmailLinkCredentialSuccess() throws {
  628. let expectation = self.expectation(description: #function)
  629. let fakeCode = "testoobcode"
  630. setFakeGetAccountProvider()
  631. setFakeSecureTokenService()
  632. // 1. Setup respond block to test and fake send request.
  633. rpcIssuer.respondBlock = {
  634. // 2. Validate the created Request instance.
  635. let request = try XCTUnwrap(self.rpcIssuer.request as? EmailLinkSignInRequest)
  636. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  637. XCTAssertEqual(request.oobCode, fakeCode)
  638. XCTAssertEqual(request.email, self.kEmail)
  639. // 3. Send the response from the fake backend.
  640. try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken,
  641. "isNewUser": true,
  642. "refreshToken": self.kRefreshToken])
  643. }
  644. try auth?.signOut()
  645. let emailCredential = EmailAuthProvider.credential(
  646. withEmail: kEmail,
  647. link: kFakeEmailSignInLink
  648. )
  649. auth?.signIn(with: emailCredential) { authResult, error in
  650. // 4. After the response triggers the callback, verify the returned result.
  651. XCTAssertTrue(Thread.isMainThread)
  652. guard let user = authResult?.user else {
  653. XCTFail("authResult.user or additionalUserInfo is missing")
  654. return
  655. }
  656. XCTAssertEqual(user.refreshToken, self.kRefreshToken)
  657. XCTAssertFalse(user.isAnonymous)
  658. XCTAssertEqual(user.email, self.kEmail)
  659. XCTAssertNil(error)
  660. expectation.fulfill()
  661. }
  662. waitForExpectations(timeout: 5)
  663. }
  664. /** @fn testSignInWithEmailLinkCredentialFailure
  665. @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
  666. email-email sign-in link credential using FIREmailAuthProvider.
  667. */
  668. func testSignInWithEmailLinkCredentialFailure() throws {
  669. let expectation = self.expectation(description: #function)
  670. // 1. Setup respond block to test and fake send request.
  671. rpcIssuer.respondBlock = {
  672. // 2. Send the response from the fake backend.
  673. try self.rpcIssuer.respond(serverErrorMessage: "USER_DISABLED")
  674. }
  675. try auth?.signOut()
  676. let emailCredential = EmailAuthProvider.credential(
  677. withEmail: kEmail,
  678. link: kFakeEmailSignInLink
  679. )
  680. auth?.signIn(with: emailCredential) { authResult, error in
  681. // 3. After the response triggers the callback, verify the returned result.
  682. XCTAssertTrue(Thread.isMainThread)
  683. XCTAssertNil(authResult)
  684. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.userDisabled.rawValue)
  685. XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
  686. expectation.fulfill()
  687. }
  688. waitForExpectations(timeout: 5)
  689. XCTAssertNil(auth?.currentUser)
  690. }
  691. /** @fn testSignInWithEmailCredentialSuccess
  692. @brief Tests the flow of a successfully @c signInWithCredential:completion: call with an
  693. email-password credential.
  694. */
  695. func testSignInWithEmailCredentialSuccess() throws {
  696. let expectation = self.expectation(description: #function)
  697. setFakeGetAccountProvider()
  698. setFakeSecureTokenService()
  699. // 1. Setup respond block to test and fake send request.
  700. rpcIssuer.respondBlock = {
  701. // 2. Validate the created Request instance.
  702. let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyPasswordRequest)
  703. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  704. XCTAssertEqual(request.password, self.kFakePassword)
  705. XCTAssertEqual(request.email, self.kEmail)
  706. // 3. Send the response from the fake backend.
  707. try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken,
  708. "isNewUser": true,
  709. "refreshToken": self.kRefreshToken])
  710. }
  711. try auth?.signOut()
  712. let emailCredential = EmailAuthProvider.credential(withEmail: kEmail, password: kFakePassword)
  713. auth?.signIn(with: emailCredential) { authResult, error in
  714. // 4. After the response triggers the callback, verify the returned result.
  715. XCTAssertTrue(Thread.isMainThread)
  716. guard let user = authResult?.user else {
  717. XCTFail("authResult.user or additionalUserInfo is missing")
  718. return
  719. }
  720. XCTAssertEqual(user.refreshToken, self.kRefreshToken)
  721. XCTAssertFalse(user.isAnonymous)
  722. XCTAssertEqual(user.email, self.kEmail)
  723. XCTAssertNil(error)
  724. expectation.fulfill()
  725. }
  726. waitForExpectations(timeout: 5)
  727. }
  728. /** @fn testSignInWithEmailCredentialFailure
  729. @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
  730. email-password credential.
  731. */
  732. func testSignInWithEmailCredentialFailure() throws {
  733. let expectation = self.expectation(description: #function)
  734. // 1. Setup respond block to test and fake send request.
  735. rpcIssuer.respondBlock = {
  736. // 2. Send the response from the fake backend.
  737. try self.rpcIssuer.respond(serverErrorMessage: "USER_DISABLED")
  738. }
  739. try auth?.signOut()
  740. let emailCredential = EmailAuthProvider.credential(withEmail: kEmail, password: kFakePassword)
  741. auth?.signIn(with: emailCredential) { authResult, error in
  742. // 3. After the response triggers the callback, verify the returned result.
  743. XCTAssertTrue(Thread.isMainThread)
  744. XCTAssertNil(authResult)
  745. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.userDisabled.rawValue)
  746. XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
  747. expectation.fulfill()
  748. }
  749. waitForExpectations(timeout: 5)
  750. XCTAssertNil(auth?.currentUser)
  751. }
  752. /** @fn testSignInWithEmailCredentialEmptyPassword
  753. @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
  754. email-password credential using an empty password. This error occurs on the client side,
  755. so there is no need to fake an RPC response.
  756. */
  757. func testSignInWithEmailCredentialEmptyPassword() throws {
  758. let expectation = self.expectation(description: #function)
  759. let emailCredential = EmailAuthProvider.credential(withEmail: kEmail, password: "")
  760. auth?.signIn(with: emailCredential) { authResult, error in
  761. XCTAssertTrue(Thread.isMainThread)
  762. XCTAssertNil(authResult)
  763. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.wrongPassword.rawValue)
  764. XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
  765. expectation.fulfill()
  766. }
  767. waitForExpectations(timeout: 5)
  768. }
  769. #if os(iOS)
  770. class FakeProvider: NSObject, FederatedAuthProvider {
  771. @available(iOS 13, tvOS 13, macOS 10.15, watchOS 8, *)
  772. func credential(with UIDelegate: FirebaseAuth.AuthUIDelegate?) async throws ->
  773. FirebaseAuth.AuthCredential {
  774. let credential = OAuthCredential(withProviderID: GoogleAuthProvider.id,
  775. sessionID: kOAuthSessionID,
  776. OAuthResponseURLString: kOAuthRequestURI)
  777. XCTAssertEqual(credential.OAuthResponseURLString, kOAuthRequestURI)
  778. XCTAssertEqual(credential.sessionID, kOAuthSessionID)
  779. return credential
  780. }
  781. }
  782. /** @fn testSignInWithProviderSuccess
  783. @brief Tests a successful @c signInWithProvider:UIDelegate:completion: call with an OAuth
  784. provider configured for Google.
  785. */
  786. func testSignInWithProviderSuccess() throws {
  787. let expectation = self.expectation(description: #function)
  788. setFakeGoogleGetAccountProvider()
  789. setFakeSecureTokenService()
  790. // 1. Setup respond block to test and fake send request.
  791. rpcIssuer.respondBlock = {
  792. // 2. Validate the created Request instance.
  793. let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyAssertionRequest)
  794. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  795. XCTAssertEqual(request.providerID, GoogleAuthProvider.id)
  796. XCTAssertTrue(request.returnSecureToken)
  797. // 3. Send the response from the fake backend.
  798. try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken,
  799. "refreshToken": self.kRefreshToken,
  800. "federatedId": self.kGoogleID,
  801. "providerId": GoogleAuthProvider.id,
  802. "localId": self.kLocalID,
  803. "displayName": self.kDisplayName,
  804. "rawUserInfo": self.kGoogleProfile,
  805. "username": self.kUserName])
  806. }
  807. try auth.signOut()
  808. auth.signIn(with: FakeProvider(), uiDelegate: nil) { authResult, error in
  809. // 4. After the response triggers the callback, verify the returned result.
  810. XCTAssertTrue(Thread.isMainThread)
  811. do {
  812. try self.assertUserGoogle(authResult?.user)
  813. } catch {
  814. XCTFail("\(error)")
  815. }
  816. XCTAssertNil(error)
  817. expectation.fulfill()
  818. }
  819. waitForExpectations(timeout: 5)
  820. try assertUserGoogle(auth.currentUser)
  821. }
  822. /** @fn testSignInWithProviderFailure
  823. @brief Tests a failed @c signInWithProvider:UIDelegate:completion: call with the error code
  824. FIRAuthErrorCodeWebSignInUserInteractionFailure.
  825. */
  826. func testSignInWithProviderFailure() throws {
  827. let expectation = self.expectation(description: #function)
  828. setFakeGoogleGetAccountProvider()
  829. setFakeSecureTokenService()
  830. // 1. Setup respond block to test and fake send request.
  831. rpcIssuer.respondBlock = {
  832. // 2. Validate the created Request instance.
  833. let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyAssertionRequest)
  834. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  835. XCTAssertEqual(request.providerID, GoogleAuthProvider.id)
  836. XCTAssertTrue(request.returnSecureToken)
  837. // 3. Send the response from the fake backend.
  838. try self.rpcIssuer.respond(serverErrorMessage: "USER_DISABLED")
  839. }
  840. try auth.signOut()
  841. auth.signIn(with: FakeProvider(), uiDelegate: nil) { authResult, error in
  842. // 4. After the response triggers the callback, verify the returned result.
  843. XCTAssertTrue(Thread.isMainThread)
  844. XCTAssertNil(authResult)
  845. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.userDisabled.rawValue)
  846. expectation.fulfill()
  847. }
  848. waitForExpectations(timeout: 5)
  849. }
  850. /** @fn testSignInWithGoogleAccountExistsError
  851. @brief Tests the flow of a failed @c signInWithCredential:completion: with a Google credential
  852. where the backend returns a needs @needConfirmation equal to true. An
  853. FIRAuthErrorCodeAccountExistsWithDifferentCredential error should be thrown.
  854. */
  855. func testSignInWithGoogleAccountExistsError() throws {
  856. let expectation = self.expectation(description: #function)
  857. setFakeGoogleGetAccountProvider()
  858. setFakeSecureTokenService()
  859. // 1. Setup respond block to test and fake send request.
  860. rpcIssuer.respondBlock = {
  861. // 2. Validate the created Request instance.
  862. let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyAssertionRequest)
  863. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  864. XCTAssertEqual(request.providerID, GoogleAuthProvider.id)
  865. XCTAssertEqual(request.providerIDToken, self.kGoogleIDToken)
  866. XCTAssertEqual(request.providerAccessToken, self.kGoogleAccessToken)
  867. XCTAssertTrue(request.returnSecureToken)
  868. // 3. Send the response from the fake backend.
  869. try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken,
  870. "refreshToken": self.kRefreshToken,
  871. "federatedId": self.kGoogleID,
  872. "providerId": GoogleAuthProvider.id,
  873. "localId": self.kLocalID,
  874. "displayName": self.kGoogleDisplayName,
  875. "rawUserInfo": self.kGoogleProfile,
  876. "username": self.kUserName,
  877. "needConfirmation": true])
  878. }
  879. try auth.signOut()
  880. let googleCredential = GoogleAuthProvider.credential(withIDToken: kGoogleIDToken,
  881. accessToken: kGoogleAccessToken)
  882. auth.signIn(with: googleCredential) { authResult, error in
  883. // 4. After the response triggers the callback, verify the returned result.
  884. XCTAssertTrue(Thread.isMainThread)
  885. XCTAssertNil(authResult)
  886. XCTAssertEqual((error as? NSError)?.code,
  887. AuthErrorCode.accountExistsWithDifferentCredential.rawValue)
  888. expectation.fulfill()
  889. }
  890. waitForExpectations(timeout: 5)
  891. }
  892. /** @fn testSignInWithOAuthCredentialSuccess
  893. @brief Tests the flow of a successful @c signInWithCredential:completion: call with a generic
  894. OAuth credential (In this case, configured for the Google IDP).
  895. */
  896. func testSignInWithOAuthCredentialSuccess() throws {
  897. let expectation = self.expectation(description: #function)
  898. setFakeGoogleGetAccountProvider()
  899. setFakeSecureTokenService()
  900. // 1. Setup respond block to test and fake send request.
  901. rpcIssuer.respondBlock = {
  902. // 2. Validate the created Request instance.
  903. let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyAssertionRequest)
  904. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  905. XCTAssertEqual(request.providerID, GoogleAuthProvider.id)
  906. XCTAssertEqual(request.requestURI, AuthTests.kOAuthRequestURI)
  907. XCTAssertEqual(request.sessionID, AuthTests.kOAuthSessionID)
  908. XCTAssertTrue(request.returnSecureToken)
  909. // 3. Send the response from the fake backend.
  910. try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken,
  911. "refreshToken": self.kRefreshToken,
  912. "federatedId": self.kGoogleID,
  913. "providerId": GoogleAuthProvider.id,
  914. "localId": self.kLocalID,
  915. "displayName": self.kGoogleDisplayName,
  916. "rawUserInfo": self.kGoogleProfile,
  917. "username": self.kUserName])
  918. }
  919. try auth.signOut()
  920. auth.signIn(with: FakeProvider(), uiDelegate: nil) { authResult, error in
  921. // 4. After the response triggers the callback, verify the returned result.
  922. do {
  923. try self.assertUserGoogle(authResult?.user)
  924. } catch {
  925. XCTFail("\(error)")
  926. }
  927. XCTAssertNil(error)
  928. expectation.fulfill()
  929. }
  930. waitForExpectations(timeout: 5)
  931. try assertUserGoogle(auth.currentUser)
  932. }
  933. #endif
  934. /** @fn testSignInWithCredentialSuccess
  935. @brief Tests the flow of a successful @c signInWithCredential:completion: call
  936. with a Google Sign-In credential.
  937. Note: also a superset of the former testSignInWithGoogleCredentialSuccess
  938. */
  939. func testSignInWithCredentialSuccess() throws {
  940. let expectation = self.expectation(description: #function)
  941. setFakeGoogleGetAccountProvider()
  942. setFakeSecureTokenService()
  943. // 1. Setup respond block to test and fake send request.
  944. rpcIssuer.respondBlock = {
  945. // 2. Validate the created Request instance.
  946. let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyAssertionRequest)
  947. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  948. XCTAssertEqual(request.providerID, GoogleAuthProvider.id)
  949. XCTAssertEqual(request.providerIDToken, self.kGoogleIDToken)
  950. XCTAssertEqual(request.providerAccessToken, self.kGoogleAccessToken)
  951. XCTAssertTrue(request.returnSecureToken)
  952. // 3. Send the response from the fake backend.
  953. try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken,
  954. "refreshToken": self.kRefreshToken,
  955. "federatedId": self.kGoogleID,
  956. "providerId": GoogleAuthProvider.id,
  957. "localId": self.kLocalID,
  958. "displayName": self.kGoogleDisplayName,
  959. "rawUserInfo": self.kGoogleProfile,
  960. "username": self.kGoogleDisplayName])
  961. }
  962. try auth.signOut()
  963. let googleCredential = GoogleAuthProvider.credential(withIDToken: kGoogleIDToken,
  964. accessToken: kGoogleAccessToken)
  965. auth.signIn(with: googleCredential) { authResult, error in
  966. // 4. After the response triggers the callback, verify the returned result.
  967. do {
  968. try self.assertUserGoogle(authResult?.user)
  969. guard let additionalUserInfo = authResult?.additionalUserInfo,
  970. let profile = additionalUserInfo.profile as? [String: String] else {
  971. XCTFail("authResult.additionalUserInfo is missing")
  972. return
  973. }
  974. XCTAssertEqual(profile, self.kGoogleProfile)
  975. XCTAssertEqual(additionalUserInfo.username, self.kGoogleDisplayName)
  976. XCTAssertEqual(additionalUserInfo.providerID, GoogleAuthProvider.id)
  977. } catch {
  978. XCTFail("\(error)")
  979. }
  980. XCTAssertNil(error)
  981. expectation.fulfill()
  982. }
  983. waitForExpectations(timeout: 5)
  984. try assertUserGoogle(auth.currentUser)
  985. }
  986. /** @fn testSignInWithGoogleCredentialFailure
  987. @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
  988. Google Sign-In credential.
  989. */
  990. func testSignInWithGoogleCredentialFailure() throws {
  991. let expectation = self.expectation(description: #function)
  992. setFakeGoogleGetAccountProvider()
  993. setFakeSecureTokenService()
  994. // 1. Setup respond block to test and fake send request.
  995. rpcIssuer.respondBlock = {
  996. // 2. Validate the created Request instance.
  997. let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyAssertionRequest)
  998. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  999. XCTAssertEqual(request.providerID, GoogleAuthProvider.id)
  1000. XCTAssertTrue(request.returnSecureToken)
  1001. // 3. Send the response from the fake backend.
  1002. try self.rpcIssuer.respond(serverErrorMessage: "EMAIL_EXISTS")
  1003. }
  1004. try auth.signOut()
  1005. let googleCredential = GoogleAuthProvider.credential(withIDToken: kGoogleIDToken,
  1006. accessToken: kGoogleAccessToken)
  1007. auth.signIn(with: googleCredential) { authResult, error in
  1008. // 4. After the response triggers the callback, verify the returned result.
  1009. XCTAssertTrue(Thread.isMainThread)
  1010. XCTAssertNil(authResult)
  1011. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.emailAlreadyInUse.rawValue)
  1012. XCTAssertEqual((error as? NSError)?.userInfo[NSLocalizedDescriptionKey] as? String,
  1013. "The email address is already in use by another account.")
  1014. expectation.fulfill()
  1015. }
  1016. waitForExpectations(timeout: 5)
  1017. }
  1018. /** @fn testSignInWithAppleCredentialFullNameInRequest
  1019. @brief Tests the flow of a successful @c signInWithCredential:completion: call
  1020. with an Apple Sign-In credential with a full name. This test differentiates from
  1021. @c testSignInWithCredentialSuccess only in verifying the full name.
  1022. */
  1023. func testSignInWithAppleCredentialFullNameInRequest() throws {
  1024. let expectation = self.expectation(description: #function)
  1025. let kAppleIDToken = "APPLE_ID_TOKEN"
  1026. let kFirst = "First"
  1027. let kLast = "Last"
  1028. var fullName = PersonNameComponents()
  1029. fullName.givenName = kFirst
  1030. fullName.familyName = kLast
  1031. setFakeGoogleGetAccountProvider()
  1032. setFakeSecureTokenService()
  1033. // 1. Setup respond block to test and fake send request.
  1034. rpcIssuer.respondBlock = {
  1035. // 2. Validate the created Request instance.
  1036. let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyAssertionRequest)
  1037. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  1038. XCTAssertEqual(request.providerID, AuthProviderID.apple.rawValue)
  1039. XCTAssertEqual(request.providerIDToken, kAppleIDToken)
  1040. XCTAssertEqual(request.fullName, fullName)
  1041. XCTAssertTrue(request.returnSecureToken)
  1042. // 3. Send the response from the fake backend.
  1043. try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken,
  1044. "refreshToken": self.kRefreshToken,
  1045. "federatedId": self.kGoogleID,
  1046. "providerId": AuthProviderID.apple.rawValue,
  1047. "localId": self.kLocalID,
  1048. "displayName": self.kGoogleDisplayName,
  1049. "rawUserInfo": self.kGoogleProfile,
  1050. "firstName": kFirst,
  1051. "lastName": kLast,
  1052. "username": self.kGoogleDisplayName])
  1053. }
  1054. try auth.signOut()
  1055. let appleCredential = OAuthProvider.appleCredential(withIDToken: kAppleIDToken,
  1056. rawNonce: nil,
  1057. fullName: fullName)
  1058. auth.signIn(with: appleCredential) { authResult, error in
  1059. // 4. After the response triggers the callback, verify the returned result.
  1060. do {
  1061. try self.assertUserGoogle(authResult?.user)
  1062. guard let additionalUserInfo = authResult?.additionalUserInfo,
  1063. let profile = additionalUserInfo.profile as? [String: String] else {
  1064. XCTFail("authResult.additionalUserInfo is missing")
  1065. return
  1066. }
  1067. XCTAssertEqual(profile, self.kGoogleProfile)
  1068. XCTAssertEqual(additionalUserInfo.username, self.kGoogleDisplayName)
  1069. XCTAssertEqual(additionalUserInfo.providerID, AuthProviderID.apple.rawValue)
  1070. } catch {
  1071. XCTFail("\(error)")
  1072. }
  1073. XCTAssertNil(error)
  1074. expectation.fulfill()
  1075. }
  1076. waitForExpectations(timeout: 5)
  1077. XCTAssertNotNil(auth.currentUser)
  1078. }
  1079. /** @fn testSignInAnonymouslySuccess
  1080. @brief Tests the flow of a successful @c signInAnonymouslyWithCompletion: call.
  1081. */
  1082. func testSignInAnonymouslySuccess() throws {
  1083. let expectation = self.expectation(description: #function)
  1084. setFakeSecureTokenService()
  1085. setFakeGetAccountProviderAnonymous()
  1086. // 1. Setup respond block to test and fake send request.
  1087. rpcIssuer.respondBlock = {
  1088. // 2. Validate the created Request instance.
  1089. let request = try XCTUnwrap(self.rpcIssuer.request as? SignUpNewUserRequest)
  1090. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  1091. XCTAssertNil(request.email)
  1092. XCTAssertNil(request.password)
  1093. XCTAssertTrue(request.returnSecureToken)
  1094. // 3. Send the response from the fake backend.
  1095. try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken,
  1096. "email": self.kEmail,
  1097. "isNewUser": true,
  1098. "refreshToken": self.kRefreshToken])
  1099. }
  1100. try auth?.signOut()
  1101. auth?.signInAnonymously { authResult, error in
  1102. // 4. After the response triggers the callback, verify the returned result.
  1103. XCTAssertNil(error)
  1104. XCTAssertTrue(Thread.isMainThread)
  1105. self.assertUserAnonymous(authResult?.user)
  1106. guard let userInfo = authResult?.additionalUserInfo else {
  1107. XCTFail("authResult.additionalUserInfo is missing")
  1108. return
  1109. }
  1110. XCTAssertTrue(userInfo.isNewUser)
  1111. XCTAssertNil(userInfo.username)
  1112. XCTAssertNil(userInfo.profile)
  1113. XCTAssertEqual(userInfo.providerID, "")
  1114. expectation.fulfill()
  1115. }
  1116. waitForExpectations(timeout: 5)
  1117. try assertUserAnonymous(XCTUnwrap(auth?.currentUser))
  1118. }
  1119. /** @fn testSignInAnonymouslyFailure
  1120. @brief Tests the flow of a failed @c signInAnonymouslyWithCompletion: call.
  1121. */
  1122. func testSignInAnonymouslyFailure() throws {
  1123. let expectation = self.expectation(description: #function)
  1124. rpcIssuer.respondBlock = {
  1125. try self.rpcIssuer.respond(serverErrorMessage: "OPERATION_NOT_ALLOWED")
  1126. }
  1127. try auth?.signOut()
  1128. auth?.verifyPasswordResetCode(kFakeOobCode) { email, error in
  1129. XCTAssertTrue(Thread.isMainThread)
  1130. XCTAssertNil(email)
  1131. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.operationNotAllowed.rawValue)
  1132. XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
  1133. expectation.fulfill()
  1134. }
  1135. waitForExpectations(timeout: 5)
  1136. XCTAssertNil(auth?.currentUser)
  1137. }
  1138. /** @fn testSignInWithCustomTokenSuccess
  1139. @brief Tests the flow of a successful @c signInWithCustomToken:completion: call.
  1140. */
  1141. func testSignInWithCustomTokenSuccess() throws {
  1142. let expectation = self.expectation(description: #function)
  1143. setFakeSecureTokenService()
  1144. setFakeGetAccountProvider()
  1145. // 1. Setup respond block to test and fake send request.
  1146. rpcIssuer.respondBlock = {
  1147. // 2. Validate the created Request instance.
  1148. let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyCustomTokenRequest)
  1149. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  1150. XCTAssertEqual(request.token, self.kCustomToken)
  1151. XCTAssertTrue(request.returnSecureToken)
  1152. // 3. Send the response from the fake backend.
  1153. try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken,
  1154. "email": self.kEmail,
  1155. "isNewUser": false,
  1156. "refreshToken": self.kRefreshToken])
  1157. }
  1158. try auth?.signOut()
  1159. auth?.signIn(withCustomToken: kCustomToken) { authResult, error in
  1160. // 4. After the response triggers the callback, verify the returned result.
  1161. XCTAssertTrue(Thread.isMainThread)
  1162. self.assertUser(authResult?.user)
  1163. guard let userInfo = authResult?.additionalUserInfo else {
  1164. XCTFail("authResult.additionalUserInfo is missing")
  1165. return
  1166. }
  1167. XCTAssertFalse(userInfo.isNewUser)
  1168. XCTAssertNil(userInfo.username)
  1169. XCTAssertNil(userInfo.profile)
  1170. XCTAssertEqual(userInfo.providerID, "")
  1171. XCTAssertNil(error)
  1172. expectation.fulfill()
  1173. }
  1174. waitForExpectations(timeout: 5)
  1175. assertUser(auth?.currentUser)
  1176. }
  1177. /** @fn testSignInWithCustomTokenFailure
  1178. @brief Tests the flow of a failed @c signInWithCustomToken:completion: call.
  1179. */
  1180. func testSignInWithCustomTokenFailure() throws {
  1181. let expectation = self.expectation(description: #function)
  1182. rpcIssuer.respondBlock = {
  1183. try self.rpcIssuer.respond(serverErrorMessage: "INVALID_CUSTOM_TOKEN")
  1184. }
  1185. try auth?.signOut()
  1186. auth?.signIn(withCustomToken: kCustomToken) { authResult, error in
  1187. XCTAssertTrue(Thread.isMainThread)
  1188. XCTAssertNil(authResult?.user)
  1189. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.invalidCustomToken.rawValue)
  1190. XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
  1191. expectation.fulfill()
  1192. }
  1193. waitForExpectations(timeout: 5)
  1194. XCTAssertNil(auth?.currentUser)
  1195. }
  1196. #if os(iOS)
  1197. /** @fn testCreateUserWithEmailPasswordWithRecaptchaVerificationSuccess
  1198. @brief Tests the flow of a successful @c createUserWithEmail:password:completion: call.
  1199. */
  1200. func testCreateUserWithEmailPasswordWithRecaptchaVerificationSuccess() throws {
  1201. let expectation = self.expectation(description: #function)
  1202. let kTestRecaptchaKey = "projects/123/keys/456"
  1203. rpcIssuer.recaptchaSiteKey = kTestRecaptchaKey
  1204. setFakeSecureTokenService()
  1205. setFakeGetAccountProvider()
  1206. // 1. Setup respond block to test and fake send request.
  1207. rpcIssuer.respondBlock = {
  1208. // 2. Validate the created Request instance.
  1209. let request = try XCTUnwrap(self.rpcIssuer.request as? SignUpNewUserRequest)
  1210. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  1211. XCTAssertEqual(request.email, self.kEmail)
  1212. XCTAssertEqual(request.password, self.kFakePassword)
  1213. XCTAssertTrue(request.returnSecureToken)
  1214. request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
  1215. recaptchaVersion: AuthTests.kFakeRecaptchaVersion)
  1216. // 3. Send the response from the fake backend.
  1217. try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken,
  1218. "email": self.kEmail,
  1219. "isNewUser": true,
  1220. "refreshToken": self.kRefreshToken])
  1221. }
  1222. try auth?.signOut()
  1223. auth?.createUser(withEmail: kEmail, password: kFakePassword) { authResult, error in
  1224. // 4. After the response triggers the callback, verify the returned result.
  1225. XCTAssertTrue(Thread.isMainThread)
  1226. self.assertUser(authResult?.user)
  1227. guard let userInfo = authResult?.additionalUserInfo else {
  1228. XCTFail("authResult.additionalUserInfo is missing")
  1229. return
  1230. }
  1231. XCTAssertTrue(userInfo.isNewUser)
  1232. XCTAssertNil(userInfo.username)
  1233. XCTAssertNil(userInfo.profile)
  1234. XCTAssertEqual(userInfo.providerID, EmailAuthProvider.id)
  1235. XCTAssertNil(error)
  1236. expectation.fulfill()
  1237. }
  1238. waitForExpectations(timeout: 5)
  1239. assertUser(auth?.currentUser)
  1240. }
  1241. /** @fn testCreateUserWithEmailPasswordWithRecaptchaVerificationFallbackSuccess
  1242. @brief Tests the flow of a successful @c createUserWithEmail:password:completion: call.
  1243. */
  1244. func testCreateUserWithEmailPasswordWithRecaptchaVerificationFallbackSuccess() throws {
  1245. let expectation = self.expectation(description: #function)
  1246. let kTestRecaptchaKey = "projects/123/keys/456"
  1247. rpcIssuer.recaptchaSiteKey = kTestRecaptchaKey
  1248. setFakeSecureTokenService()
  1249. setFakeGetAccountProvider()
  1250. // 1. Setup respond block to test and fake send request.
  1251. rpcIssuer.respondBlock = {
  1252. // 2. Validate the created Request instance.
  1253. let request = try XCTUnwrap(self.rpcIssuer.request as? SignUpNewUserRequest)
  1254. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  1255. XCTAssertEqual(request.email, self.kEmail)
  1256. XCTAssertEqual(request.password, self.kFakePassword)
  1257. XCTAssertTrue(request.returnSecureToken)
  1258. request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
  1259. recaptchaVersion: AuthTests.kFakeRecaptchaVersion)
  1260. // 3. Send the response from the fake backend.
  1261. try self.rpcIssuer.respond(serverErrorMessage: "MISSING_RECAPTCHA_TOKEN")
  1262. }
  1263. rpcIssuer.nextRespondBlock = {
  1264. // 4. Validate again the created Request instance after the recaptcha retry.
  1265. let request = try XCTUnwrap(self.rpcIssuer.request as? SignUpNewUserRequest)
  1266. XCTAssertEqual(request.email, self.kEmail)
  1267. XCTAssertEqual(request.password, self.kFakePassword)
  1268. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  1269. XCTAssertTrue(request.returnSecureToken)
  1270. request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
  1271. recaptchaVersion: AuthTests.kFakeRecaptchaVersion)
  1272. // 5. Send the response from the fake backend.
  1273. try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken,
  1274. "email": self.kEmail,
  1275. "isNewUser": true,
  1276. "refreshToken": self.kRefreshToken])
  1277. }
  1278. try auth?.signOut()
  1279. auth?.createUser(withEmail: kEmail, password: kFakePassword) { authResult, error in
  1280. // 4. After the response triggers the callback, verify the returned result.
  1281. XCTAssertTrue(Thread.isMainThread)
  1282. self.assertUser(authResult?.user)
  1283. guard let userInfo = authResult?.additionalUserInfo else {
  1284. XCTFail("authResult.additionalUserInfo is missing")
  1285. return
  1286. }
  1287. XCTAssertTrue(userInfo.isNewUser)
  1288. XCTAssertNil(userInfo.username)
  1289. XCTAssertNil(userInfo.profile)
  1290. XCTAssertEqual(userInfo.providerID, EmailAuthProvider.id)
  1291. XCTAssertNil(error)
  1292. expectation.fulfill()
  1293. }
  1294. waitForExpectations(timeout: 5)
  1295. assertUser(auth?.currentUser)
  1296. }
  1297. #endif
  1298. /** @fn testCreateUserWithEmailPasswordSuccess
  1299. @brief Tests the flow of a successful @c createUserWithEmail:password:completion: call.
  1300. */
  1301. func testCreateUserWithEmailPasswordSuccess() throws {
  1302. let expectation = self.expectation(description: #function)
  1303. setFakeSecureTokenService()
  1304. setFakeGetAccountProvider()
  1305. // 1. Setup respond block to test and fake send request.
  1306. rpcIssuer.respondBlock = {
  1307. // 2. Validate the created Request instance.
  1308. let request = try XCTUnwrap(self.rpcIssuer.request as? SignUpNewUserRequest)
  1309. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  1310. XCTAssertEqual(request.email, self.kEmail)
  1311. XCTAssertEqual(request.password, self.kFakePassword)
  1312. XCTAssertTrue(request.returnSecureToken)
  1313. // 3. Send the response from the fake backend.
  1314. try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken,
  1315. "email": self.kEmail,
  1316. "isNewUser": true,
  1317. "refreshToken": self.kRefreshToken])
  1318. }
  1319. try auth?.signOut()
  1320. auth?.createUser(withEmail: kEmail, password: kFakePassword) { authResult, error in
  1321. // 4. After the response triggers the callback, verify the returned result.
  1322. XCTAssertTrue(Thread.isMainThread)
  1323. self.assertUser(authResult?.user)
  1324. guard let userInfo = authResult?.additionalUserInfo else {
  1325. XCTFail("authResult.additionalUserInfo is missing")
  1326. return
  1327. }
  1328. XCTAssertTrue(userInfo.isNewUser)
  1329. XCTAssertNil(userInfo.username)
  1330. XCTAssertNil(userInfo.profile)
  1331. XCTAssertEqual(userInfo.providerID, EmailAuthProvider.id)
  1332. XCTAssertNil(error)
  1333. expectation.fulfill()
  1334. }
  1335. waitForExpectations(timeout: 5)
  1336. assertUser(auth?.currentUser)
  1337. }
  1338. /** @fn testCreateUserWithEmailPasswordFailure
  1339. @brief Tests the flow of a failed @c createUserWithEmail:password:completion: call.
  1340. */
  1341. func testCreateUserWithEmailPasswordFailure() throws {
  1342. let expectation = self.expectation(description: #function)
  1343. let reason = "The password must be 6 characters long or more."
  1344. rpcIssuer.respondBlock = {
  1345. try self.rpcIssuer.respond(serverErrorMessage: "WEAK_PASSWORD")
  1346. }
  1347. try auth?.signOut()
  1348. auth?.createUser(withEmail: kEmail, password: kFakePassword) { authResult, error in
  1349. XCTAssertTrue(Thread.isMainThread)
  1350. XCTAssertNil(authResult?.user)
  1351. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.weakPassword.rawValue)
  1352. XCTAssertEqual((error as? NSError)?.userInfo[NSLocalizedDescriptionKey] as? String, reason)
  1353. expectation.fulfill()
  1354. }
  1355. waitForExpectations(timeout: 5)
  1356. XCTAssertNil(auth?.currentUser)
  1357. }
  1358. /** @fn testCreateUserEmptyPasswordFailure
  1359. @brief Tests the flow of a failed @c createUserWithEmail:password:completion: call due to an
  1360. empty password. This error occurs on the client side, so there is no need to fake an RPC
  1361. response.
  1362. */
  1363. func testCreateUserEmptyPasswordFailure() throws {
  1364. let expectation = self.expectation(description: #function)
  1365. try auth?.signOut()
  1366. auth?.createUser(withEmail: kEmail, password: "") { authResult, error in
  1367. XCTAssertTrue(Thread.isMainThread)
  1368. XCTAssertNil(authResult?.user)
  1369. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.weakPassword.rawValue)
  1370. expectation.fulfill()
  1371. }
  1372. waitForExpectations(timeout: 5)
  1373. }
  1374. /** @fn testCreateUserEmptyEmailFailure
  1375. @brief Tests the flow of a failed @c createUserWithEmail:password:completion: call due to an
  1376. empty email address. This error occurs on the client side, so there is no need to fake an
  1377. RPC response.
  1378. */
  1379. func testCreateUserEmptyEmailFailure() throws {
  1380. let expectation = self.expectation(description: #function)
  1381. try auth?.signOut()
  1382. auth?.createUser(withEmail: "", password: kFakePassword) { authResult, error in
  1383. XCTAssertTrue(Thread.isMainThread)
  1384. XCTAssertNil(authResult?.user)
  1385. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.missingEmail.rawValue)
  1386. expectation.fulfill()
  1387. }
  1388. waitForExpectations(timeout: 5)
  1389. }
  1390. #if os(iOS)
  1391. /** @fn testSendPasswordResetEmailWithRecaptchaSuccess
  1392. @brief Tests the flow of a successful @c sendPasswordResetWithEmail:completion: call.
  1393. */
  1394. func testSendPasswordResetEmailWithRecaptchaSuccess() throws {
  1395. let expectation = self.expectation(description: #function)
  1396. let kTestRecaptchaKey = "projects/123/keys/456"
  1397. rpcIssuer.recaptchaSiteKey = kTestRecaptchaKey
  1398. // 1. Setup respond block to test and fake send request.
  1399. rpcIssuer.respondBlock = {
  1400. // 2. Validate the created Request instance.
  1401. let request = try XCTUnwrap(self.rpcIssuer.request as? GetOOBConfirmationCodeRequest)
  1402. XCTAssertEqual(request.email, self.kEmail)
  1403. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  1404. request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
  1405. recaptchaVersion: AuthTests.kFakeRecaptchaVersion)
  1406. // 3. Send the response from the fake backend.
  1407. _ = try self.rpcIssuer.respond(withJSON: [:])
  1408. }
  1409. auth?.sendPasswordReset(withEmail: kEmail) { error in
  1410. // 4. After the response triggers the callback, verify success.
  1411. XCTAssertTrue(Thread.isMainThread)
  1412. XCTAssertNil(error)
  1413. expectation.fulfill()
  1414. }
  1415. waitForExpectations(timeout: 5)
  1416. }
  1417. /** @fn testSendPasswordResetEmailWithRecaptchaFallbackSuccess
  1418. @brief Tests the flow of a successful @c sendPasswordResetWithEmail:completion: call.
  1419. */
  1420. func testSendPasswordResetEmailWithRecaptchaFallbackSuccess() throws {
  1421. let expectation = self.expectation(description: #function)
  1422. let kTestRecaptchaKey = "projects/123/keys/456"
  1423. rpcIssuer.recaptchaSiteKey = kTestRecaptchaKey
  1424. // 1. Setup respond block to test and fake send request.
  1425. rpcIssuer.respondBlock = {
  1426. // 2. Validate the created Request instance.
  1427. let request = try XCTUnwrap(self.rpcIssuer.request as? GetOOBConfirmationCodeRequest)
  1428. XCTAssertEqual(request.email, self.kEmail)
  1429. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  1430. request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
  1431. recaptchaVersion: AuthTests.kFakeRecaptchaVersion)
  1432. // 3. Send the response from the fake backend.
  1433. try self.rpcIssuer.respond(serverErrorMessage: "MISSING_RECAPTCHA_TOKEN")
  1434. }
  1435. rpcIssuer.nextRespondBlock = {
  1436. // 4. Validate again the created Request instance after the recaptcha retry.
  1437. let request = try XCTUnwrap(self.rpcIssuer.request as? GetOOBConfirmationCodeRequest)
  1438. XCTAssertEqual(request.email, self.kEmail)
  1439. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  1440. request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
  1441. recaptchaVersion: AuthTests.kFakeRecaptchaVersion)
  1442. // 5. Send the response from the fake backend.
  1443. try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken,
  1444. "email": self.kEmail,
  1445. "isNewUser": true,
  1446. "refreshToken": self.kRefreshToken])
  1447. }
  1448. auth?.sendPasswordReset(withEmail: kEmail) { error in
  1449. // 4. After the response triggers the callback, verify success.
  1450. XCTAssertTrue(Thread.isMainThread)
  1451. XCTAssertNil(error)
  1452. expectation.fulfill()
  1453. }
  1454. waitForExpectations(timeout: 5)
  1455. }
  1456. #endif
  1457. /** @fn testSendPasswordResetEmailSuccess
  1458. @brief Tests the flow of a successful @c sendPasswordReset call.
  1459. */
  1460. func testSendPasswordResetEmailSuccess() throws {
  1461. let expectation = self.expectation(description: #function)
  1462. // 1. Setup respond block to test and fake send request.
  1463. rpcIssuer.respondBlock = {
  1464. // 2. Validate the created Request instance.
  1465. let request = try XCTUnwrap(self.rpcIssuer.request as? GetOOBConfirmationCodeRequest)
  1466. XCTAssertEqual(request.email, self.kEmail)
  1467. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  1468. // 3. Send the response from the fake backend.
  1469. _ = try self.rpcIssuer.respond(withJSON: [:])
  1470. }
  1471. auth?.sendPasswordReset(withEmail: kEmail) { error in
  1472. // 4. After the response triggers the callback, verify success.
  1473. XCTAssertTrue(Thread.isMainThread)
  1474. XCTAssertNil(error)
  1475. expectation.fulfill()
  1476. }
  1477. waitForExpectations(timeout: 5)
  1478. }
  1479. /** @fn testSendPasswordResetEmailFailure
  1480. @brief Tests the flow of a failed @c sendPasswordReset call.
  1481. */
  1482. func testSendPasswordResetEmailFailure() throws {
  1483. let expectation = self.expectation(description: #function)
  1484. rpcIssuer.respondBlock = {
  1485. try self.rpcIssuer.respond(underlyingErrorMessage: "ipRefererBlocked")
  1486. }
  1487. auth?.sendPasswordReset(withEmail: kEmail) { error in
  1488. XCTAssertTrue(Thread.isMainThread)
  1489. let rpcError = (error as? NSError)!
  1490. XCTAssertEqual(rpcError.code, AuthErrorCode.appNotAuthorized.rawValue)
  1491. XCTAssertNotNil(rpcError.userInfo[NSLocalizedDescriptionKey])
  1492. expectation.fulfill()
  1493. }
  1494. waitForExpectations(timeout: 5)
  1495. }
  1496. #if os(iOS)
  1497. /** @fn testSendSignInLinkToEmailWithRecaptchaSuccess
  1498. @brief Tests the flow of a successful @c sendSignInLinkToEmail:actionCodeSettings: call.
  1499. */
  1500. func testSendSignInLinkToEmailWithRecaptchaSuccess() throws {
  1501. let expectation = self.expectation(description: #function)
  1502. let kTestRecaptchaKey = "projects/123/keys/456"
  1503. rpcIssuer.recaptchaSiteKey = kTestRecaptchaKey
  1504. // 1. Setup respond block to test and fake send request.
  1505. rpcIssuer.respondBlock = {
  1506. // 2. Validate the created Request instance.
  1507. let request = try XCTUnwrap(self.rpcIssuer.request as? GetOOBConfirmationCodeRequest)
  1508. XCTAssertEqual(request.email, self.kEmail)
  1509. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  1510. XCTAssertEqual(request.continueURL, self.kContinueURL)
  1511. XCTAssertTrue(request.handleCodeInApp)
  1512. request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
  1513. recaptchaVersion: AuthTests.kFakeRecaptchaVersion)
  1514. // 3. Send the response from the fake backend.
  1515. _ = try self.rpcIssuer.respond(withJSON: [:])
  1516. }
  1517. auth?.sendSignInLink(toEmail: kEmail,
  1518. actionCodeSettings: fakeActionCodeSettings()) { error in
  1519. // 4. After the response triggers the callback, verify success.
  1520. XCTAssertTrue(Thread.isMainThread)
  1521. XCTAssertNil(error)
  1522. expectation.fulfill()
  1523. }
  1524. waitForExpectations(timeout: 5)
  1525. }
  1526. /** @fn testSendSignInLinkToEmailWithRecaptchaFallbackSuccess
  1527. @brief Tests the flow of a successful @c sendSignInLinkToEmail:actionCodeSettings: call.
  1528. */
  1529. func testSendSignInLinkToEmailWithRecaptchaFallbackSuccess() throws {
  1530. let expectation = self.expectation(description: #function)
  1531. let kTestRecaptchaKey = "projects/123/keys/456"
  1532. rpcIssuer.recaptchaSiteKey = kTestRecaptchaKey
  1533. // 1. Setup respond block to test and fake send request.
  1534. rpcIssuer.respondBlock = {
  1535. // 2. Validate the created Request instance.
  1536. let request = try XCTUnwrap(self.rpcIssuer.request as? GetOOBConfirmationCodeRequest)
  1537. XCTAssertEqual(request.email, self.kEmail)
  1538. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  1539. XCTAssertEqual(request.continueURL, self.kContinueURL)
  1540. XCTAssertTrue(request.handleCodeInApp)
  1541. request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
  1542. recaptchaVersion: AuthTests.kFakeRecaptchaVersion)
  1543. // 3. Send the response from the fake backend.
  1544. _ = try self.rpcIssuer.respond(withJSON: [:])
  1545. }
  1546. rpcIssuer.nextRespondBlock = {
  1547. // 4. Validate again the created Request instance after the recaptcha retry.
  1548. let request = try XCTUnwrap(self.rpcIssuer.request as? GetOOBConfirmationCodeRequest)
  1549. XCTAssertEqual(request.email, self.kEmail)
  1550. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  1551. request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
  1552. recaptchaVersion: AuthTests.kFakeRecaptchaVersion)
  1553. // 5. Send the response from the fake backend.
  1554. try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken,
  1555. "email": self.kEmail,
  1556. "isNewUser": true,
  1557. "refreshToken": self.kRefreshToken])
  1558. }
  1559. auth?.sendSignInLink(toEmail: kEmail,
  1560. actionCodeSettings: fakeActionCodeSettings()) { error in
  1561. // 4. After the response triggers the callback, verify success.
  1562. XCTAssertTrue(Thread.isMainThread)
  1563. XCTAssertNil(error)
  1564. expectation.fulfill()
  1565. }
  1566. waitForExpectations(timeout: 5)
  1567. }
  1568. #endif
  1569. /** @fn testSendSignInLinkToEmailSuccess
  1570. @brief Tests the flow of a successful @c sendSignInLinkToEmail call.
  1571. */
  1572. func testSendSignInLinkToEmailSuccess() throws {
  1573. let expectation = self.expectation(description: #function)
  1574. // 1. Setup respond block to test and fake send request.
  1575. rpcIssuer.respondBlock = {
  1576. // 2. Validate the created Request instance.
  1577. let request = try XCTUnwrap(self.rpcIssuer.request as? GetOOBConfirmationCodeRequest)
  1578. XCTAssertEqual(request.email, self.kEmail)
  1579. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  1580. XCTAssertEqual(request.continueURL, self.kContinueURL)
  1581. XCTAssertTrue(request.handleCodeInApp)
  1582. // 3. Send the response from the fake backend.
  1583. _ = try self.rpcIssuer.respond(withJSON: [:])
  1584. }
  1585. auth?.sendSignInLink(toEmail: kEmail,
  1586. actionCodeSettings: fakeActionCodeSettings()) { error in
  1587. // 4. After the response triggers the callback, verify success.
  1588. XCTAssertTrue(Thread.isMainThread)
  1589. XCTAssertNil(error)
  1590. expectation.fulfill()
  1591. }
  1592. waitForExpectations(timeout: 5)
  1593. }
  1594. /** @fn testSendSignInLinkToEmailFailure
  1595. @brief Tests the flow of a failed @c sendSignInLink call.
  1596. */
  1597. func testSendSignInLinkToEmailFailure() throws {
  1598. let expectation = self.expectation(description: #function)
  1599. rpcIssuer.respondBlock = {
  1600. try self.rpcIssuer.respond(underlyingErrorMessage: "ipRefererBlocked")
  1601. }
  1602. auth?.sendSignInLink(toEmail: kEmail,
  1603. actionCodeSettings: fakeActionCodeSettings()) { error in
  1604. XCTAssertTrue(Thread.isMainThread)
  1605. let rpcError = error as? NSError
  1606. XCTAssertEqual(rpcError?.code, AuthErrorCode.appNotAuthorized.rawValue)
  1607. XCTAssertNotNil(rpcError?.userInfo[NSLocalizedDescriptionKey])
  1608. expectation.fulfill()
  1609. }
  1610. waitForExpectations(timeout: 5)
  1611. }
  1612. /** @fn testUpdateCurrentUserFailure
  1613. @brief Tests the flow of a failed @c updateCurrentUser:completion:
  1614. call.
  1615. */
  1616. func testUpdateCurrentUserFailure() throws {
  1617. try waitForSignInWithAccessToken()
  1618. let expectation = self.expectation(description: #function)
  1619. let kTestAPIKey2 = "fakeAPIKey2"
  1620. let auth = try XCTUnwrap(auth)
  1621. let user2 = auth.currentUser
  1622. user2?.requestConfiguration = AuthRequestConfiguration(apiKey: kTestAPIKey2,
  1623. appID: kTestFirebaseAppID)
  1624. rpcIssuer.respondBlock = {
  1625. try self.rpcIssuer.respond(underlyingErrorMessage: "keyInvalid")
  1626. }
  1627. // Clear fake so we can inject error
  1628. rpcIssuer.fakeGetAccountProviderJSON = nil
  1629. auth.updateCurrentUser(user2) { error in
  1630. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.invalidAPIKey.rawValue)
  1631. expectation.fulfill()
  1632. }
  1633. waitForExpectations(timeout: 5)
  1634. }
  1635. /** @fn testUpdateCurrentUserFailureNetworkError
  1636. @brief Tests the flow of a failed @c updateCurrentUser:completion:
  1637. call with a network error.
  1638. */
  1639. func testUpdateCurrentUserFailureNetworkError() throws {
  1640. try waitForSignInWithAccessToken()
  1641. let expectation = self.expectation(description: #function)
  1642. let kTestAPIKey2 = "fakeAPIKey2"
  1643. let auth = try XCTUnwrap(auth)
  1644. let user2 = auth.currentUser
  1645. user2?.requestConfiguration = AuthRequestConfiguration(apiKey: kTestAPIKey2,
  1646. appID: kTestFirebaseAppID)
  1647. rpcIssuer.respondBlock = {
  1648. let kFakeErrorDomain = "fakeDomain"
  1649. let kFakeErrorCode = -1
  1650. let responseError = NSError(domain: kFakeErrorDomain, code: kFakeErrorCode)
  1651. try self.rpcIssuer.respond(withData: nil, error: responseError)
  1652. }
  1653. // Clear fake so we can inject error
  1654. rpcIssuer.fakeGetAccountProviderJSON = nil
  1655. auth.updateCurrentUser(user2) { error in
  1656. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.networkError.rawValue)
  1657. expectation.fulfill()
  1658. }
  1659. waitForExpectations(timeout: 5)
  1660. }
  1661. /** @fn testUpdateCurrentUserFailureNullUser
  1662. @brief Tests the flow of a failed @c updateCurrentUser:completion:
  1663. call with FIRAuthErrorCodeNullUser.
  1664. */
  1665. func testUpdateCurrentUserFailureNullUser() throws {
  1666. try waitForSignInWithAccessToken()
  1667. let expectation = self.expectation(description: #function)
  1668. auth.updateCurrentUser(nil) { error in
  1669. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.nullUser.rawValue)
  1670. expectation.fulfill()
  1671. }
  1672. waitForExpectations(timeout: 5)
  1673. }
  1674. /** @fn testUpdateCurrentUserFailureTenantIDMismatch
  1675. @brief Tests the flow of a failed @c updateCurrentUser:completion:
  1676. call with FIRAuthErrorCodeTenantIDMismatch.
  1677. */
  1678. func testUpdateCurrentUserFailureTenantIDMismatch() throws {
  1679. // User without tenant id
  1680. try waitForSignInWithAccessToken()
  1681. let auth = try XCTUnwrap(auth)
  1682. let user1 = auth.currentUser
  1683. try auth.signOut()
  1684. // User with tenant id "tenant-id"
  1685. auth.tenantID = "tenant-id-1"
  1686. let kTestAccessToken2 = "fakeAccessToken2"
  1687. try waitForSignInWithAccessToken(fakeAccessToken: kTestAccessToken2)
  1688. let user2 = auth.currentUser
  1689. try auth.signOut()
  1690. auth.tenantID = "tenant-id-2"
  1691. let expectation = self.expectation(description: #function)
  1692. auth.updateCurrentUser(user1) { error in
  1693. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.tenantIDMismatch.rawValue)
  1694. expectation.fulfill()
  1695. }
  1696. try auth.signOut()
  1697. auth.tenantID = "tenant-id-2"
  1698. let expectation2 = self.expectation(description: "tenant-id-test2")
  1699. auth.updateCurrentUser(user2) { error in
  1700. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.tenantIDMismatch.rawValue)
  1701. expectation2.fulfill()
  1702. }
  1703. try auth.signOut()
  1704. auth.tenantID = nil
  1705. let expectation3 = self.expectation(description: "tenant-id-test3")
  1706. auth.updateCurrentUser(user2) { error in
  1707. XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.tenantIDMismatch.rawValue)
  1708. expectation3.fulfill()
  1709. }
  1710. waitForExpectations(timeout: 5)
  1711. }
  1712. /** @fn testUpdateCurrentUserSuccess
  1713. @brief Tests the flow of a successful @c updateCurrentUser:completion:
  1714. call with a network error.
  1715. */
  1716. func testUpdateCurrentUserSuccess() throws {
  1717. // Sign in with the first user.
  1718. try waitForSignInWithAccessToken()
  1719. let auth = try XCTUnwrap(auth)
  1720. let user1 = auth.currentUser
  1721. let kTestAPIKey = "fakeAPIKey"
  1722. user1?.requestConfiguration = AuthRequestConfiguration(apiKey: kTestAPIKey,
  1723. appID: kTestFirebaseAppID)
  1724. try auth.signOut()
  1725. let kTestAccessToken2 = "fakeAccessToken2"
  1726. try waitForSignInWithAccessToken(fakeAccessToken: kTestAccessToken2)
  1727. let user2 = auth.currentUser
  1728. let expectation = self.expectation(description: #function)
  1729. // Current user should now be user2.
  1730. XCTAssertEqual(auth.currentUser, user2)
  1731. auth.updateCurrentUser(user1) { error in
  1732. XCTAssertNil(error)
  1733. // Current user should now be user1.
  1734. XCTAssertEqual(auth.currentUser, user1)
  1735. XCTAssertNotEqual(auth.currentUser, user2)
  1736. expectation.fulfill()
  1737. }
  1738. waitForExpectations(timeout: 5)
  1739. }
  1740. /** @fn testRevokeTokenSuccess
  1741. @brief Tests the flow of a successful @c revokeToken:completion.
  1742. */
  1743. func testRevokeTokenSuccess() throws {
  1744. try waitForSignInWithAccessToken()
  1745. let expectation = self.expectation(description: #function)
  1746. let code = "code"
  1747. rpcIssuer.respondBlock = {
  1748. let request = try XCTUnwrap(self.rpcIssuer.request as? RevokeTokenRequest)
  1749. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  1750. XCTAssertEqual(request.providerID, AuthProviderID.apple.rawValue)
  1751. XCTAssertEqual(request.token, code)
  1752. XCTAssertEqual(request.tokenType, .authorizationCode)
  1753. // Send the response from the fake backend.
  1754. _ = try self.rpcIssuer.respond(withJSON: [:])
  1755. }
  1756. auth?.revokeToken(withAuthorizationCode: code) { error in
  1757. // Verify callback success.
  1758. XCTAssertNil(error)
  1759. expectation.fulfill()
  1760. }
  1761. waitForExpectations(timeout: 5)
  1762. }
  1763. /** @fn testRevokeTokenMissingCallback
  1764. @brief Tests the flow of @c revokeToken:completion with a nil callback.
  1765. */
  1766. func testRevokeTokenMissingCallback() throws {
  1767. try waitForSignInWithAccessToken()
  1768. let code = "code"
  1769. let issuer = rpcIssuer
  1770. issuer?.respondBlock = {
  1771. let request = try XCTUnwrap(issuer?.request as? RevokeTokenRequest)
  1772. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  1773. XCTAssertEqual(request.providerID, AuthProviderID.apple.rawValue)
  1774. XCTAssertEqual(request.token, code)
  1775. XCTAssertEqual(request.tokenType, .authorizationCode)
  1776. // Send the response from the fake backend.
  1777. _ = try issuer?.respond(withJSON: [:])
  1778. }
  1779. auth?.revokeToken(withAuthorizationCode: code)
  1780. }
  1781. /** @fn testSignOut
  1782. @brief Tests the @c signOut: method.
  1783. */
  1784. func testSignOut() throws {
  1785. try waitForSignInWithAccessToken()
  1786. // Verify signing out succeeds and clears the current user.
  1787. let auth = try XCTUnwrap(auth)
  1788. try auth.signOut()
  1789. XCTAssertNil(auth.currentUser)
  1790. }
  1791. /** @fn testIsSignInWithEmailLink
  1792. @brief Tests the @c isSignInWithEmailLink: method.
  1793. */
  1794. func testIsSignInWithEmailLink() throws {
  1795. let auth = try XCTUnwrap(auth)
  1796. let kBadSignInEmailLink = "http://www.facebook.com"
  1797. XCTAssertTrue(auth.isSignIn(withEmailLink: kFakeEmailSignInLink))
  1798. XCTAssertTrue(auth.isSignIn(withEmailLink: kFakeEmailSignInDeeplink))
  1799. XCTAssertFalse(auth.isSignIn(withEmailLink: kBadSignInEmailLink))
  1800. XCTAssertFalse(auth.isSignIn(withEmailLink: ""))
  1801. }
  1802. /** @fn testAuthStateChanges
  1803. @brief Tests @c addAuthStateDidChangeListener: and @c removeAuthStateDidChangeListener: methods.
  1804. */
  1805. func testAuthStateChanges() throws {
  1806. // Set up listener.
  1807. let auth = try XCTUnwrap(auth)
  1808. var shouldHaveUser = false
  1809. var expectation: XCTestExpectation?
  1810. let listener = { listenerAuth, user in
  1811. XCTAssertTrue(Thread.isMainThread)
  1812. XCTAssertEqual(auth, listenerAuth)
  1813. XCTAssertEqual(user, auth.currentUser)
  1814. if shouldHaveUser {
  1815. XCTAssertNotNil(user)
  1816. } else {
  1817. XCTAssertNil(user)
  1818. }
  1819. // `expectation` being nil means the listener is not expected to be fired at this moment.
  1820. XCTAssertNotNil(expectation)
  1821. expectation?.fulfill()
  1822. }
  1823. try auth.signOut()
  1824. // Listener should fire immediately when attached.
  1825. expectation = self.expectation(description: "initial")
  1826. shouldHaveUser = false
  1827. let handle = auth.addStateDidChangeListener(listener)
  1828. waitForExpectations(timeout: 5)
  1829. expectation = nil
  1830. // Listener should fire for signing in.
  1831. expectation = self
  1832. .expectation(description: "sign-in") // waited on in waitForSignInWithAccessToken
  1833. shouldHaveUser = true
  1834. try waitForSignInWithAccessToken()
  1835. // Listener should not fire for signing in again.
  1836. expectation = nil
  1837. shouldHaveUser = true
  1838. try waitForSignInWithAccessToken()
  1839. // Listener should fire for signing out.
  1840. expectation = self.expectation(description: "sign-out")
  1841. shouldHaveUser = false
  1842. try auth.signOut()
  1843. waitForExpectations(timeout: 5)
  1844. // Listener should no longer fire once detached.
  1845. expectation = nil
  1846. auth.removeStateDidChangeListener(handle)
  1847. try waitForSignInWithAccessToken()
  1848. }
  1849. /** @fn testIDTokenChanges
  1850. @brief Tests @c addIDTokenDidChangeListener: and @c removeIDTokenDidChangeListener: methods.
  1851. */
  1852. func testIDTokenChanges() throws {
  1853. // Set up listener.
  1854. let auth = try XCTUnwrap(auth)
  1855. var shouldHaveUser = false
  1856. var expectation: XCTestExpectation?
  1857. var fulfilled = false
  1858. let listener = { listenerAuth, user in
  1859. XCTAssertTrue(Thread.isMainThread)
  1860. XCTAssertEqual(auth, listenerAuth)
  1861. XCTAssertEqual(user, auth.currentUser)
  1862. if shouldHaveUser {
  1863. XCTAssertNotNil(user)
  1864. } else {
  1865. XCTAssertNil(user)
  1866. }
  1867. // `expectation` being nil means the listener is not expected to be fired at this moment.
  1868. XCTAssertNotNil(expectation)
  1869. if !fulfilled {
  1870. fulfilled = true
  1871. expectation?.fulfill()
  1872. }
  1873. }
  1874. try auth.signOut()
  1875. // Listener should fire immediately when attached.
  1876. expectation = self.expectation(description: "initial")
  1877. shouldHaveUser = false
  1878. let handle = auth.addIDTokenDidChangeListener(listener)
  1879. waitForExpectations(timeout: 5)
  1880. expectation = nil
  1881. // Listener should fire for signing in. Expectation is waited on in
  1882. // waitForSignInWithAccessToken.
  1883. fulfilled = false
  1884. expectation = self.expectation(description: "sign-in")
  1885. shouldHaveUser = true
  1886. try waitForSignInWithAccessToken()
  1887. // Listener should not fire for signing in again.
  1888. expectation = nil
  1889. shouldHaveUser = true
  1890. try waitForSignInWithAccessToken()
  1891. // Listener should fire for signing in again as the same user with another access token.
  1892. fulfilled = false
  1893. expectation = self.expectation(description: "sign-in")
  1894. shouldHaveUser = true
  1895. try waitForSignInWithAccessToken(fakeAccessToken: AuthTests.kNewAccessToken)
  1896. // Listener should fire for signing out.
  1897. fulfilled = false
  1898. expectation = self.expectation(description: "sign-out")
  1899. shouldHaveUser = false
  1900. try auth.signOut()
  1901. waitForExpectations(timeout: 5)
  1902. // Listener should no longer fire once detached.
  1903. expectation = nil
  1904. auth.removeStateDidChangeListener(handle)
  1905. try waitForSignInWithAccessToken()
  1906. }
  1907. /** @fn testUseEmulator
  1908. @brief Tests the @c useEmulatorWithHost:port: method.
  1909. */
  1910. func testUseEmulator() throws {
  1911. auth.useEmulator(withHost: "host", port: 12345)
  1912. XCTAssertEqual("host:12345", auth.requestConfiguration.emulatorHostAndPort)
  1913. #if os(iOS)
  1914. let settings = try XCTUnwrap(auth.settings)
  1915. XCTAssertTrue(settings.isAppVerificationDisabledForTesting)
  1916. #endif
  1917. }
  1918. /** @fn testUseEmulatorNeverCalled
  1919. @brief Tests that the emulatorHostAndPort stored in @c FIRAuthRequestConfiguration is nil if the
  1920. @c useEmulatorWithHost:port: is not called.
  1921. */
  1922. func testUseEmulatorNeverCalled() throws {
  1923. XCTAssertNil(auth.requestConfiguration.emulatorHostAndPort)
  1924. #if os(iOS)
  1925. let settings = try XCTUnwrap(auth.settings)
  1926. XCTAssertFalse(settings.isAppVerificationDisabledForTesting)
  1927. #endif
  1928. }
  1929. /** @fn testUseEmulatorIPv6Address
  1930. @brief Tests the @c useEmulatorWithHost:port: method with an IPv6 host address.
  1931. */
  1932. func testUseEmulatorIPv6Address() throws {
  1933. auth.useEmulator(withHost: "::1", port: 12345)
  1934. XCTAssertEqual("[::1]:12345", auth.requestConfiguration.emulatorHostAndPort)
  1935. #if os(iOS)
  1936. let settings = try XCTUnwrap(auth.settings)
  1937. XCTAssertTrue(settings.isAppVerificationDisabledForTesting)
  1938. #endif
  1939. }
  1940. // MARK: Automatic Token Refresh Tests.
  1941. /** @fn testAutomaticTokenRefresh
  1942. @brief Tests a successful flow to automatically refresh tokens for a signed in user.
  1943. */
  1944. func testAutomaticTokenRefresh() throws {
  1945. try auth.signOut()
  1946. // Enable auto refresh
  1947. enableAutoTokenRefresh()
  1948. // Sign in a user.
  1949. try waitForSignInWithAccessToken()
  1950. setFakeSecureTokenService(fakeAccessToken: AuthTests.kNewAccessToken)
  1951. // Verify that the current user's access token is the "old" access token before automatic token
  1952. // refresh.
  1953. XCTAssertEqual(AuthTests.kAccessToken, auth.currentUser?.rawAccessToken())
  1954. // Execute saved token refresh task.
  1955. let expectation = self.expectation(description: #function)
  1956. kAuthGlobalWorkQueue.async {
  1957. XCTAssertNotNil(self.authDispatcherCallback)
  1958. self.authDispatcherCallback?()
  1959. expectation.fulfill()
  1960. }
  1961. waitForExpectations(timeout: 5)
  1962. waitForAuthGlobalWorkQueueDrain()
  1963. // Verify that current user's access token is the "new" access token provided in the mock secure
  1964. // token response during automatic token refresh.
  1965. RPCBaseTests.waitSleep()
  1966. XCTAssertEqual(AuthTests.kNewAccessToken, auth.currentUser?.rawAccessToken())
  1967. }
  1968. /** @fn testAutomaticTokenRefreshInvalidTokenFailure
  1969. @brief Tests an unsuccessful flow to auto refresh tokens with an "invalid token" error.
  1970. This error should cause the user to be signed out.
  1971. */
  1972. func testAutomaticTokenRefreshInvalidTokenFailure() throws {
  1973. try auth.signOut()
  1974. // Enable auto refresh
  1975. enableAutoTokenRefresh()
  1976. // Sign in a user.
  1977. try waitForSignInWithAccessToken()
  1978. // Set up expectation for secureToken RPC made by a failed attempt to refresh tokens.
  1979. rpcIssuer.secureTokenErrorString = "INVALID_ID_TOKEN"
  1980. // Verify that the current user's access token is the "old" access token before automatic token
  1981. // refresh.
  1982. XCTAssertEqual(AuthTests.kAccessToken, auth.currentUser?.rawAccessToken())
  1983. // Execute saved token refresh task.
  1984. let expectation = self.expectation(description: #function)
  1985. kAuthGlobalWorkQueue.async {
  1986. XCTAssertNotNil(self.authDispatcherCallback)
  1987. self.authDispatcherCallback?()
  1988. expectation.fulfill()
  1989. }
  1990. waitForExpectations(timeout: 5)
  1991. waitForAuthGlobalWorkQueueDrain()
  1992. // Verify that the user is nil after failed attempt to refresh tokens caused signed out.
  1993. RPCBaseTests.waitSleep()
  1994. XCTAssertNil(auth.currentUser)
  1995. }
  1996. /** @fn testAutomaticTokenRefreshRetry
  1997. @brief Tests that a retry is attempted for a automatic token refresh task (which is not due to
  1998. invalid tokens). The initial attempt to refresh the access token fails, but the second
  1999. attempt is successful.
  2000. */
  2001. func testAutomaticTokenRefreshRetry() throws {
  2002. try auth.signOut()
  2003. // Enable auto refresh
  2004. enableAutoTokenRefresh()
  2005. // Sign in a user.
  2006. try waitForSignInWithAccessToken()
  2007. // Set up expectation for secureToken RPC made by a failed attempt to refresh tokens.
  2008. rpcIssuer.secureTokenNetworkError = NSError(domain: "ERROR", code: -1)
  2009. // Execute saved token refresh task.
  2010. let expectation = self.expectation(description: #function)
  2011. kAuthGlobalWorkQueue.async {
  2012. XCTAssertNotNil(self.authDispatcherCallback)
  2013. self.authDispatcherCallback?()
  2014. self.authDispatcherCallback = nil
  2015. expectation.fulfill()
  2016. }
  2017. waitForExpectations(timeout: 5)
  2018. waitForAuthGlobalWorkQueueDrain()
  2019. rpcIssuer.secureTokenNetworkError = nil
  2020. setFakeSecureTokenService(fakeAccessToken: AuthTests.kNewAccessToken)
  2021. // The old access token should still be the current user's access token and not the new access
  2022. // token (kNewAccessToken).
  2023. XCTAssertEqual(AuthTests.kAccessToken, auth.currentUser?.rawAccessToken())
  2024. // Execute saved token refresh task.
  2025. let expectation2 = self.expectation(description: "dispatchAfterExpectation")
  2026. kAuthGlobalWorkQueue.async {
  2027. RPCBaseTests.waitSleep()
  2028. XCTAssertNotNil(self.authDispatcherCallback)
  2029. self.authDispatcherCallback?()
  2030. expectation2.fulfill()
  2031. }
  2032. waitForExpectations(timeout: 5)
  2033. waitForAuthGlobalWorkQueueDrain()
  2034. // Time for callback to run.
  2035. RPCBaseTests.waitSleep()
  2036. // Verify that current user's access token is the "new" access token provided in the mock secure
  2037. // token response during automatic token refresh.
  2038. XCTAssertEqual(AuthTests.kNewAccessToken, auth.currentUser?.rawAccessToken())
  2039. }
  2040. #if os(iOS)
  2041. /** @fn testAutoRefreshAppForegroundedNotification
  2042. @brief Tests that app foreground notification triggers the scheduling of an automatic token
  2043. refresh task.
  2044. */
  2045. func testAutoRefreshAppForegroundedNotification() throws {
  2046. try auth.signOut()
  2047. // Enable auto refresh
  2048. enableAutoTokenRefresh()
  2049. // Sign in a user.
  2050. try waitForSignInWithAccessToken()
  2051. // Post "UIApplicationDidBecomeActiveNotification" to trigger scheduling token refresh task.
  2052. NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
  2053. setFakeSecureTokenService(fakeAccessToken: AuthTests.kNewAccessToken)
  2054. // Verify that the current user's access token is the "old" access token before automatic
  2055. // token refresh.
  2056. XCTAssertEqual(AuthTests.kAccessToken, auth.currentUser?.rawAccessToken())
  2057. // Execute saved token refresh task.
  2058. let expectation = self.expectation(description: #function)
  2059. kAuthGlobalWorkQueue.async {
  2060. XCTAssertNotNil(self.authDispatcherCallback)
  2061. self.authDispatcherCallback?()
  2062. expectation.fulfill()
  2063. }
  2064. waitForExpectations(timeout: 5)
  2065. waitForAuthGlobalWorkQueueDrain()
  2066. // Time for callback to run.
  2067. RPCBaseTests.waitSleep()
  2068. // Verify that current user's access token is the "new" access token provided in the mock
  2069. // secure token response during automatic token refresh.
  2070. XCTAssertEqual(AuthTests.kNewAccessToken, auth.currentUser?.rawAccessToken())
  2071. }
  2072. #endif
  2073. // MARK: Application Delegate tests.
  2074. #if os(iOS)
  2075. func testAppDidRegisterForRemoteNotifications_APNSTokenUpdated() {
  2076. class FakeAuthTokenManager: AuthAPNSTokenManager {
  2077. override var token: AuthAPNSToken? {
  2078. get {
  2079. return tokenStore
  2080. }
  2081. set(setToken) {
  2082. tokenStore = setToken
  2083. }
  2084. }
  2085. }
  2086. let apnsToken = Data()
  2087. auth.tokenManager = FakeAuthTokenManager(withApplication: UIApplication.shared)
  2088. auth.application(UIApplication.shared,
  2089. didRegisterForRemoteNotificationsWithDeviceToken: apnsToken)
  2090. XCTAssertEqual(auth.tokenManager.token?.data, apnsToken)
  2091. XCTAssertEqual(auth.tokenManager.token?.type, .unknown)
  2092. }
  2093. func testAppDidFailToRegisterForRemoteNotifications_TokenManagerCancels() {
  2094. class FakeAuthTokenManager: AuthAPNSTokenManager {
  2095. var cancelled = false
  2096. override func cancel(withError error: Error) {
  2097. cancelled = true
  2098. }
  2099. }
  2100. let error = NSError(domain: "AuthTests", code: -1)
  2101. let fakeTokenManager = FakeAuthTokenManager(withApplication: UIApplication.shared)
  2102. auth.tokenManager = fakeTokenManager
  2103. XCTAssertFalse(fakeTokenManager.cancelled)
  2104. auth.application(UIApplication.shared,
  2105. didFailToRegisterForRemoteNotificationsWithError: error)
  2106. XCTAssertTrue(fakeTokenManager.cancelled)
  2107. }
  2108. func testAppDidReceiveRemoteNotificationWithCompletion_NotificationManagerHandleCanNotification() {
  2109. class FakeNotificationManager: AuthNotificationManager {
  2110. var canHandled = false
  2111. override func canHandle(notification: [AnyHashable: Any]) -> Bool {
  2112. canHandled = true
  2113. return true
  2114. }
  2115. }
  2116. let notification = ["test": ""]
  2117. let fakeKeychain = AuthKeychainServices(
  2118. service: "AuthTests",
  2119. storage: FakeAuthKeychainStorage()
  2120. )
  2121. let appCredentialManager = AuthAppCredentialManager(withKeychain: fakeKeychain)
  2122. let fakeNotificationManager = FakeNotificationManager(withApplication: UIApplication.shared,
  2123. appCredentialManager: appCredentialManager)
  2124. auth.notificationManager = fakeNotificationManager
  2125. XCTAssertFalse(fakeNotificationManager.canHandled)
  2126. auth.application(UIApplication.shared,
  2127. didReceiveRemoteNotification: notification) { _ in
  2128. }
  2129. XCTAssertTrue(fakeNotificationManager.canHandled)
  2130. }
  2131. func testAppOpenURL_AuthPresenterCanHandleURL() throws {
  2132. class FakeURLPresenter: AuthURLPresenter {
  2133. var canHandled = false
  2134. override func canHandle(url: URL) -> Bool {
  2135. canHandled = true
  2136. return true
  2137. }
  2138. }
  2139. let url = try XCTUnwrap(URL(string: "https://localhost"))
  2140. let fakeURLPresenter = FakeURLPresenter()
  2141. auth.authURLPresenter = fakeURLPresenter
  2142. XCTAssertFalse(fakeURLPresenter.canHandled)
  2143. XCTAssertTrue(auth.application(UIApplication.shared, open: url, options: [:]))
  2144. XCTAssertTrue(fakeURLPresenter.canHandled)
  2145. }
  2146. #endif // os(iOS)
  2147. // MARK: Interoperability Tests
  2148. func testComponentsRegistered() throws {
  2149. // Verify that the components are registered properly. Check the count, because any time a new
  2150. // component is added it should be added to the test suite as well.
  2151. XCTAssertEqual(AuthComponent.componentsToRegister().count, 1)
  2152. // TODO: Can/should we do something like?
  2153. // XCTAssert(component.protocol == @protocol(FIRAuthInterop));
  2154. }
  2155. // MARK: Helper Functions
  2156. private func enableAutoTokenRefresh() {
  2157. let expectation = self.expectation(description: #function)
  2158. auth.getToken(forcingRefresh: false) { token, error in
  2159. expectation.fulfill()
  2160. }
  2161. waitForExpectations(timeout: 5)
  2162. }
  2163. private func waitForSignInWithAccessToken(fakeAccessToken: String = kAccessToken) throws {
  2164. let kRefreshToken = "fakeRefreshToken"
  2165. let expectation = self.expectation(description: #function)
  2166. setFakeGetAccountProvider()
  2167. setFakeSecureTokenService()
  2168. // 1. Set up respondBlock to test request and send it to generate a fake response.
  2169. rpcIssuer.respondBlock = {
  2170. // 2. Validate the created Request instance.
  2171. let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyPasswordRequest)
  2172. XCTAssertEqual(request.email, self.kEmail)
  2173. XCTAssertEqual(request.password, self.kFakePassword)
  2174. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  2175. XCTAssertTrue(request.returnSecureToken)
  2176. // 3. Send the response from the fake backend.
  2177. try self.rpcIssuer.respond(withJSON: ["idToken": fakeAccessToken,
  2178. "email": self.kEmail,
  2179. "isNewUser": true,
  2180. "expiresIn": "3600",
  2181. "refreshToken": kRefreshToken])
  2182. }
  2183. auth?.signIn(withEmail: kEmail, password: kFakePassword) { authResult, error in
  2184. // 4. After the response triggers the callback, verify the returned result.
  2185. XCTAssertTrue(Thread.isMainThread)
  2186. guard let user = authResult?.user else {
  2187. XCTFail("authResult.user is missing")
  2188. return
  2189. }
  2190. XCTAssertEqual(user.refreshToken, kRefreshToken)
  2191. XCTAssertFalse(user.isAnonymous)
  2192. XCTAssertEqual(user.email, self.kEmail)
  2193. guard let additionalUserInfo = authResult?.additionalUserInfo else {
  2194. XCTFail("authResult.additionalUserInfo is missing")
  2195. return
  2196. }
  2197. XCTAssertFalse(additionalUserInfo.isNewUser)
  2198. XCTAssertEqual(additionalUserInfo.providerID, EmailAuthProvider.id)
  2199. XCTAssertNil(error)
  2200. expectation.fulfill()
  2201. }
  2202. waitForExpectations(timeout: 5)
  2203. assertUser(auth?.currentUser)
  2204. }
  2205. private func assertUser(_ user: User?) {
  2206. guard let user = user else {
  2207. XCTFail("authResult.additionalUserInfo is missing")
  2208. return
  2209. }
  2210. XCTAssertEqual(user.uid, kLocalID)
  2211. XCTAssertEqual(user.displayName, kDisplayName)
  2212. XCTAssertEqual(user.email, kEmail)
  2213. XCTAssertFalse(user.isAnonymous)
  2214. XCTAssertEqual(user.providerData.count, 1)
  2215. }
  2216. private func assertUserAnonymous(_ user: User?) {
  2217. guard let user = user else {
  2218. XCTFail("authResult.additionalUserInfo is missing")
  2219. return
  2220. }
  2221. XCTAssertEqual(user.uid, kLocalID)
  2222. XCTAssertNil(user.email)
  2223. XCTAssertNil(user.displayName)
  2224. XCTAssertTrue(user.isAnonymous)
  2225. XCTAssertEqual(user.providerData.count, 0)
  2226. }
  2227. }