AuthenticationController.js 19 KB

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