AuthenticationController.mjs 19 KB

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