AuthenticationController.js 20 KB

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