AuthenticationControllerTests.js 41 KB

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