AuthenticationController.mjs 19 KB

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