AuthenticationControllerTests.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  1. const sinon = require('sinon')
  2. const chai = require('chai')
  3. const { expect } = chai
  4. const modulePath =
  5. '../../../../app/src/Features/Authentication/AuthenticationController.js'
  6. const SandboxedModule = require('sandboxed-module')
  7. const tk = require('timekeeper')
  8. const MockRequest = require('../helpers/MockRequest')
  9. const MockResponse = require('../helpers/MockResponse')
  10. const { ObjectId } = require('mongodb')
  11. describe('AuthenticationController', function() {
  12. beforeEach(function() {
  13. tk.freeze(Date.now())
  14. this.UserModel = { findOne: sinon.stub() }
  15. this.httpAuthUsers = {
  16. 'valid-test-user': Math.random()
  17. .toString(16)
  18. .slice(2)
  19. }
  20. this.AuthenticationController = SandboxedModule.require(modulePath, {
  21. globals: {
  22. console: console
  23. },
  24. requires: {
  25. '../Helpers/AsyncFormHelper': (this.AsyncFormHelper = {
  26. redirect: sinon.stub()
  27. }),
  28. '../../infrastructure/RequestContentTypeDetection': {
  29. acceptsJson: (this.acceptsJson = sinon.stub().returns(false))
  30. },
  31. './AuthenticationManager': (this.AuthenticationManager = {}),
  32. '../User/UserUpdater': (this.UserUpdater = {
  33. updateUser: sinon.stub()
  34. }),
  35. '@overleaf/metrics': (this.Metrics = { inc: sinon.stub() }),
  36. '../Security/LoginRateLimiter': (this.LoginRateLimiter = {
  37. processLoginRequest: sinon.stub(),
  38. recordSuccessfulLogin: sinon.stub()
  39. }),
  40. '../User/UserHandler': (this.UserHandler = {
  41. setupLoginData: sinon.stub()
  42. }),
  43. '../Analytics/AnalyticsManager': (this.AnalyticsManager = {
  44. recordEvent: sinon.stub(),
  45. identifyUser: sinon.stub()
  46. }),
  47. '../../infrastructure/SessionStoreManager': (this.SessionStoreManager = {}),
  48. 'logger-sharelatex': (this.logger = {
  49. log: sinon.stub(),
  50. warn: sinon.stub(),
  51. error: sinon.stub(),
  52. err: sinon.stub()
  53. }),
  54. 'settings-sharelatex': (this.Settings = {
  55. siteUrl: 'http://www.foo.bar',
  56. httpAuthUsers: this.httpAuthUsers
  57. }),
  58. passport: (this.passport = {
  59. authenticate: sinon.stub().returns(sinon.stub())
  60. }),
  61. '../User/UserSessionsManager': (this.UserSessionsManager = {
  62. trackSession: sinon.stub(),
  63. untrackSession: sinon.stub(),
  64. revokeAllUserSessions: sinon.stub().callsArgWith(1, null)
  65. }),
  66. '../../infrastructure/Modules': (this.Modules = {
  67. hooks: { fire: sinon.stub().yields(null, []) }
  68. }),
  69. '../Notifications/NotificationsBuilder': (this.NotificationsBuilder = {
  70. ipMatcherAffiliation: sinon.stub()
  71. }),
  72. '../../models/User': { User: this.UserModel },
  73. '../../../../modules/oauth2-server/app/src/Oauth2Server': (this.Oauth2Server = {
  74. Request: sinon.stub(),
  75. Response: sinon.stub(),
  76. server: {
  77. authenticate: sinon.stub()
  78. }
  79. }),
  80. '../Helpers/UrlHelper': (this.UrlHelper = {
  81. getSafeRedirectPath: sinon.stub()
  82. })
  83. }
  84. })
  85. this.UrlHelper.getSafeRedirectPath
  86. .withArgs('https://evil.com')
  87. .returns(undefined)
  88. this.UrlHelper.getSafeRedirectPath.returnsArg(0)
  89. this.user = {
  90. _id: ObjectId(),
  91. email: (this.email = 'USER@example.com'),
  92. first_name: 'bob',
  93. last_name: 'brown',
  94. referal_id: 1234,
  95. isAdmin: false
  96. }
  97. this.password = 'banana'
  98. this.req = new MockRequest()
  99. this.res = new MockResponse()
  100. this.callback = sinon.stub()
  101. this.next = sinon.stub()
  102. })
  103. afterEach(function() {
  104. tk.reset()
  105. })
  106. describe('validateAdmin', function() {
  107. beforeEach(function() {
  108. this.Settings.adminDomains = ['good.example.com']
  109. this.goodAdmin = {
  110. email: 'alice@good.example.com',
  111. isAdmin: true
  112. }
  113. this.badAdmin = {
  114. email: 'beatrice@bad.example.com',
  115. isAdmin: true
  116. }
  117. this.normalUser = {
  118. email: 'claire@whatever.example.com',
  119. isAdmin: false
  120. }
  121. })
  122. it('should skip when adminDomains are not configured', function(done) {
  123. this.Settings.adminDomains = []
  124. this.AuthenticationController.getSessionUser = sinon
  125. .stub()
  126. .returns(this.normalUser)
  127. this.AuthenticationController.validateAdmin(this.req, this.res, err => {
  128. this.AuthenticationController.getSessionUser.called.should.equal(false)
  129. expect(err).to.not.exist
  130. done()
  131. })
  132. })
  133. it('should skip non-admin user', function(done) {
  134. this.AuthenticationController.getSessionUser = sinon
  135. .stub()
  136. .returns(this.normalUser)
  137. this.AuthenticationController.validateAdmin(this.req, this.res, err => {
  138. this.AuthenticationController.getSessionUser.called.should.equal(true)
  139. expect(err).to.not.exist
  140. done()
  141. })
  142. })
  143. it('should permit an admin with the right doman', function(done) {
  144. this.AuthenticationController.getSessionUser = sinon
  145. .stub()
  146. .returns(this.goodAdmin)
  147. this.AuthenticationController.validateAdmin(this.req, this.res, err => {
  148. this.AuthenticationController.getSessionUser.called.should.equal(true)
  149. expect(err).to.not.exist
  150. done()
  151. })
  152. })
  153. it('should block an admin with a missing email', function(done) {
  154. this.AuthenticationController.getSessionUser = sinon
  155. .stub()
  156. .returns({ isAdmin: true })
  157. this.AuthenticationController.validateAdmin(this.req, this.res, err => {
  158. this.AuthenticationController.getSessionUser.called.should.equal(true)
  159. expect(err).to.exist
  160. done()
  161. })
  162. })
  163. it('should block an admin with a bad domain', function(done) {
  164. this.AuthenticationController.getSessionUser = sinon
  165. .stub()
  166. .returns(this.badAdmin)
  167. this.AuthenticationController.validateAdmin(this.req, this.res, err => {
  168. this.AuthenticationController.getSessionUser.called.should.equal(true)
  169. expect(err).to.exist
  170. done()
  171. })
  172. })
  173. })
  174. describe('isUserLoggedIn', function() {
  175. beforeEach(function() {
  176. this.stub = sinon.stub(this.AuthenticationController, 'getLoggedInUserId')
  177. })
  178. afterEach(function() {
  179. this.stub.restore()
  180. })
  181. it('should do the right thing in all cases', function() {
  182. this.AuthenticationController.getLoggedInUserId.returns('some_id')
  183. expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal(
  184. true
  185. )
  186. this.AuthenticationController.getLoggedInUserId.returns(null)
  187. expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal(
  188. false
  189. )
  190. this.AuthenticationController.getLoggedInUserId.returns(false)
  191. expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal(
  192. false
  193. )
  194. this.AuthenticationController.getLoggedInUserId.returns(undefined)
  195. expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal(
  196. false
  197. )
  198. })
  199. })
  200. describe('setInSessionUser', function() {
  201. beforeEach(function() {
  202. this.user = {
  203. _id: 'id',
  204. first_name: 'a',
  205. last_name: 'b',
  206. email: 'c'
  207. }
  208. this.AuthenticationController.getSessionUser = sinon
  209. .stub()
  210. .returns(this.user)
  211. })
  212. it('should update the right properties', function() {
  213. this.AuthenticationController.setInSessionUser(this.req, {
  214. first_name: 'new_first_name',
  215. email: 'new_email'
  216. })
  217. const expectedUser = {
  218. _id: 'id',
  219. first_name: 'new_first_name',
  220. last_name: 'b',
  221. email: 'new_email'
  222. }
  223. expect(this.user).to.deep.equal(expectedUser)
  224. expect(this.user).to.deep.equal(expectedUser)
  225. })
  226. })
  227. describe('passportLogin', function() {
  228. beforeEach(function() {
  229. this.info = null
  230. this.req.login = sinon.stub().callsArgWith(1, null)
  231. this.res.json = sinon.stub()
  232. this.req.session = {
  233. passport: { user: this.user },
  234. postLoginRedirect: '/path/to/redir/to'
  235. }
  236. this.req.session.destroy = sinon.stub().callsArgWith(0, null)
  237. this.req.session.save = sinon.stub().callsArgWith(0, null)
  238. this.req.sessionStore = { generate: sinon.stub() }
  239. this.AuthenticationController.finishLogin = sinon.stub()
  240. this.passport.authenticate.callsArgWith(1, null, this.user, this.info)
  241. this.err = new Error('woops')
  242. })
  243. it('should call passport.authenticate', function() {
  244. this.AuthenticationController.passportLogin(this.req, this.res, this.next)
  245. this.passport.authenticate.callCount.should.equal(1)
  246. })
  247. describe('when authenticate produces an error', function() {
  248. beforeEach(function() {
  249. this.passport.authenticate.callsArgWith(1, this.err)
  250. })
  251. it('should return next with an error', function() {
  252. this.AuthenticationController.passportLogin(
  253. this.req,
  254. this.res,
  255. this.next
  256. )
  257. this.next.calledWith(this.err).should.equal(true)
  258. })
  259. })
  260. describe('when authenticate produces a user', function() {
  261. beforeEach(function() {
  262. this.req.session.postLoginRedirect = 'some_redirect'
  263. this.passport.authenticate.callsArgWith(1, null, this.user, this.info)
  264. })
  265. afterEach(function() {
  266. delete this.req.session.postLoginRedirect
  267. })
  268. it('should call finishLogin', function() {
  269. this.AuthenticationController.passportLogin(
  270. this.req,
  271. this.res,
  272. this.next
  273. )
  274. this.AuthenticationController.finishLogin.callCount.should.equal(1)
  275. this.AuthenticationController.finishLogin
  276. .calledWith(this.user)
  277. .should.equal(true)
  278. })
  279. })
  280. describe('when authenticate does not produce a user', function() {
  281. beforeEach(function() {
  282. this.info = { text: 'a', type: 'b' }
  283. this.passport.authenticate.callsArgWith(1, null, false, this.info)
  284. })
  285. it('should not call finishLogin', function() {
  286. this.AuthenticationController.passportLogin(
  287. this.req,
  288. this.res,
  289. this.next
  290. )
  291. this.AuthenticationController.finishLogin.callCount.should.equal(0)
  292. })
  293. it('should not send a json response with redirect', function() {
  294. this.AuthenticationController.passportLogin(
  295. this.req,
  296. this.res,
  297. this.next
  298. )
  299. this.res.json.callCount.should.equal(1)
  300. this.res.json.calledWith({ message: this.info }).should.equal(true)
  301. expect(this.res.json.lastCall.args[0].redir != null).to.equal(false)
  302. })
  303. })
  304. })
  305. describe('doPassportLogin', function() {
  306. beforeEach(function() {
  307. this.AuthenticationController._recordFailedLogin = sinon.stub()
  308. this.AuthenticationController._recordSuccessfulLogin = sinon.stub()
  309. this.Modules.hooks.fire = sinon.stub().callsArgWith(3, null, [])
  310. // @AuthenticationController.establishUserSession = sinon.stub().callsArg(2)
  311. this.req.body = {
  312. email: this.email,
  313. password: this.password,
  314. session: {
  315. postLoginRedirect: '/path/to/redir/to'
  316. }
  317. }
  318. this.cb = sinon.stub()
  319. })
  320. describe('when the preDoPassportLogin hooks produce an info object', function() {
  321. beforeEach(function() {
  322. this.Modules.hooks.fire = sinon
  323. .stub()
  324. .callsArgWith(3, null, [null, { redir: '/somewhere' }, null])
  325. })
  326. it('should stop early and call done with this info object', function(done) {
  327. this.AuthenticationController.doPassportLogin(
  328. this.req,
  329. this.req.body.email,
  330. this.req.body.password,
  331. this.cb
  332. )
  333. this.cb.callCount.should.equal(1)
  334. this.cb
  335. .calledWith(null, false, { redir: '/somewhere' })
  336. .should.equal(true)
  337. this.LoginRateLimiter.processLoginRequest.callCount.should.equal(0)
  338. done()
  339. })
  340. })
  341. describe('when the users rate limit', function() {
  342. beforeEach(function() {
  343. this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false)
  344. })
  345. it('should block the request if the limit has been exceeded', function(done) {
  346. this.AuthenticationController.doPassportLogin(
  347. this.req,
  348. this.req.body.email,
  349. this.req.body.password,
  350. this.cb
  351. )
  352. this.cb.callCount.should.equal(1)
  353. this.cb.calledWith(null, null).should.equal(true)
  354. done()
  355. })
  356. })
  357. describe('when the user is authenticated', function() {
  358. beforeEach(function() {
  359. this.cb = sinon.stub()
  360. this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  361. this.AuthenticationManager.authenticate = sinon
  362. .stub()
  363. .callsArgWith(2, null, this.user)
  364. this.req.sessionID = Math.random()
  365. this.AuthenticationController.doPassportLogin(
  366. this.req,
  367. this.req.body.email,
  368. this.req.body.password,
  369. this.cb
  370. )
  371. })
  372. it('should attempt to authorise the user', function() {
  373. this.AuthenticationManager.authenticate
  374. .calledWith({ email: this.email.toLowerCase() }, this.password)
  375. .should.equal(true)
  376. })
  377. it("should establish the user's session", function() {
  378. this.cb.calledWith(null, this.user).should.equal(true)
  379. })
  380. })
  381. describe('when the user is not authenticated', function() {
  382. beforeEach(function() {
  383. this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  384. this.AuthenticationManager.authenticate = sinon
  385. .stub()
  386. .callsArgWith(2, null, null)
  387. this.cb = sinon.stub()
  388. this.AuthenticationController.doPassportLogin(
  389. this.req,
  390. this.req.body.email,
  391. this.req.body.password,
  392. this.cb
  393. )
  394. })
  395. it('should not establish the login', function() {
  396. this.cb.callCount.should.equal(1)
  397. this.cb.calledWith(null, false)
  398. // @res.body.should.exist
  399. expect(this.cb.lastCall.args[2]).to.contain.all.keys(['text', 'type'])
  400. })
  401. // message:
  402. // text: 'Your email or password were incorrect. Please try again',
  403. // type: 'error'
  404. it('should not setup the user data in the background', function() {
  405. this.UserHandler.setupLoginData.called.should.equal(false)
  406. })
  407. it('should record a failed login', function() {
  408. this.AuthenticationController._recordFailedLogin.called.should.equal(
  409. true
  410. )
  411. })
  412. it('should log the failed login', function() {
  413. this.logger.log
  414. .calledWith({ email: this.email.toLowerCase() }, 'failed log in')
  415. .should.equal(true)
  416. })
  417. })
  418. })
  419. describe('getLoggedInUserId', function() {
  420. beforeEach(function() {
  421. this.req = { session: {} }
  422. })
  423. it('should return the user id from the session', function() {
  424. this.user_id = '2134'
  425. this.req.session.user = { _id: this.user_id }
  426. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  427. expect(result).to.equal(this.user_id)
  428. })
  429. it('should return user for passport session', function() {
  430. this.user_id = '2134'
  431. this.req.session = {
  432. passport: {
  433. user: {
  434. _id: this.user_id
  435. }
  436. }
  437. }
  438. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  439. expect(result).to.equal(this.user_id)
  440. })
  441. it('should return null if there is no user on the session', function() {
  442. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  443. expect(result).to.equal(null)
  444. })
  445. it('should return null if there is no session', function() {
  446. this.req = {}
  447. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  448. expect(result).to.equal(null)
  449. })
  450. it('should return null if there is no req', function() {
  451. this.req = {}
  452. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  453. expect(result).to.equal(null)
  454. })
  455. })
  456. describe('requireLogin', function() {
  457. beforeEach(function() {
  458. this.user = {
  459. _id: 'user-id-123',
  460. email: 'user@sharelatex.com'
  461. }
  462. this.middleware = this.AuthenticationController.requireLogin()
  463. })
  464. describe('when the user is logged in', function() {
  465. beforeEach(function() {
  466. this.req.session = {
  467. user: (this.user = {
  468. _id: 'user-id-123',
  469. email: 'user@sharelatex.com'
  470. })
  471. }
  472. this.middleware(this.req, this.res, this.next)
  473. })
  474. it('should call the next method in the chain', function() {
  475. this.next.called.should.equal(true)
  476. })
  477. })
  478. describe('when the user is not logged in', function() {
  479. beforeEach(function() {
  480. this.req.session = {}
  481. this.AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
  482. this.req.query = {}
  483. this.middleware(this.req, this.res, this.next)
  484. })
  485. it('should redirect to the register or login page', function() {
  486. this.AuthenticationController._redirectToLoginOrRegisterPage
  487. .calledWith(this.req, this.res)
  488. .should.equal(true)
  489. })
  490. })
  491. })
  492. describe('validateUserSession', function() {
  493. beforeEach(function() {
  494. this.user = {
  495. _id: 'user-id-123',
  496. email: 'user@sharelatex.com'
  497. }
  498. this.middleware = this.AuthenticationController.validateUserSession()
  499. })
  500. describe('when the user has a session token', function() {
  501. beforeEach(function() {
  502. this.req.user = this.user
  503. this.SessionStoreManager.hasValidationToken = sinon.stub().returns(true)
  504. this.middleware(this.req, this.res, this.next)
  505. })
  506. it('should call the next method in the chain', function() {
  507. this.next.called.should.equal(true)
  508. })
  509. })
  510. describe('when the user does not have a session token', function() {
  511. beforeEach(function() {
  512. this.req.session = {
  513. user: this.user,
  514. regenerate: sinon.stub().yields()
  515. }
  516. this.req.user = this.user
  517. this.AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
  518. this.req.query = {}
  519. this.SessionStoreManager.hasValidationToken = sinon
  520. .stub()
  521. .returns(false)
  522. this.middleware(this.req, this.res, this.next)
  523. })
  524. it('should destroy the current session', function() {
  525. this.req.session.regenerate.called.should.equal(true)
  526. })
  527. it('should redirect to the register or login page', function() {
  528. this.AuthenticationController._redirectToLoginOrRegisterPage
  529. .calledWith(this.req, this.res)
  530. .should.equal(true)
  531. })
  532. })
  533. })
  534. describe('requireOauth', function() {
  535. beforeEach(function() {
  536. this.res.send = sinon.stub()
  537. this.res.status = sinon.stub().returns(this.res)
  538. this.res.sendStatus = sinon.stub()
  539. this.middleware = this.AuthenticationController.requireOauth()
  540. })
  541. describe('when Oauth2Server authenticates', function() {
  542. beforeEach(function() {
  543. this.token = {
  544. accessToken: 'token',
  545. user: 'user'
  546. }
  547. this.Oauth2Server.server.authenticate.yields(null, this.token)
  548. this.middleware(this.req, this.res, this.next)
  549. })
  550. it('should set oauth_token on request', function() {
  551. this.req.oauth_token.should.equal(this.token)
  552. })
  553. it('should set oauth on request', function() {
  554. this.req.oauth.access_token.should.equal(this.token.accessToken)
  555. })
  556. it('should set oauth_user on request', function() {
  557. this.req.oauth_user.should.equal('user')
  558. })
  559. it('should call next', function() {
  560. this.next.should.have.been.calledOnce
  561. })
  562. })
  563. describe('when Oauth2Server returns 401 error', function() {
  564. beforeEach(function() {
  565. this.Oauth2Server.server.authenticate.yields({ code: 401 })
  566. this.middleware(this.req, this.res, this.next)
  567. })
  568. it('should return 401 error', function() {
  569. this.res.status.should.have.been.calledWith(401)
  570. })
  571. it('should not call next', function() {
  572. this.next.should.have.not.been.calledOnce
  573. })
  574. })
  575. })
  576. describe('requireGlobalLogin', function() {
  577. beforeEach(function() {
  578. this.req.headers = {}
  579. this.AuthenticationController.httpAuth = sinon.stub()
  580. this.setRedirect = sinon.spy(
  581. this.AuthenticationController,
  582. 'setRedirectInSession'
  583. )
  584. })
  585. afterEach(function() {
  586. this.setRedirect.restore()
  587. })
  588. describe('with white listed url', function() {
  589. beforeEach(function() {
  590. this.AuthenticationController.addEndpointToLoginWhitelist('/login')
  591. this.req._parsedUrl.pathname = '/login'
  592. this.AuthenticationController.requireGlobalLogin(
  593. this.req,
  594. this.res,
  595. this.next
  596. )
  597. })
  598. it('should call next() directly', function() {
  599. this.next.called.should.equal(true)
  600. })
  601. })
  602. describe('with white listed url and a query string', function() {
  603. beforeEach(function() {
  604. this.AuthenticationController.addEndpointToLoginWhitelist('/login')
  605. this.req._parsedUrl.pathname = '/login'
  606. this.req.url = '/login?query=something'
  607. this.AuthenticationController.requireGlobalLogin(
  608. this.req,
  609. this.res,
  610. this.next
  611. )
  612. })
  613. it('should call next() directly', function() {
  614. this.next.called.should.equal(true)
  615. })
  616. })
  617. describe('with http auth', function() {
  618. beforeEach(function() {
  619. this.req.headers['authorization'] = 'Mock Basic Auth'
  620. this.AuthenticationController.requireGlobalLogin(
  621. this.req,
  622. this.res,
  623. this.next
  624. )
  625. })
  626. it('should pass the request onto httpAuth', function() {
  627. this.AuthenticationController.httpAuth
  628. .calledWith(this.req, this.res, this.next)
  629. .should.equal(true)
  630. })
  631. })
  632. describe('with a user session', function() {
  633. beforeEach(function() {
  634. this.req.session = { user: { mock: 'user', _id: 'some_id' } }
  635. this.AuthenticationController.requireGlobalLogin(
  636. this.req,
  637. this.res,
  638. this.next
  639. )
  640. })
  641. it('should call next() directly', function() {
  642. this.next.called.should.equal(true)
  643. })
  644. })
  645. describe('with no login credentials', function() {
  646. beforeEach(function() {
  647. this.req.session = {}
  648. this.AuthenticationController.requireGlobalLogin(
  649. this.req,
  650. this.res,
  651. this.next
  652. )
  653. })
  654. it('should have called setRedirectInSession', function() {
  655. this.setRedirect.callCount.should.equal(1)
  656. })
  657. it('should redirect to the /login page', function() {
  658. this.res.redirectedTo.should.equal('/login')
  659. })
  660. })
  661. })
  662. describe('httpAuth', function() {
  663. describe('with http auth', function() {
  664. it('should error with incorrect user', function(done) {
  665. this.req.headers = {
  666. authorization: `Basic ${Buffer.from('user:nope').toString('base64')}`
  667. }
  668. this.req.end = status => {
  669. expect(status).to.equal('Unauthorized')
  670. done()
  671. }
  672. this.AuthenticationController.httpAuth(this.req, this.req)
  673. })
  674. it('should error with incorrect password', function(done) {
  675. this.req.headers = {
  676. authorization: `Basic ${Buffer.from('valid-test-user:nope').toString(
  677. 'base64'
  678. )}`
  679. }
  680. this.req.end = status => {
  681. expect(status).to.equal('Unauthorized')
  682. done()
  683. }
  684. this.AuthenticationController.httpAuth(this.req, this.req)
  685. })
  686. it('should fail with empty pass', function(done) {
  687. this.req.headers = {
  688. authorization: `Basic ${Buffer.from(`invalid-test-user:`).toString(
  689. 'base64'
  690. )}`
  691. }
  692. this.req.end = status => {
  693. expect(status).to.equal('Unauthorized')
  694. done()
  695. }
  696. this.AuthenticationController.httpAuth(this.req, this.req)
  697. })
  698. it('should succeed with correct user/pass', function(done) {
  699. this.req.headers = {
  700. authorization: `Basic ${Buffer.from(
  701. `valid-test-user:${this.httpAuthUsers['valid-test-user']}`
  702. ).toString('base64')}`
  703. }
  704. this.AuthenticationController.httpAuth(this.req, this.res, done)
  705. })
  706. })
  707. })
  708. describe('_redirectToLoginOrRegisterPage', function() {
  709. beforeEach(function() {
  710. this.middleware = this.AuthenticationController.requireLogin(
  711. (this.options = { load_from_db: false })
  712. )
  713. this.req.session = {}
  714. this.AuthenticationController._redirectToRegisterPage = sinon.stub()
  715. this.AuthenticationController._redirectToLoginPage = sinon.stub()
  716. this.req.query = {}
  717. })
  718. describe('they have come directly to the url', function() {
  719. beforeEach(function() {
  720. this.req.query = {}
  721. this.middleware(this.req, this.res, this.next)
  722. })
  723. it('should redirect to the login page', function() {
  724. this.AuthenticationController._redirectToRegisterPage
  725. .calledWith(this.req, this.res)
  726. .should.equal(false)
  727. this.AuthenticationController._redirectToLoginPage
  728. .calledWith(this.req, this.res)
  729. .should.equal(true)
  730. })
  731. })
  732. describe('they have come via a templates link', function() {
  733. beforeEach(function() {
  734. this.req.query.zipUrl = 'something'
  735. this.middleware(this.req, this.res, this.next)
  736. })
  737. it('should redirect to the register page', function() {
  738. this.AuthenticationController._redirectToRegisterPage
  739. .calledWith(this.req, this.res)
  740. .should.equal(true)
  741. this.AuthenticationController._redirectToLoginPage
  742. .calledWith(this.req, this.res)
  743. .should.equal(false)
  744. })
  745. })
  746. describe('they have been invited to a project', function() {
  747. beforeEach(function() {
  748. this.req.query.project_name = 'something'
  749. this.middleware(this.req, this.res, this.next)
  750. })
  751. it('should redirect to the register page', function() {
  752. this.AuthenticationController._redirectToRegisterPage
  753. .calledWith(this.req, this.res)
  754. .should.equal(true)
  755. this.AuthenticationController._redirectToLoginPage
  756. .calledWith(this.req, this.res)
  757. .should.equal(false)
  758. })
  759. })
  760. })
  761. describe('_redirectToRegisterPage', function() {
  762. beforeEach(function() {
  763. this.req.path = '/target/url'
  764. this.req.query = { extra_query: 'foo' }
  765. this.AuthenticationController._redirectToRegisterPage(this.req, this.res)
  766. })
  767. it('should redirect to the register page with a query string attached', function() {
  768. this.req.session.postLoginRedirect.should.equal(
  769. '/target/url?extra_query=foo'
  770. )
  771. this.res.redirectedTo.should.equal('/register?extra_query=foo')
  772. })
  773. it('should log out a message', function() {
  774. this.logger.log
  775. .calledWith(
  776. { url: this.url },
  777. 'user not logged in so redirecting to register page'
  778. )
  779. .should.equal(true)
  780. })
  781. })
  782. describe('_redirectToLoginPage', function() {
  783. beforeEach(function() {
  784. this.req.path = '/target/url'
  785. this.req.query = { extra_query: 'foo' }
  786. this.AuthenticationController._redirectToLoginPage(this.req, this.res)
  787. })
  788. it('should redirect to the register page with a query string attached', function() {
  789. this.req.session.postLoginRedirect.should.equal(
  790. '/target/url?extra_query=foo'
  791. )
  792. this.res.redirectedTo.should.equal('/login?extra_query=foo')
  793. })
  794. })
  795. describe('_recordSuccessfulLogin', function() {
  796. beforeEach(function() {
  797. this.UserUpdater.updateUser = sinon.stub().callsArg(2)
  798. this.AuthenticationController._recordSuccessfulLogin(
  799. this.user._id,
  800. this.callback
  801. )
  802. })
  803. it('should increment the user.login.success metric', function() {
  804. this.Metrics.inc.calledWith('user.login.success').should.equal(true)
  805. })
  806. it("should update the user's login count and last logged in date", function() {
  807. this.UserUpdater.updateUser.args[0][1]['$set'][
  808. 'lastLoggedIn'
  809. ].should.not.equal(undefined)
  810. this.UserUpdater.updateUser.args[0][1]['$inc']['loginCount'].should.equal(
  811. 1
  812. )
  813. })
  814. it('should call the callback', function() {
  815. this.callback.called.should.equal(true)
  816. })
  817. })
  818. describe('_recordFailedLogin', function() {
  819. beforeEach(function() {
  820. this.AuthenticationController._recordFailedLogin(this.callback)
  821. })
  822. it('should increment the user.login.failed metric', function() {
  823. this.Metrics.inc.calledWith('user.login.failed').should.equal(true)
  824. })
  825. it('should call the callback', function() {
  826. this.callback.called.should.equal(true)
  827. })
  828. })
  829. describe('setRedirectInSession', function() {
  830. beforeEach(function() {
  831. this.req = { session: {} }
  832. this.req.path = '/somewhere'
  833. this.req.query = { one: '1' }
  834. })
  835. it('should set redirect property on session', function() {
  836. this.AuthenticationController.setRedirectInSession(this.req)
  837. expect(this.req.session.postLoginRedirect).to.equal('/somewhere?one=1')
  838. })
  839. it('should set the supplied value', function() {
  840. this.AuthenticationController.setRedirectInSession(
  841. this.req,
  842. '/somewhere/specific'
  843. )
  844. expect(this.req.session.postLoginRedirect).to.equal('/somewhere/specific')
  845. })
  846. it('should not allow open redirects', function() {
  847. this.AuthenticationController.setRedirectInSession(
  848. this.req,
  849. 'https://evil.com'
  850. )
  851. expect(this.req.session.postLoginRedirect).to.be.undefined
  852. })
  853. describe('with a png', function() {
  854. beforeEach(function() {
  855. this.req = { session: {} }
  856. })
  857. it('should not set the redirect', function() {
  858. this.AuthenticationController.setRedirectInSession(
  859. this.req,
  860. '/something.png'
  861. )
  862. expect(this.req.session.postLoginRedirect).to.equal(undefined)
  863. })
  864. })
  865. describe('with a js path', function() {
  866. beforeEach(function() {
  867. this.req = { session: {} }
  868. })
  869. it('should not set the redirect', function() {
  870. this.AuthenticationController.setRedirectInSession(
  871. this.req,
  872. '/js/something.js'
  873. )
  874. expect(this.req.session.postLoginRedirect).to.equal(undefined)
  875. })
  876. })
  877. })
  878. describe('_getRedirectFromSession', function() {
  879. it('should get redirect property from session', function() {
  880. this.req = { session: { postLoginRedirect: '/a?b=c' } }
  881. expect(
  882. this.AuthenticationController._getRedirectFromSession(this.req)
  883. ).to.equal('/a?b=c')
  884. })
  885. it('should not allow open redirects', function() {
  886. this.req = { session: { postLoginRedirect: 'https://evil.com' } }
  887. expect(this.AuthenticationController._getRedirectFromSession(this.req)).to
  888. .be.null
  889. })
  890. it('handle null values', function() {
  891. this.req = { session: {} }
  892. expect(this.AuthenticationController._getRedirectFromSession(this.req)).to
  893. .be.null
  894. })
  895. })
  896. describe('_clearRedirectFromSession', function() {
  897. beforeEach(function() {
  898. this.req = { session: { postLoginRedirect: '/a?b=c' } }
  899. })
  900. it('should remove the redirect property from session', function() {
  901. this.AuthenticationController._clearRedirectFromSession(this.req)
  902. expect(this.req.session.postLoginRedirect).to.equal(undefined)
  903. })
  904. })
  905. describe('finishLogin', function() {
  906. // - get redirect
  907. // - async handlers
  908. // - afterLoginSessionSetup
  909. // - clear redirect
  910. // - issue redir, two ways
  911. beforeEach(function() {
  912. this.AuthenticationController._getRedirectFromSession = sinon
  913. .stub()
  914. .returns('/some/page')
  915. this.req.sessionID = 'thisisacryptographicallysecurerandomid'
  916. this.req.session = {
  917. passport: { user: { _id: 'one' } }
  918. }
  919. this.req.session.destroy = sinon.stub().callsArgWith(0, null)
  920. this.req.session.save = sinon.stub().callsArgWith(0, null)
  921. this.req.sessionStore = { generate: sinon.stub() }
  922. this.req.login = sinon.stub().yields(null)
  923. this.AuthenticationController._clearRedirectFromSession = sinon.stub()
  924. this.AuthenticationController._redirectToReconfirmPage = sinon.stub()
  925. this.UserSessionsManager.trackSession = sinon.stub()
  926. this.UserHandler.setupLoginData = sinon.stub()
  927. this.LoginRateLimiter.recordSuccessfulLogin = sinon.stub()
  928. this.AuthenticationController._recordSuccessfulLogin = sinon.stub()
  929. this.AnalyticsManager.recordEvent = sinon.stub()
  930. this.AnalyticsManager.identifyUser = sinon.stub()
  931. this.acceptsJson.returns(true)
  932. this.res.json = sinon.stub()
  933. this.res.redirect = sinon.stub()
  934. })
  935. it('should extract the redirect from the session', function() {
  936. this.AuthenticationController.finishLogin(
  937. this.user,
  938. this.req,
  939. this.res,
  940. this.next
  941. )
  942. expect(
  943. this.AuthenticationController._getRedirectFromSession.callCount
  944. ).to.equal(1)
  945. expect(
  946. this.AuthenticationController._getRedirectFromSession.calledWith(
  947. this.req
  948. )
  949. ).to.equal(true)
  950. })
  951. it('should clear redirect from session', function() {
  952. this.AuthenticationController.finishLogin(
  953. this.user,
  954. this.req,
  955. this.res,
  956. this.next
  957. )
  958. expect(
  959. this.AuthenticationController._clearRedirectFromSession.callCount
  960. ).to.equal(1)
  961. expect(
  962. this.AuthenticationController._clearRedirectFromSession.calledWith(
  963. this.req
  964. )
  965. ).to.equal(true)
  966. })
  967. it('should issue a json response with a redirect', function() {
  968. this.AuthenticationController.finishLogin(
  969. this.user,
  970. this.req,
  971. this.res,
  972. this.next
  973. )
  974. expect(
  975. this.AsyncFormHelper.redirect.calledWith(
  976. this.req,
  977. this.res,
  978. '/some/page'
  979. )
  980. ).to.equal(true)
  981. })
  982. describe('with a non-json request', function() {
  983. beforeEach(function() {
  984. this.acceptsJson.returns(false)
  985. this.res.json = sinon.stub()
  986. this.res.redirect = sinon.stub()
  987. })
  988. it('should issue a plain redirect', function() {
  989. this.AuthenticationController.finishLogin(
  990. this.user,
  991. this.req,
  992. this.res,
  993. this.next
  994. )
  995. expect(
  996. this.AsyncFormHelper.redirect.calledWith(
  997. this.req,
  998. this.res,
  999. '/some/page'
  1000. )
  1001. ).to.equal(true)
  1002. })
  1003. })
  1004. describe('when user is flagged to reconfirm', function() {
  1005. beforeEach(function() {
  1006. this.req.session = {}
  1007. this.user.must_reconfirm = true
  1008. })
  1009. it('should redirect to reconfirm page', function() {
  1010. this.AuthenticationController.finishLogin(
  1011. this.user,
  1012. this.req,
  1013. this.res,
  1014. this.next
  1015. )
  1016. expect(
  1017. this.AuthenticationController._redirectToReconfirmPage.calledWith(
  1018. this.req
  1019. )
  1020. ).to.equal(true)
  1021. })
  1022. })
  1023. describe('preFinishLogin hook', function() {
  1024. it('call hook and proceed', function() {
  1025. this.Modules.hooks.fire = sinon.stub().yields(null, [])
  1026. this.AuthenticationController.finishLogin(
  1027. this.user,
  1028. this.req,
  1029. this.res,
  1030. this.next
  1031. )
  1032. sinon.assert.calledWith(
  1033. this.Modules.hooks.fire,
  1034. 'preFinishLogin',
  1035. this.req,
  1036. this.res,
  1037. this.user
  1038. )
  1039. expect(this.AsyncFormHelper.redirect.called).to.equal(true)
  1040. })
  1041. it('stop if hook has redirected', function(done) {
  1042. this.Modules.hooks.fire = sinon
  1043. .stub()
  1044. .yields(null, [{ doNotFinish: true }])
  1045. this.AuthenticationController.finishLogin(
  1046. this.user,
  1047. this.req,
  1048. this.res,
  1049. this.next
  1050. )
  1051. expect(this.next.callCount).to.equal(0)
  1052. expect(this.res.json.callCount).to.equal(0)
  1053. done()
  1054. })
  1055. it('call next with hook errors', function(done) {
  1056. this.Modules.hooks.fire = sinon.stub().yields(new Error())
  1057. this.AuthenticationController.finishLogin(
  1058. this.user,
  1059. this.req,
  1060. this.res,
  1061. error => {
  1062. expect(error).to.exist
  1063. expect(this.res.json.callCount).to.equal(0)
  1064. done()
  1065. }
  1066. )
  1067. })
  1068. })
  1069. describe('_afterLoginSessionSetup', function() {
  1070. beforeEach(function() {})
  1071. it('should call req.login', function() {
  1072. this.AuthenticationController.finishLogin(
  1073. this.user,
  1074. this.req,
  1075. this.res,
  1076. this.next
  1077. )
  1078. this.req.login.callCount.should.equal(1)
  1079. })
  1080. it('should call req.session.save', function() {
  1081. this.AuthenticationController.finishLogin(
  1082. this.user,
  1083. this.req,
  1084. this.res,
  1085. this.next
  1086. )
  1087. this.req.session.save.callCount.should.equal(1)
  1088. })
  1089. it('should call UserSessionsManager.trackSession', function() {
  1090. this.AuthenticationController.finishLogin(
  1091. this.user,
  1092. this.req,
  1093. this.res,
  1094. this.next
  1095. )
  1096. this.UserSessionsManager.trackSession.callCount.should.equal(1)
  1097. })
  1098. describe('when req.session.save produces an error', function() {
  1099. beforeEach(function() {
  1100. this.req.session.save = sinon
  1101. .stub()
  1102. .callsArgWith(0, new Error('woops'))
  1103. })
  1104. it('should produce an error', function(done) {
  1105. this.AuthenticationController.finishLogin(
  1106. this.user,
  1107. this.req,
  1108. this.res,
  1109. err => {
  1110. expect(err).to.not.be.oneOf([null, undefined])
  1111. expect(err).to.be.instanceof(Error)
  1112. done()
  1113. }
  1114. )
  1115. })
  1116. it('should not call UserSessionsManager.trackSession', function(done) {
  1117. this.AuthenticationController.finishLogin(
  1118. this.user,
  1119. this.req,
  1120. this.res,
  1121. err => {
  1122. expect(err).to.exist
  1123. this.UserSessionsManager.trackSession.callCount.should.equal(0)
  1124. done()
  1125. }
  1126. )
  1127. })
  1128. })
  1129. })
  1130. describe('_loginAsyncHandlers', function() {
  1131. beforeEach(function() {
  1132. this.AuthenticationController.finishLogin(
  1133. this.user,
  1134. this.req,
  1135. this.res,
  1136. this.next
  1137. )
  1138. })
  1139. it('should call identifyUser', function() {
  1140. this.AnalyticsManager.identifyUser
  1141. .calledWith(this.user._id, this.req.sessionID)
  1142. .should.equal(true)
  1143. })
  1144. it('should setup the user data in the background', function() {
  1145. this.UserHandler.setupLoginData.calledWith(this.user).should.equal(true)
  1146. })
  1147. it('should set res.session.justLoggedIn', function() {
  1148. this.req.session.justLoggedIn.should.equal(true)
  1149. })
  1150. it('should record the successful login', function() {
  1151. this.AuthenticationController._recordSuccessfulLogin
  1152. .calledWith(this.user._id)
  1153. .should.equal(true)
  1154. })
  1155. it('should tell the rate limiter that there was a success for that email', function() {
  1156. this.LoginRateLimiter.recordSuccessfulLogin
  1157. .calledWith(this.user.email)
  1158. .should.equal(true)
  1159. })
  1160. it('should log the successful login', function() {
  1161. this.logger.log
  1162. .calledWith(
  1163. { email: this.user.email, user_id: this.user._id.toString() },
  1164. 'successful log in'
  1165. )
  1166. .should.equal(true)
  1167. })
  1168. it('should track the login event', function() {
  1169. this.AnalyticsManager.recordEvent
  1170. .calledWith(this.user._id, 'user-logged-in')
  1171. .should.equal(true)
  1172. })
  1173. })
  1174. })
  1175. })