AuthenticationController.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. const AuthenticationManager = require('./AuthenticationManager')
  2. const SessionManager = require('./SessionManager')
  3. const OError = require('@overleaf/o-error')
  4. const LoginRateLimiter = require('../Security/LoginRateLimiter')
  5. const UserUpdater = require('../User/UserUpdater')
  6. const Metrics = require('@overleaf/metrics')
  7. const logger = require('@overleaf/logger')
  8. const querystring = require('querystring')
  9. const Settings = require('@overleaf/settings')
  10. const basicAuth = require('basic-auth')
  11. const tsscmp = require('tsscmp')
  12. const UserHandler = require('../User/UserHandler')
  13. const UserSessionsManager = require('../User/UserSessionsManager')
  14. const SessionStoreManager = require('../../infrastructure/SessionStoreManager')
  15. const Analytics = require('../Analytics/AnalyticsManager')
  16. const passport = require('passport')
  17. const NotificationsBuilder = require('../Notifications/NotificationsBuilder')
  18. const UrlHelper = require('../Helpers/UrlHelper')
  19. const AsyncFormHelper = require('../Helpers/AsyncFormHelper')
  20. const _ = require('lodash')
  21. const UserAuditLogHandler = require('../User/UserAuditLogHandler')
  22. const AnalyticsRegistrationSourceHelper = require('../Analytics/AnalyticsRegistrationSourceHelper')
  23. const {
  24. acceptsJson,
  25. } = require('../../infrastructure/RequestContentTypeDetection')
  26. const { ParallelLoginError } = require('./AuthenticationErrors')
  27. const { hasAdminAccess } = require('../Helpers/AdminAuthorizationHelper')
  28. const Modules = require('../../infrastructure/Modules')
  29. function send401WithChallenge(res) {
  30. res.setHeader('WWW-Authenticate', 'OverleafLogin')
  31. res.sendStatus(401)
  32. }
  33. function checkCredentials(userDetailsMap, user, password) {
  34. const expectedPassword = userDetailsMap.get(user)
  35. const userExists = userDetailsMap.has(user) && expectedPassword // user exists with a non-null password
  36. const isValid = userExists && tsscmp(expectedPassword, password)
  37. if (!isValid) {
  38. logger.err({ user }, 'invalid login details')
  39. }
  40. Metrics.inc('security.http-auth.check-credentials', 1, {
  41. path: userExists ? 'known-user' : 'unknown-user',
  42. status: isValid ? 'pass' : 'fail',
  43. })
  44. return isValid
  45. }
  46. const AuthenticationController = {
  47. serializeUser(user, callback) {
  48. if (!user._id || !user.email) {
  49. const err = new Error('serializeUser called with non-user object')
  50. logger.warn({ user }, err.message)
  51. return callback(err)
  52. }
  53. const lightUser = {
  54. _id: user._id,
  55. first_name: user.first_name,
  56. last_name: user.last_name,
  57. isAdmin: user.isAdmin,
  58. staffAccess: user.staffAccess,
  59. email: user.email,
  60. referal_id: user.referal_id,
  61. session_created: new Date().toISOString(),
  62. ip_address: user._login_req_ip,
  63. must_reconfirm: user.must_reconfirm,
  64. v1_id: user.overleaf != null ? user.overleaf.id : undefined,
  65. analyticsId: user.analyticsId || user._id,
  66. alphaProgram: user.alphaProgram || undefined, // only store if set
  67. betaProgram: user.betaProgram || undefined, // only store if set
  68. }
  69. callback(null, lightUser)
  70. },
  71. deserializeUser(user, cb) {
  72. cb(null, user)
  73. },
  74. passportLogin(req, res, next) {
  75. // This function is middleware which wraps the passport.authenticate middleware,
  76. // so we can send back our custom `{message: {text: "", type: ""}}` responses on failure,
  77. // and send a `{redir: ""}` response on success
  78. passport.authenticate('local', function (err, user, info) {
  79. if (err) {
  80. return next(err)
  81. }
  82. if (user) {
  83. // `user` is either a user object or false
  84. AuthenticationController.setAuditInfo(req, { method: 'Password login' })
  85. return AuthenticationController.finishLogin(user, req, res, next)
  86. } else {
  87. if (info.redir != null) {
  88. return res.json({ redir: info.redir })
  89. } else {
  90. res.status(info.status || 200)
  91. delete info.status
  92. const body = { message: info }
  93. const { errorReason } = info
  94. if (errorReason) {
  95. body.errorReason = errorReason
  96. delete info.errorReason
  97. }
  98. return res.json(body)
  99. }
  100. }
  101. })(req, res, next)
  102. },
  103. finishLogin(user, req, res, next) {
  104. if (user === false) {
  105. return AsyncFormHelper.redirect(req, res, '/login')
  106. } // OAuth2 'state' mismatch
  107. if (Settings.adminOnlyLogin && !hasAdminAccess(user)) {
  108. return res.status(403).json({
  109. message: { type: 'error', text: 'Admin only panel' },
  110. })
  111. }
  112. const auditInfo = AuthenticationController.getAuditInfo(req)
  113. const anonymousAnalyticsId = req.session.analyticsId
  114. const isNewUser = req.session.justRegistered || false
  115. Modules.hooks.fire(
  116. 'preFinishLogin',
  117. req,
  118. res,
  119. user,
  120. function (error, results) {
  121. if (error) {
  122. return next(error)
  123. }
  124. if (results.some(result => result && result.doNotFinish)) {
  125. return
  126. }
  127. if (user.must_reconfirm) {
  128. return AuthenticationController._redirectToReconfirmPage(
  129. req,
  130. res,
  131. user
  132. )
  133. }
  134. const redir =
  135. AuthenticationController._getRedirectFromSession(req) || '/project'
  136. _loginAsyncHandlers(req, user, anonymousAnalyticsId, isNewUser)
  137. const userId = user._id
  138. UserAuditLogHandler.addEntry(
  139. userId,
  140. 'login',
  141. userId,
  142. req.ip,
  143. auditInfo,
  144. err => {
  145. if (err) {
  146. return next(err)
  147. }
  148. _afterLoginSessionSetup(req, user, function (err) {
  149. if (err) {
  150. return next(err)
  151. }
  152. AuthenticationController._clearRedirectFromSession(req)
  153. AnalyticsRegistrationSourceHelper.clearSource(req.session)
  154. AnalyticsRegistrationSourceHelper.clearInbound(req.session)
  155. AsyncFormHelper.redirect(req, res, redir)
  156. })
  157. }
  158. )
  159. }
  160. )
  161. },
  162. doPassportLogin(req, username, password, done) {
  163. const email = username.toLowerCase()
  164. Modules.hooks.fire(
  165. 'preDoPassportLogin',
  166. req,
  167. email,
  168. function (err, infoList) {
  169. if (err) {
  170. return done(err)
  171. }
  172. const info = infoList.find(i => i != null)
  173. if (info != null) {
  174. return done(null, false, info)
  175. }
  176. LoginRateLimiter.processLoginRequest(email, function (err, isAllowed) {
  177. if (err) {
  178. return done(err)
  179. }
  180. if (!isAllowed) {
  181. logger.debug({ email }, 'too many login requests')
  182. return done(null, null, {
  183. text: req.i18n.translate('to_many_login_requests_2_mins'),
  184. type: 'error',
  185. status: 429,
  186. })
  187. }
  188. const auditLog = {
  189. ipAddress: req.ip,
  190. info: { method: 'Password login' },
  191. }
  192. AuthenticationManager.authenticate(
  193. { email },
  194. password,
  195. auditLog,
  196. function (error, user) {
  197. if (error != null) {
  198. if (error instanceof ParallelLoginError) {
  199. return done(null, false, { status: 429 })
  200. }
  201. return done(error)
  202. }
  203. if (
  204. user &&
  205. AuthenticationController.captchaRequiredForLogin(req, user)
  206. ) {
  207. done(null, false, {
  208. text: req.i18n.translate('cannot_verify_user_not_robot'),
  209. type: 'error',
  210. errorReason: 'cannot_verify_user_not_robot',
  211. status: 400,
  212. })
  213. } else if (user) {
  214. // async actions
  215. done(null, user)
  216. } else {
  217. AuthenticationController._recordFailedLogin()
  218. logger.debug({ email }, 'failed log in')
  219. done(null, false, {
  220. text: req.i18n.translate('email_or_password_wrong_try_again'),
  221. type: 'error',
  222. status: 401,
  223. })
  224. }
  225. }
  226. )
  227. })
  228. }
  229. )
  230. },
  231. captchaRequiredForLogin(req, user) {
  232. switch (AuthenticationController.getAuditInfo(req).captcha) {
  233. case 'trusted':
  234. case 'disabled':
  235. return false
  236. case 'solved':
  237. return false
  238. case 'skipped': {
  239. let required = false
  240. if (user.lastFailedLogin) {
  241. const requireCaptchaUntil =
  242. user.lastFailedLogin.getTime() +
  243. Settings.elevateAccountSecurityAfterFailedLogin
  244. required = requireCaptchaUntil >= Date.now()
  245. }
  246. Metrics.inc('force_captcha_on_login', 1, {
  247. status: required ? 'yes' : 'no',
  248. })
  249. return required
  250. }
  251. default:
  252. throw new Error('captcha middleware missing in handler chain')
  253. }
  254. },
  255. ipMatchCheck(req, user) {
  256. if (req.ip !== user.lastLoginIp) {
  257. NotificationsBuilder.ipMatcherAffiliation(user._id).create(
  258. req.ip,
  259. () => {}
  260. )
  261. }
  262. return UserUpdater.updateUser(
  263. user._id.toString(),
  264. {
  265. $set: { lastLoginIp: req.ip },
  266. },
  267. () => {}
  268. )
  269. },
  270. requireLogin() {
  271. const doRequest = function (req, res, next) {
  272. if (next == null) {
  273. next = function () {}
  274. }
  275. if (!SessionManager.isUserLoggedIn(req.session)) {
  276. if (acceptsJson(req)) return send401WithChallenge(res)
  277. return AuthenticationController._redirectToLoginOrRegisterPage(req, res)
  278. } else {
  279. req.user = SessionManager.getSessionUser(req.session)
  280. return next()
  281. }
  282. }
  283. return doRequest
  284. },
  285. requireOauth() {
  286. // require this here because module may not be included in some versions
  287. const Oauth2Server = require('../../../../modules/oauth2-server/app/src/Oauth2Server')
  288. return function (req, res, next) {
  289. if (next == null) {
  290. next = function () {}
  291. }
  292. const request = new Oauth2Server.Request(req)
  293. const response = new Oauth2Server.Response(res)
  294. return Oauth2Server.server.authenticate(
  295. request,
  296. response,
  297. {},
  298. function (err, token) {
  299. if (err) {
  300. // use a 401 status code for malformed header for git-bridge
  301. if (
  302. err.code === 400 &&
  303. err.message === 'Invalid request: malformed authorization header'
  304. ) {
  305. err.code = 401
  306. }
  307. // send all other errors
  308. return res
  309. .status(err.code)
  310. .json({ error: err.name, error_description: err.message })
  311. }
  312. req.oauth = { access_token: token.accessToken }
  313. req.oauth_token = token
  314. req.oauth_user = token.user
  315. return next()
  316. }
  317. )
  318. }
  319. },
  320. validateUserSession: function () {
  321. // Middleware to check that the user's session is still good on key actions,
  322. // such as opening a a project. Could be used to check that session has not
  323. // exceeded a maximum lifetime (req.session.session_created), or for session
  324. // hijacking checks (e.g. change of ip address, req.session.ip_address). For
  325. // now, just check that the session has been loaded from the session store
  326. // correctly.
  327. return function (req, res, next) {
  328. // check that the session store is returning valid results
  329. if (req.session && !SessionStoreManager.hasValidationToken(req)) {
  330. // force user to update session
  331. req.session.regenerate(() => {
  332. // need to destroy the existing session and generate a new one
  333. // otherwise they will already be logged in when they are redirected
  334. // to the login page
  335. if (acceptsJson(req)) return send401WithChallenge(res)
  336. AuthenticationController._redirectToLoginOrRegisterPage(req, res)
  337. })
  338. } else {
  339. next()
  340. }
  341. }
  342. },
  343. _globalLoginWhitelist: [],
  344. addEndpointToLoginWhitelist(endpoint) {
  345. return AuthenticationController._globalLoginWhitelist.push(endpoint)
  346. },
  347. requireGlobalLogin(req, res, next) {
  348. if (
  349. AuthenticationController._globalLoginWhitelist.includes(
  350. req._parsedUrl.pathname
  351. )
  352. ) {
  353. return next()
  354. }
  355. if (req.headers.authorization != null) {
  356. AuthenticationController.requirePrivateApiAuth()(req, res, next)
  357. } else if (SessionManager.isUserLoggedIn(req.session)) {
  358. next()
  359. } else {
  360. logger.debug(
  361. { url: req.url },
  362. 'user trying to access endpoint not in global whitelist'
  363. )
  364. if (acceptsJson(req)) return send401WithChallenge(res)
  365. AuthenticationController.setRedirectInSession(req)
  366. res.redirect('/login')
  367. }
  368. },
  369. validateAdmin(req, res, next) {
  370. const adminDomains = Settings.adminDomains
  371. if (
  372. !adminDomains ||
  373. !(Array.isArray(adminDomains) && adminDomains.length)
  374. ) {
  375. return next()
  376. }
  377. const user = SessionManager.getSessionUser(req.session)
  378. if (!hasAdminAccess(user)) {
  379. return next()
  380. }
  381. const email = user.email
  382. if (email == null) {
  383. return next(
  384. new OError('[ValidateAdmin] Admin user without email address', {
  385. userId: user._id,
  386. })
  387. )
  388. }
  389. if (!adminDomains.find(domain => email.endsWith(`@${domain}`))) {
  390. return next(
  391. new OError('[ValidateAdmin] Admin user with invalid email domain', {
  392. email,
  393. userId: user._id,
  394. })
  395. )
  396. }
  397. return next()
  398. },
  399. checkCredentials,
  400. requireBasicAuth: function (userDetails) {
  401. const userDetailsMap = new Map(Object.entries(userDetails))
  402. return function (req, res, next) {
  403. const credentials = basicAuth(req)
  404. if (
  405. !credentials ||
  406. !checkCredentials(userDetailsMap, credentials.name, credentials.pass)
  407. ) {
  408. send401WithChallenge(res)
  409. Metrics.inc('security.http-auth', 1, { status: 'reject' })
  410. } else {
  411. Metrics.inc('security.http-auth', 1, { status: 'accept' })
  412. next()
  413. }
  414. }
  415. },
  416. requirePrivateApiAuth() {
  417. return AuthenticationController.requireBasicAuth(Settings.httpAuthUsers)
  418. },
  419. setAuditInfo(req, info) {
  420. if (!req.__authAuditInfo) {
  421. req.__authAuditInfo = {}
  422. }
  423. Object.assign(req.__authAuditInfo, info)
  424. },
  425. getAuditInfo(req) {
  426. return req.__authAuditInfo || {}
  427. },
  428. setRedirectInSession(req, value) {
  429. if (value == null) {
  430. value =
  431. Object.keys(req.query).length > 0
  432. ? `${req.path}?${querystring.stringify(req.query)}`
  433. : `${req.path}`
  434. }
  435. if (
  436. req.session != null &&
  437. !/^\/(socket.io|js|stylesheets|img)\/.*$/.test(value) &&
  438. !/^.*\.(png|jpeg|svg)$/.test(value)
  439. ) {
  440. const safePath = UrlHelper.getSafeRedirectPath(value)
  441. return (req.session.postLoginRedirect = safePath)
  442. }
  443. },
  444. _redirectToLoginOrRegisterPage(req, res) {
  445. if (
  446. req.query.zipUrl != null ||
  447. req.query.project_name != null ||
  448. req.path === '/user/subscription/new'
  449. ) {
  450. AuthenticationController._redirectToRegisterPage(req, res)
  451. } else {
  452. AuthenticationController._redirectToLoginPage(req, res)
  453. }
  454. },
  455. _redirectToLoginPage(req, res) {
  456. logger.debug(
  457. { url: req.url },
  458. 'user not logged in so redirecting to login page'
  459. )
  460. AuthenticationController.setRedirectInSession(req)
  461. const url = `/login?${querystring.stringify(req.query)}`
  462. res.redirect(url)
  463. Metrics.inc('security.login-redirect')
  464. },
  465. _redirectToReconfirmPage(req, res, user) {
  466. logger.debug(
  467. { url: req.url },
  468. 'user needs to reconfirm so redirecting to reconfirm page'
  469. )
  470. req.session.reconfirm_email = user != null ? user.email : undefined
  471. const redir = '/user/reconfirm'
  472. AsyncFormHelper.redirect(req, res, redir)
  473. },
  474. _redirectToRegisterPage(req, res) {
  475. logger.debug(
  476. { url: req.url },
  477. 'user not logged in so redirecting to register page'
  478. )
  479. AuthenticationController.setRedirectInSession(req)
  480. const url = `/register?${querystring.stringify(req.query)}`
  481. res.redirect(url)
  482. Metrics.inc('security.login-redirect')
  483. },
  484. _recordSuccessfulLogin(userId, callback) {
  485. if (callback == null) {
  486. callback = function () {}
  487. }
  488. UserUpdater.updateUser(
  489. userId.toString(),
  490. {
  491. $set: { lastLoggedIn: new Date() },
  492. $inc: { loginCount: 1 },
  493. },
  494. function (error) {
  495. if (error != null) {
  496. callback(error)
  497. }
  498. Metrics.inc('user.login.success')
  499. callback()
  500. }
  501. )
  502. },
  503. _recordFailedLogin(callback) {
  504. Metrics.inc('user.login.failed')
  505. if (callback) callback()
  506. },
  507. _getRedirectFromSession(req) {
  508. let safePath
  509. const value = _.get(req, ['session', 'postLoginRedirect'])
  510. if (value) {
  511. safePath = UrlHelper.getSafeRedirectPath(value)
  512. }
  513. return safePath || null
  514. },
  515. _clearRedirectFromSession(req) {
  516. if (req.session != null) {
  517. delete req.session.postLoginRedirect
  518. }
  519. },
  520. }
  521. function _afterLoginSessionSetup(req, user, callback) {
  522. if (callback == null) {
  523. callback = function () {}
  524. }
  525. req.login(user, function (err) {
  526. if (err) {
  527. OError.tag(err, 'error from req.login', {
  528. user_id: user._id,
  529. })
  530. return callback(err)
  531. }
  532. // Regenerate the session to get a new sessionID (cookie value) to
  533. // protect against session fixation attacks
  534. const oldSession = req.session
  535. req.session.destroy(function (err) {
  536. if (err) {
  537. OError.tag(err, 'error when trying to destroy old session', {
  538. user_id: user._id,
  539. })
  540. return callback(err)
  541. }
  542. req.sessionStore.generate(req)
  543. // Note: the validation token is not writable, so it does not get
  544. // transferred to the new session below.
  545. for (const key in oldSession) {
  546. const value = oldSession[key]
  547. if (key !== '__tmp' && key !== 'csrfSecret') {
  548. req.session[key] = value
  549. }
  550. }
  551. req.session.save(function (err) {
  552. if (err) {
  553. OError.tag(err, 'error saving regenerated session after login', {
  554. user_id: user._id,
  555. })
  556. return callback(err)
  557. }
  558. UserSessionsManager.trackSession(user, req.sessionID, function () {})
  559. if (!req.deviceHistory) {
  560. // Captcha disabled or SSO-based login.
  561. return callback()
  562. }
  563. req.deviceHistory.add(user.email)
  564. req.deviceHistory
  565. .serialize(req.res)
  566. .catch(err => {
  567. logger.err({ err }, 'cannot serialize deviceHistory')
  568. })
  569. .finally(() => callback())
  570. })
  571. })
  572. })
  573. }
  574. function _loginAsyncHandlers(req, user, anonymousAnalyticsId, isNewUser) {
  575. UserHandler.setupLoginData(user, err => {
  576. if (err != null) {
  577. logger.warn({ err }, 'error setting up login data')
  578. }
  579. })
  580. LoginRateLimiter.recordSuccessfulLogin(user.email, () => {})
  581. AuthenticationController._recordSuccessfulLogin(user._id, () => {})
  582. AuthenticationController.ipMatchCheck(req, user)
  583. Analytics.recordEventForUser(user._id, 'user-logged-in', {
  584. source: req.session.saml
  585. ? 'saml'
  586. : req.user_info?.auth_provider || 'email-password',
  587. })
  588. Analytics.identifyUser(user._id, anonymousAnalyticsId, isNewUser)
  589. logger.debug(
  590. { email: user.email, userId: user._id.toString() },
  591. 'successful log in'
  592. )
  593. req.session.justLoggedIn = true
  594. // capture the request ip for use when creating the session
  595. return (user._login_req_ip = req.ip)
  596. }
  597. module.exports = AuthenticationController