AuthenticationControllerTests.js 40 KB

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