AuthenticationController.js 20 KB

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