AuthTests.swift 105 KB

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