AuthenticationControllerTests.js 42 KB

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