AuthenticationController.mjs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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.mjs'
  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.mjs'
  23. import AdminAuthorizationHelper from '../Helpers/AdminAuthorizationHelper.mjs'
  24. import Modules from '../../infrastructure/Modules.mjs'
  25. import { expressify, promisify } from '@overleaf/promise-utils'
  26. import { handleAuthenticateErrors } from './AuthenticationErrors.mjs'
  27. import EmailHelper from '../Helpers/EmailHelper.mjs'
  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. // 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. lightUser.adminRoles = user.adminRoles
  84. }
  85. callback(null, lightUser)
  86. },
  87. deserializeUser(user, cb) {
  88. cb(null, user)
  89. },
  90. passportLogin(req, res, next) {
  91. // This function is middleware which wraps the passport.authenticate middleware,
  92. // so we can send back our custom `{message: {text: "", type: ""}}` responses on failure,
  93. // and send a `{redir: ""}` response on success
  94. passport.authenticate(
  95. 'local',
  96. { keepSessionInfo: true },
  97. async function (err, user, info) {
  98. if (err) {
  99. return next(err)
  100. }
  101. if (user) {
  102. // `user` is either a user object or false
  103. AuthenticationController.setAuditInfo(req, {
  104. method: 'Password login',
  105. })
  106. try {
  107. // We could investigate whether this can be done together with 'preFinishLogin' instead of being its own hook
  108. await Modules.promises.hooks.fire(
  109. 'saasLogin',
  110. { email: user.email },
  111. req
  112. )
  113. await AuthenticationController.promises.finishLogin(user, req, res)
  114. } catch (err) {
  115. return next(err)
  116. }
  117. } else {
  118. if (info.redir != null) {
  119. return res.json({ redir: info.redir })
  120. } else {
  121. res.status(info.status || 200)
  122. delete info.status
  123. const body = { message: info }
  124. const { errorReason } = info
  125. if (errorReason) {
  126. body.errorReason = errorReason
  127. delete info.errorReason
  128. }
  129. return res.json(body)
  130. }
  131. }
  132. }
  133. )(req, res, next)
  134. },
  135. async _finishLoginAsync(user, req, res) {
  136. if (user === false) {
  137. return AsyncFormHelper.redirect(req, res, '/login')
  138. } // OAuth2 'state' mismatch
  139. if (user.suspended) {
  140. return AsyncFormHelper.redirect(req, res, '/account-suspended')
  141. }
  142. if (Settings.adminOnlyLogin && !hasAdminAccess(user)) {
  143. return res.status(403).json({
  144. message: { type: 'error', text: 'Admin only panel' },
  145. })
  146. }
  147. const auditInfo = AuthenticationController.getAuditInfo(req)
  148. const anonymousAnalyticsId = req.session.analyticsId
  149. const isNewUser = req.session.justRegistered || false
  150. const results = await Modules.promises.hooks.fire(
  151. 'preFinishLogin',
  152. req,
  153. res,
  154. user
  155. )
  156. if (results.some(result => result && result.doNotFinish)) {
  157. return
  158. }
  159. if (user.must_reconfirm) {
  160. return AuthenticationController._redirectToReconfirmPage(req, res, user)
  161. }
  162. const redir =
  163. AuthenticationController.getRedirectFromSession(req) || '/project'
  164. _loginAsyncHandlers(req, user, anonymousAnalyticsId, isNewUser)
  165. const userId = user._id
  166. await UserAuditLogHandler.promises.addEntry(
  167. userId,
  168. 'login',
  169. userId,
  170. req.ip,
  171. auditInfo
  172. )
  173. await _afterLoginSessionSetupAsync(req, user)
  174. AuthenticationController._clearRedirectFromSession(req)
  175. AnalyticsRegistrationSourceHelper.clearSource(req.session)
  176. AnalyticsRegistrationSourceHelper.clearInbound(req.session)
  177. AsyncFormHelper.redirect(req, res, redir)
  178. },
  179. finishLogin(user, req, res, next) {
  180. AuthenticationController._finishLoginAsync(user, req, res).catch(err =>
  181. next(err)
  182. )
  183. },
  184. async doPassportLogin(req, username, password, done) {
  185. let user, info
  186. try {
  187. ;({ user, info } = await AuthenticationController._doPassportLogin(
  188. req,
  189. username,
  190. password
  191. ))
  192. } catch (error) {
  193. return done(error)
  194. }
  195. return done(undefined, user, info)
  196. },
  197. /**
  198. *
  199. * @param req
  200. * @param username
  201. * @param password
  202. * @returns {Promise<{ user: any, info: any}>}
  203. */
  204. async _doPassportLogin(req, username, password) {
  205. const email = EmailHelper.parseEmail(username)
  206. if (!email) {
  207. Metrics.inc('login_failure_reason', 1, { status: 'invalid_email' })
  208. return {
  209. user: null,
  210. info: {
  211. status: 400,
  212. type: 'error',
  213. text: req.i18n.translate('email_address_is_invalid'),
  214. },
  215. }
  216. }
  217. AuthenticationController.setAuditInfo(req, { method: 'Password login' })
  218. const { fromKnownDevice } = AuthenticationController.getAuditInfo(req)
  219. const auditLog = {
  220. ipAddress: req.ip,
  221. info: { method: 'Password login', fromKnownDevice },
  222. }
  223. let user, isPasswordReused
  224. try {
  225. ;({ user, isPasswordReused } =
  226. await AuthenticationManager.promises.authenticate(
  227. { email },
  228. password,
  229. auditLog,
  230. {
  231. enforceHIBPCheck: !fromKnownDevice,
  232. }
  233. ))
  234. } catch (error) {
  235. return {
  236. user: false,
  237. info: handleAuthenticateErrors(error, req),
  238. }
  239. }
  240. if (user && AuthenticationController.captchaRequiredForLogin(req, user)) {
  241. Metrics.inc('login_failure_reason', 1, { status: 'captcha_missing' })
  242. return {
  243. user: false,
  244. info: {
  245. text: req.i18n.translate('cannot_verify_user_not_robot'),
  246. type: 'error',
  247. errorReason: 'cannot_verify_user_not_robot',
  248. status: 400,
  249. },
  250. }
  251. } else if (user) {
  252. if (
  253. isPasswordReused &&
  254. AuthenticationController.getRedirectFromSession(req) == null
  255. ) {
  256. AuthenticationController.setRedirectInSession(
  257. req,
  258. '/compromised-password'
  259. )
  260. }
  261. // async actions
  262. return { user, info: undefined }
  263. } else {
  264. Metrics.inc('login_failure_reason', 1, { status: 'password_invalid' })
  265. AuthenticationController._recordFailedLogin()
  266. logger.debug({ email }, 'failed log in')
  267. return {
  268. user: false,
  269. info: {
  270. type: 'error',
  271. key: 'invalid-password-retry-or-reset',
  272. status: 401,
  273. },
  274. }
  275. }
  276. },
  277. captchaRequiredForLogin(req, user) {
  278. switch (AuthenticationController.getAuditInfo(req).captcha) {
  279. case 'trusted':
  280. case 'disabled':
  281. return false
  282. case 'solved':
  283. return false
  284. case 'skipped': {
  285. let required = false
  286. if (user.lastFailedLogin) {
  287. const requireCaptchaUntil =
  288. user.lastFailedLogin.getTime() +
  289. Settings.elevateAccountSecurityAfterFailedLogin
  290. required = requireCaptchaUntil >= Date.now()
  291. }
  292. Metrics.inc('force_captcha_on_login', 1, {
  293. status: required ? 'yes' : 'no',
  294. })
  295. return required
  296. }
  297. default:
  298. throw new Error('captcha middleware missing in handler chain')
  299. }
  300. },
  301. ipMatchCheck(req, user) {
  302. if (req.ip !== user.lastLoginIp) {
  303. NotificationsBuilder.ipMatcherAffiliation(user._id.toString()).create(
  304. req.ip,
  305. () => {}
  306. )
  307. }
  308. return UserUpdater.updateUser(
  309. user._id.toString(),
  310. {
  311. $set: { lastLoginIp: req.ip },
  312. },
  313. () => {}
  314. )
  315. },
  316. requireLogin() {
  317. const doRequest = function (req, res, next) {
  318. if (next == null) {
  319. next = function () {}
  320. }
  321. if (!SessionManager.isUserLoggedIn(req.session)) {
  322. if (acceptsJson(req)) return send401WithChallenge(res)
  323. return AuthenticationController._redirectToLoginOrRegisterPage(req, res)
  324. } else {
  325. req.user = SessionManager.getSessionUser(req.session)
  326. req.logger?.addFields({ userId: req.user._id })
  327. return next()
  328. }
  329. }
  330. return doRequest
  331. },
  332. /**
  333. * @param {string} scope
  334. * @return {import('express').Handler}
  335. */
  336. requireOauth(scope) {
  337. if (typeof scope !== 'string' || !scope) {
  338. throw new Error(
  339. "requireOauth() expects a non-empty string as 'scope' parameter"
  340. )
  341. }
  342. const middleware = async (req, res, next) => {
  343. const Oauth2Server = (
  344. await import('../../../../modules/oauth2-server/app/src/Oauth2Server.mjs')
  345. ).default
  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.promises.populateTeamInvites(user).catch(err => {
  586. logger.warn({ err }, 'error setting up login data')
  587. })
  588. LoginRateLimiter.recordSuccessfulLogin(user.email, () => {})
  589. AuthenticationController._recordSuccessfulLogin(user._id, () => {})
  590. AuthenticationController.ipMatchCheck(req, user)
  591. Analytics.recordEventForUserInBackground(user._id, 'user-logged-in', {
  592. source: req.session.saml
  593. ? 'saml'
  594. : req.user_info?.auth_provider || 'email-password',
  595. })
  596. Analytics.identifyUser(user._id, anonymousAnalyticsId, isNewUser)
  597. logger.debug(
  598. { email: user.email, userId: user._id.toString() },
  599. 'successful log in'
  600. )
  601. req.session.justLoggedIn = true
  602. // capture the request ip for use when creating the session
  603. return (user._login_req_ip = req.ip)
  604. }
  605. AuthenticationController.promises = {
  606. finishLogin: AuthenticationController._finishLoginAsync,
  607. }
  608. export default AuthenticationController