AuthenticationController.js 19 KB

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