AuthTests.swift 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449
  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 an 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 adress. This error occurs on the client side, so there is no need to fake an RPC
  1377. 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. let listener = { listenerAuth, user in
  1858. XCTAssertTrue(Thread.isMainThread)
  1859. XCTAssertEqual(auth, listenerAuth)
  1860. XCTAssertEqual(user, auth.currentUser)
  1861. if shouldHaveUser {
  1862. XCTAssertNotNil(user)
  1863. } else {
  1864. XCTAssertNil(user)
  1865. }
  1866. // `expectation` being nil means the listener is not expected to be fired at this moment.
  1867. XCTAssertNotNil(expectation)
  1868. expectation?.fulfill()
  1869. }
  1870. try auth.signOut()
  1871. // Listener should fire immediately when attached.
  1872. expectation = self.expectation(description: "initial")
  1873. shouldHaveUser = false
  1874. let handle = auth.addIDTokenDidChangeListener(listener)
  1875. waitForExpectations(timeout: 5)
  1876. expectation = nil
  1877. // Listener should fire for signing in. Expectation is waited on in
  1878. // waitForSignInWithAccessToken.
  1879. expectation = self.expectation(description: "sign-in")
  1880. shouldHaveUser = true
  1881. try waitForSignInWithAccessToken()
  1882. // Listener should not fire for signing in again.
  1883. expectation = nil
  1884. shouldHaveUser = true
  1885. try waitForSignInWithAccessToken()
  1886. // Listener should fire for signing in again as the same user with another access token.
  1887. expectation = self.expectation(description: "sign-in")
  1888. shouldHaveUser = true
  1889. try waitForSignInWithAccessToken(fakeAccessToken: AuthTests.kNewAccessToken)
  1890. // Listener should fire for signing out.
  1891. expectation = self.expectation(description: "sign-out")
  1892. shouldHaveUser = false
  1893. try auth.signOut()
  1894. waitForExpectations(timeout: 5)
  1895. // Listener should no longer fire once detached.
  1896. expectation = nil
  1897. auth.removeStateDidChangeListener(handle)
  1898. try waitForSignInWithAccessToken()
  1899. }
  1900. /** @fn testUseEmulator
  1901. @brief Tests the @c useEmulatorWithHost:port: method.
  1902. */
  1903. func testUseEmulator() throws {
  1904. auth.useEmulator(withHost: "host", port: 12345)
  1905. XCTAssertEqual("host:12345", auth.requestConfiguration.emulatorHostAndPort)
  1906. #if os(iOS)
  1907. let settings = try XCTUnwrap(auth.settings)
  1908. XCTAssertTrue(settings.isAppVerificationDisabledForTesting)
  1909. #endif
  1910. }
  1911. /** @fn testUseEmulatorNeverCalled
  1912. @brief Tests that the emulatorHostAndPort stored in @c FIRAuthRequestConfiguration is nil if the
  1913. @c useEmulatorWithHost:port: is not called.
  1914. */
  1915. func testUseEmulatorNeverCalled() throws {
  1916. XCTAssertNil(auth.requestConfiguration.emulatorHostAndPort)
  1917. #if os(iOS)
  1918. let settings = try XCTUnwrap(auth.settings)
  1919. XCTAssertFalse(settings.isAppVerificationDisabledForTesting)
  1920. #endif
  1921. }
  1922. /** @fn testUseEmulatorIPv6Address
  1923. @brief Tests the @c useEmulatorWithHost:port: method with an IPv6 host address.
  1924. */
  1925. func testUseEmulatorIPv6Address() throws {
  1926. auth.useEmulator(withHost: "::1", port: 12345)
  1927. XCTAssertEqual("[::1]:12345", auth.requestConfiguration.emulatorHostAndPort)
  1928. #if os(iOS)
  1929. let settings = try XCTUnwrap(auth.settings)
  1930. XCTAssertTrue(settings.isAppVerificationDisabledForTesting)
  1931. #endif
  1932. }
  1933. // MARK: Automatic Token Refresh Tests.
  1934. /** @fn testAutomaticTokenRefresh
  1935. @brief Tests a successful flow to automatically refresh tokens for a signed in user.
  1936. */
  1937. func testAutomaticTokenRefresh() throws {
  1938. try auth.signOut()
  1939. // Enable auto refresh
  1940. enableAutoTokenRefresh()
  1941. // Sign in a user.
  1942. try waitForSignInWithAccessToken()
  1943. setFakeSecureTokenService(fakeAccessToken: AuthTests.kNewAccessToken)
  1944. // Verify that the current user's access token is the "old" access token before automatic token
  1945. // refresh.
  1946. XCTAssertEqual(AuthTests.kAccessToken, auth.currentUser?.rawAccessToken())
  1947. // Execute saved token refresh task.
  1948. let expectation = self.expectation(description: #function)
  1949. kAuthGlobalWorkQueue.async {
  1950. XCTAssertNotNil(self.authDispatcherCallback)
  1951. self.authDispatcherCallback?()
  1952. expectation.fulfill()
  1953. }
  1954. waitForExpectations(timeout: 5)
  1955. waitForAuthGlobalWorkQueueDrain()
  1956. // Verify that current user's access token is the "new" access token provided in the mock secure
  1957. // token response during automatic token refresh.
  1958. RPCBaseTests.waitSleep()
  1959. XCTAssertEqual(AuthTests.kNewAccessToken, auth.currentUser?.rawAccessToken())
  1960. }
  1961. /** @fn testAutomaticTokenRefreshInvalidTokenFailure
  1962. @brief Tests an unsuccessful flow to auto refresh tokens with an "invalid token" error.
  1963. This error should cause the user to be signed out.
  1964. */
  1965. func testAutomaticTokenRefreshInvalidTokenFailure() throws {
  1966. try auth.signOut()
  1967. // Enable auto refresh
  1968. enableAutoTokenRefresh()
  1969. // Sign in a user.
  1970. try waitForSignInWithAccessToken()
  1971. // Set up expectation for secureToken RPC made by a failed attempt to refresh tokens.
  1972. rpcIssuer.secureTokenErrorString = "INVALID_ID_TOKEN"
  1973. // Verify that the current user's access token is the "old" access token before automatic token
  1974. // refresh.
  1975. XCTAssertEqual(AuthTests.kAccessToken, auth.currentUser?.rawAccessToken())
  1976. // Execute saved token refresh task.
  1977. let expectation = self.expectation(description: #function)
  1978. kAuthGlobalWorkQueue.async {
  1979. XCTAssertNotNil(self.authDispatcherCallback)
  1980. self.authDispatcherCallback?()
  1981. expectation.fulfill()
  1982. }
  1983. waitForExpectations(timeout: 5)
  1984. waitForAuthGlobalWorkQueueDrain()
  1985. // Verify that the user is nil after failed attempt to refresh tokens caused signed out.
  1986. RPCBaseTests.waitSleep()
  1987. XCTAssertNil(auth.currentUser)
  1988. }
  1989. /** @fn testAutomaticTokenRefreshRetry
  1990. @brief Tests that a retry is attempted for a automatic token refresh task (which is not due to
  1991. invalid tokens). The initial attempt to refresh the access token fails, but the second
  1992. attempt is successful.
  1993. */
  1994. func testAutomaticTokenRefreshRetry() throws {
  1995. try auth.signOut()
  1996. // Enable auto refresh
  1997. enableAutoTokenRefresh()
  1998. // Sign in a user.
  1999. try waitForSignInWithAccessToken()
  2000. // Set up expectation for secureToken RPC made by a failed attempt to refresh tokens.
  2001. rpcIssuer.secureTokenNetworkError = NSError(domain: "ERROR", code: -1)
  2002. // Execute saved token refresh task.
  2003. let expectation = self.expectation(description: #function)
  2004. kAuthGlobalWorkQueue.async {
  2005. XCTAssertNotNil(self.authDispatcherCallback)
  2006. self.authDispatcherCallback?()
  2007. self.authDispatcherCallback = nil
  2008. expectation.fulfill()
  2009. }
  2010. waitForExpectations(timeout: 5)
  2011. waitForAuthGlobalWorkQueueDrain()
  2012. rpcIssuer.secureTokenNetworkError = nil
  2013. setFakeSecureTokenService(fakeAccessToken: AuthTests.kNewAccessToken)
  2014. // The old access token should still be the current user's access token and not the new access
  2015. // token (kNewAccessToken).
  2016. XCTAssertEqual(AuthTests.kAccessToken, auth.currentUser?.rawAccessToken())
  2017. // Execute saved token refresh task.
  2018. let expectation2 = self.expectation(description: "dispatchAfterExpectation")
  2019. kAuthGlobalWorkQueue.async {
  2020. RPCBaseTests.waitSleep()
  2021. XCTAssertNotNil(self.authDispatcherCallback)
  2022. self.authDispatcherCallback?()
  2023. expectation2.fulfill()
  2024. }
  2025. waitForExpectations(timeout: 5)
  2026. waitForAuthGlobalWorkQueueDrain()
  2027. // Time for callback to run.
  2028. RPCBaseTests.waitSleep()
  2029. // Verify that current user's access token is the "new" access token provided in the mock secure
  2030. // token response during automatic token refresh.
  2031. XCTAssertEqual(AuthTests.kNewAccessToken, auth.currentUser?.rawAccessToken())
  2032. }
  2033. #if os(iOS)
  2034. /** @fn testAutoRefreshAppForegroundedNotification
  2035. @brief Tests that app foreground notification triggers the scheduling of an automatic token
  2036. refresh task.
  2037. */
  2038. func testAutoRefreshAppForegroundedNotification() throws {
  2039. try auth.signOut()
  2040. // Enable auto refresh
  2041. enableAutoTokenRefresh()
  2042. // Sign in a user.
  2043. try waitForSignInWithAccessToken()
  2044. // Post "UIApplicationDidBecomeActiveNotification" to trigger scheduling token refresh task.
  2045. NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
  2046. setFakeSecureTokenService(fakeAccessToken: AuthTests.kNewAccessToken)
  2047. // Verify that the current user's access token is the "old" access token before automatic
  2048. // token refresh.
  2049. XCTAssertEqual(AuthTests.kAccessToken, auth.currentUser?.rawAccessToken())
  2050. // Execute saved token refresh task.
  2051. let expectation = self.expectation(description: #function)
  2052. kAuthGlobalWorkQueue.async {
  2053. XCTAssertNotNil(self.authDispatcherCallback)
  2054. self.authDispatcherCallback?()
  2055. expectation.fulfill()
  2056. }
  2057. waitForExpectations(timeout: 5)
  2058. waitForAuthGlobalWorkQueueDrain()
  2059. // Time for callback to run.
  2060. RPCBaseTests.waitSleep()
  2061. // Verify that current user's access token is the "new" access token provided in the mock
  2062. // secure token response during automatic token refresh.
  2063. XCTAssertEqual(AuthTests.kNewAccessToken, auth.currentUser?.rawAccessToken())
  2064. }
  2065. #endif
  2066. // MARK: Application Delegate tests.
  2067. #if os(iOS)
  2068. func testAppDidRegisterForRemoteNotifications_APNSTokenUpdated() {
  2069. class FakeAuthTokenManager: AuthAPNSTokenManager {
  2070. override var token: AuthAPNSToken? {
  2071. get {
  2072. return tokenStore
  2073. }
  2074. set(setToken) {
  2075. tokenStore = setToken
  2076. }
  2077. }
  2078. }
  2079. let apnsToken = Data()
  2080. auth.tokenManager = FakeAuthTokenManager(withApplication: UIApplication.shared)
  2081. auth.application(UIApplication.shared,
  2082. didRegisterForRemoteNotificationsWithDeviceToken: apnsToken)
  2083. XCTAssertEqual(auth.tokenManager.token?.data, apnsToken)
  2084. XCTAssertEqual(auth.tokenManager.token?.type, .unknown)
  2085. }
  2086. func testAppDidFailToRegisterForRemoteNotifications_TokenManagerCancels() {
  2087. class FakeAuthTokenManager: AuthAPNSTokenManager {
  2088. var cancelled = false
  2089. override func cancel(withError error: Error) {
  2090. cancelled = true
  2091. }
  2092. }
  2093. let error = NSError(domain: "AuthTests", code: -1)
  2094. let fakeTokenManager = FakeAuthTokenManager(withApplication: UIApplication.shared)
  2095. auth.tokenManager = fakeTokenManager
  2096. XCTAssertFalse(fakeTokenManager.cancelled)
  2097. auth.application(UIApplication.shared,
  2098. didFailToRegisterForRemoteNotificationsWithError: error)
  2099. XCTAssertTrue(fakeTokenManager.cancelled)
  2100. }
  2101. func testAppDidReceiveRemoteNotificationWithCompletion_NotificationManagerHandleCanNotification() {
  2102. class FakeNotificationManager: AuthNotificationManager {
  2103. var canHandled = false
  2104. override func canHandle(notification: [AnyHashable: Any]) -> Bool {
  2105. canHandled = true
  2106. return true
  2107. }
  2108. }
  2109. let notification = ["test": ""]
  2110. let fakeKeychain = AuthKeychainServices(
  2111. service: "AuthTests",
  2112. storage: FakeAuthKeychainStorage()
  2113. )
  2114. let appCredentialManager = AuthAppCredentialManager(withKeychain: fakeKeychain)
  2115. let fakeNotificationManager = FakeNotificationManager(withApplication: UIApplication.shared,
  2116. appCredentialManager: appCredentialManager)
  2117. auth.notificationManager = fakeNotificationManager
  2118. XCTAssertFalse(fakeNotificationManager.canHandled)
  2119. auth.application(UIApplication.shared,
  2120. didReceiveRemoteNotification: notification) { _ in
  2121. }
  2122. XCTAssertTrue(fakeNotificationManager.canHandled)
  2123. }
  2124. func testAppOpenURL_AuthPresenterCanHandleURL() throws {
  2125. class FakeURLPresenter: AuthURLPresenter {
  2126. var canHandled = false
  2127. override func canHandle(url: URL) -> Bool {
  2128. canHandled = true
  2129. return true
  2130. }
  2131. }
  2132. let url = try XCTUnwrap(URL(string: "https://localhost"))
  2133. let fakeURLPresenter = FakeURLPresenter()
  2134. auth.authURLPresenter = fakeURLPresenter
  2135. XCTAssertFalse(fakeURLPresenter.canHandled)
  2136. XCTAssertTrue(auth.application(UIApplication.shared, open: url, options: [:]))
  2137. XCTAssertTrue(fakeURLPresenter.canHandled)
  2138. }
  2139. #endif // os(iOS)
  2140. // MARK: Interoperability Tests
  2141. func testComponentsRegistered() throws {
  2142. // Verify that the components are registered properly. Check the count, because any time a new
  2143. // component is added it should be added to the test suite as well.
  2144. XCTAssertEqual(AuthComponent.componentsToRegister().count, 1)
  2145. // TODO: Can/should we do something like?
  2146. // XCTAssert(component.protocol == @protocol(FIRAuthInterop));
  2147. }
  2148. // MARK: Helper Functions
  2149. private func enableAutoTokenRefresh() {
  2150. let expectation = self.expectation(description: #function)
  2151. auth.getToken(forcingRefresh: false) { token, error in
  2152. expectation.fulfill()
  2153. }
  2154. waitForExpectations(timeout: 5)
  2155. }
  2156. private func waitForSignInWithAccessToken(fakeAccessToken: String = kAccessToken) throws {
  2157. let kRefreshToken = "fakeRefreshToken"
  2158. let expectation = self.expectation(description: #function)
  2159. setFakeGetAccountProvider()
  2160. setFakeSecureTokenService()
  2161. // 1. Set up respondBlock to test request and send it to generate a fake response.
  2162. rpcIssuer.respondBlock = {
  2163. // 2. Validate the created Request instance.
  2164. let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyPasswordRequest)
  2165. XCTAssertEqual(request.email, self.kEmail)
  2166. XCTAssertEqual(request.password, self.kFakePassword)
  2167. XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
  2168. XCTAssertTrue(request.returnSecureToken)
  2169. // 3. Send the response from the fake backend.
  2170. try self.rpcIssuer.respond(withJSON: ["idToken": fakeAccessToken,
  2171. "email": self.kEmail,
  2172. "isNewUser": true,
  2173. "expiresIn": "3600",
  2174. "refreshToken": kRefreshToken])
  2175. }
  2176. auth?.signIn(withEmail: kEmail, password: kFakePassword) { authResult, error in
  2177. // 4. After the response triggers the callback, verify the returned result.
  2178. XCTAssertTrue(Thread.isMainThread)
  2179. guard let user = authResult?.user else {
  2180. XCTFail("authResult.user is missing")
  2181. return
  2182. }
  2183. XCTAssertEqual(user.refreshToken, kRefreshToken)
  2184. XCTAssertFalse(user.isAnonymous)
  2185. XCTAssertEqual(user.email, self.kEmail)
  2186. guard let additionalUserInfo = authResult?.additionalUserInfo else {
  2187. XCTFail("authResult.additionalUserInfo is missing")
  2188. return
  2189. }
  2190. XCTAssertFalse(additionalUserInfo.isNewUser)
  2191. XCTAssertEqual(additionalUserInfo.providerID, EmailAuthProvider.id)
  2192. XCTAssertNil(error)
  2193. expectation.fulfill()
  2194. }
  2195. waitForExpectations(timeout: 5)
  2196. assertUser(auth?.currentUser)
  2197. }
  2198. private func assertUser(_ user: User?) {
  2199. guard let user = user else {
  2200. XCTFail("authResult.additionalUserInfo is missing")
  2201. return
  2202. }
  2203. XCTAssertEqual(user.uid, kLocalID)
  2204. XCTAssertEqual(user.displayName, kDisplayName)
  2205. XCTAssertEqual(user.email, kEmail)
  2206. XCTAssertFalse(user.isAnonymous)
  2207. XCTAssertEqual(user.providerData.count, 1)
  2208. }
  2209. private func assertUserAnonymous(_ user: User?) {
  2210. guard let user = user else {
  2211. XCTFail("authResult.additionalUserInfo is missing")
  2212. return
  2213. }
  2214. XCTAssertEqual(user.uid, kLocalID)
  2215. XCTAssertNil(user.email)
  2216. XCTAssertNil(user.displayName)
  2217. XCTAssertTrue(user.isAnonymous)
  2218. XCTAssertEqual(user.providerData.count, 0)
  2219. }
  2220. }