TokenAccessController.mjs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. import AuthenticationController from '../Authentication/AuthenticationController.js'
  2. import SessionManager from '../Authentication/SessionManager.js'
  3. import TokenAccessHandler from './TokenAccessHandler.js'
  4. import Errors from '../Errors/Errors.js'
  5. import logger from '@overleaf/logger'
  6. import OError from '@overleaf/o-error'
  7. import { expressify } from '@overleaf/promise-utils'
  8. import AuthorizationManager from '../Authorization/AuthorizationManager.js'
  9. import PrivilegeLevels from '../Authorization/PrivilegeLevels.js'
  10. import ProjectAuditLogHandler from '../Project/ProjectAuditLogHandler.js'
  11. import CollaboratorsInviteHandler from '../Collaborators/CollaboratorsInviteHandler.mjs'
  12. import CollaboratorsHandler from '../Collaborators/CollaboratorsHandler.js'
  13. import EditorRealTimeController from '../Editor/EditorRealTimeController.js'
  14. import CollaboratorsGetter from '../Collaborators/CollaboratorsGetter.js'
  15. import ProjectGetter from '../Project/ProjectGetter.js'
  16. import AsyncFormHelper from '../Helpers/AsyncFormHelper.js'
  17. import AnalyticsManager from '../Analytics/AnalyticsManager.js'
  18. import { canRedirectToAdminDomain } from '../Helpers/AdminAuthorizationHelper.js'
  19. import { getSafeAdminDomainRedirect } from '../Helpers/UrlHelper.js'
  20. import UserGetter from '../User/UserGetter.js'
  21. import Settings from '@overleaf/settings'
  22. import LimitationsManager from '../Subscription/LimitationsManager.js'
  23. const orderedPrivilegeLevels = [
  24. PrivilegeLevels.NONE,
  25. PrivilegeLevels.READ_ONLY,
  26. PrivilegeLevels.REVIEW,
  27. PrivilegeLevels.READ_AND_WRITE,
  28. PrivilegeLevels.OWNER,
  29. ]
  30. async function _userAlreadyHasHigherPrivilege(userId, projectId, tokenType) {
  31. if (!Object.values(TokenAccessHandler.TOKEN_TYPES).includes(tokenType)) {
  32. throw new Error('bad token type')
  33. }
  34. if (!userId) {
  35. return false
  36. }
  37. const privilegeLevel =
  38. await AuthorizationManager.promises.getPrivilegeLevelForProject(
  39. userId,
  40. projectId
  41. )
  42. return (
  43. orderedPrivilegeLevels.indexOf(privilegeLevel) >=
  44. orderedPrivilegeLevels.indexOf(tokenType)
  45. )
  46. }
  47. const makePostUrl = token => {
  48. if (TokenAccessHandler.isReadAndWriteToken(token)) {
  49. return `/${token}/grant`
  50. } else if (TokenAccessHandler.isReadOnlyToken(token)) {
  51. return `/read/${token}/grant`
  52. } else {
  53. throw new Error('invalid token type')
  54. }
  55. }
  56. async function _handleV1Project(token, userId) {
  57. if (!userId) {
  58. return { v1Import: { status: 'mustLogin' } }
  59. } else {
  60. const docInfo = await TokenAccessHandler.promises.getV1DocInfo(
  61. token,
  62. userId
  63. )
  64. // This should not happen anymore, but it does show
  65. // a nice "contact support" message, so it can stay
  66. if (!docInfo) {
  67. return { v1Import: { status: 'cannotImport' } }
  68. }
  69. if (!docInfo.exists) {
  70. return null
  71. }
  72. if (docInfo.exported) {
  73. return null
  74. }
  75. return {
  76. v1Import: {
  77. status: 'canDownloadZip',
  78. projectId: token,
  79. hasOwner: docInfo.has_owner,
  80. name: docInfo.name || 'Untitled',
  81. brandInfo: docInfo.brand_info,
  82. },
  83. }
  84. }
  85. }
  86. async function _isOverleafStaff(userId) {
  87. const emails = await UserGetter.promises.getUserConfirmedEmails(userId)
  88. const adminDomains = Settings.adminDomains ?? []
  89. return emails.some(email =>
  90. adminDomains.some(adminDomain => email.email.endsWith(`@${adminDomain}`))
  91. )
  92. }
  93. async function tokenAccessPage(req, res, next) {
  94. const { token } = req.params
  95. if (!TokenAccessHandler.isValidToken(token)) {
  96. return next(new Errors.NotFoundError())
  97. }
  98. try {
  99. if (TokenAccessHandler.isReadOnlyToken(token)) {
  100. const docPublishedInfo =
  101. await TokenAccessHandler.promises.getV1DocPublishedInfo(token)
  102. if (docPublishedInfo.allow === false) {
  103. return res.redirect(302, docPublishedInfo.published_path)
  104. }
  105. }
  106. res.render('project/token/access-react', {
  107. postUrl: makePostUrl(token),
  108. })
  109. } catch (err) {
  110. return next(
  111. OError.tag(err, 'error while rendering token access page', { token })
  112. )
  113. }
  114. }
  115. async function checkAndGetProjectOrResponseAction(
  116. tokenType,
  117. token,
  118. userId,
  119. tokenHashPrefix,
  120. req,
  121. res,
  122. next
  123. ) {
  124. const isAnonymousUser = !userId
  125. if (
  126. isAnonymousUser &&
  127. tokenType === TokenAccessHandler.TOKEN_TYPES.READ_AND_WRITE &&
  128. !TokenAccessHandler.ANONYMOUS_READ_AND_WRITE_ENABLED
  129. ) {
  130. logger.warn('[TokenAccess] deny anonymous read-and-write token access')
  131. let projectUrlWithToken = TokenAccessHandler.makeTokenUrl(token)
  132. if (tokenHashPrefix && tokenHashPrefix.startsWith('#')) {
  133. projectUrlWithToken += `${tokenHashPrefix}`
  134. }
  135. AuthenticationController.setRedirectInSession(req, projectUrlWithToken)
  136. return [
  137. null,
  138. () => {
  139. res.json({
  140. redirect: '/restricted',
  141. anonWriteAccessDenied: true,
  142. })
  143. },
  144. { action: 'denied anonymous read-and-write token access' },
  145. ]
  146. }
  147. // Try to get the project, and/or an alternative action to take.
  148. // Returns a tuple of [project, action]
  149. const project = await TokenAccessHandler.promises.getProjectByToken(
  150. tokenType,
  151. token
  152. )
  153. if (!project) {
  154. if (Settings.overleaf) {
  155. const v1ImportData = await _handleV1Project(token, userId)
  156. return [
  157. null,
  158. () => {
  159. if (v1ImportData) {
  160. res.json(v1ImportData)
  161. } else {
  162. res.sendStatus(404)
  163. }
  164. },
  165. { action: v1ImportData ? 'import v1' : '404' },
  166. ]
  167. } else {
  168. return [null, null, { action: '404' }]
  169. }
  170. }
  171. const projectId = project._id
  172. const tokenAccessEnabled =
  173. TokenAccessHandler.tokenAccessEnabledForProject(project)
  174. if (isAnonymousUser && tokenAccessEnabled) {
  175. if (tokenType === TokenAccessHandler.TOKEN_TYPES.READ_AND_WRITE) {
  176. if (TokenAccessHandler.ANONYMOUS_READ_AND_WRITE_ENABLED) {
  177. logger.debug({ projectId }, 'granting read-write anonymous access')
  178. TokenAccessHandler.grantSessionTokenAccess(req, projectId, token)
  179. return [
  180. null,
  181. () => {
  182. res.json({
  183. redirect: `/project/${projectId}`,
  184. grantAnonymousAccess: tokenType,
  185. })
  186. },
  187. { projectId, action: 'granting read-write anonymous access' },
  188. ]
  189. } else {
  190. // anonymous read-and-write token access should have been denied already
  191. throw new Error(
  192. 'unreachable: anonymous read-and-write token access bug'
  193. )
  194. }
  195. } else if (tokenType === TokenAccessHandler.TOKEN_TYPES.READ_ONLY) {
  196. logger.debug({ projectId }, 'granting read-only anonymous access')
  197. TokenAccessHandler.grantSessionTokenAccess(req, projectId, token)
  198. return [
  199. null,
  200. () => {
  201. res.json({
  202. redirect: `/project/${projectId}`,
  203. grantAnonymousAccess: tokenType,
  204. })
  205. },
  206. { projectId, action: 'granting read-only anonymous access' },
  207. ]
  208. } else {
  209. throw new Error('unreachable')
  210. }
  211. }
  212. const userHasPrivilege = await _userAlreadyHasHigherPrivilege(
  213. userId,
  214. projectId,
  215. tokenType
  216. )
  217. if (userHasPrivilege) {
  218. return [
  219. null,
  220. () => {
  221. res.json({ redirect: `/project/${project._id}`, higherAccess: true })
  222. },
  223. { projectId, action: 'user already has higher or same privilege' },
  224. ]
  225. }
  226. // Handle admin redirect
  227. // If the project owner is an internal staff (using @overleaf.com email),
  228. // the admin will join the project "for real".
  229. // If the project owner is a external user
  230. // the admin will be redirect to admin domain to view the project.
  231. if (canRedirectToAdminDomain(SessionManager.getSessionUser(req.session))) {
  232. const isProjectOwnerOverleafStaff = await _isOverleafStaff(
  233. project.owner_ref
  234. )
  235. if (isProjectOwnerOverleafStaff) {
  236. logger.warn(
  237. { projectId, userId },
  238. 'letting admin user join staff project'
  239. )
  240. } else {
  241. let projectUrlWithToken = TokenAccessHandler.makeTokenUrl(token)
  242. if (tokenHashPrefix && tokenHashPrefix.startsWith('#')) {
  243. projectUrlWithToken += `${tokenHashPrefix}`
  244. }
  245. return [
  246. null,
  247. () =>
  248. res.json({
  249. redirect: getSafeAdminDomainRedirect(projectUrlWithToken),
  250. }),
  251. { projectId, action: 'redirect admin user to admin domain' },
  252. ]
  253. }
  254. }
  255. if (!tokenAccessEnabled) {
  256. return [
  257. null,
  258. () => {
  259. next(new Errors.NotFoundError())
  260. },
  261. { projectId, action: 'token access not enabled' },
  262. ]
  263. }
  264. return [project, null, { projectId, action: 'continue' }]
  265. }
  266. async function grantTokenAccessReadAndWrite(req, res, next) {
  267. const { token } = req.params
  268. const { confirmedByUser, tokenHashPrefix } = req.body
  269. const userId = SessionManager.getLoggedInUserId(req.session)
  270. if (!TokenAccessHandler.isReadAndWriteToken(token)) {
  271. return res.sendStatus(400)
  272. }
  273. const tokenType = TokenAccessHandler.TOKEN_TYPES.READ_AND_WRITE
  274. try {
  275. const [project, action, logData] = await checkAndGetProjectOrResponseAction(
  276. tokenType,
  277. token,
  278. userId,
  279. tokenHashPrefix,
  280. req,
  281. res,
  282. next
  283. )
  284. TokenAccessHandler.checkTokenHashPrefix(
  285. token,
  286. tokenHashPrefix,
  287. tokenType,
  288. userId,
  289. logData
  290. )
  291. if (action) {
  292. return action()
  293. }
  294. if (!project) {
  295. return next(new Errors.NotFoundError())
  296. }
  297. if (!confirmedByUser) {
  298. return res.json({
  299. requireAccept: {
  300. projectName: project.name,
  301. },
  302. })
  303. }
  304. const pendingEditor =
  305. !(await LimitationsManager.promises.canAcceptEditCollaboratorInvite(
  306. project._id
  307. ))
  308. await ProjectAuditLogHandler.promises.addEntry(
  309. project._id,
  310. 'accept-via-link-sharing',
  311. userId,
  312. req.ip,
  313. {
  314. privileges: pendingEditor ? 'readOnly' : 'readAndWrite',
  315. ...(pendingEditor && { pendingEditor: true }),
  316. }
  317. )
  318. AnalyticsManager.recordEventForUserInBackground(userId, 'project-joined', {
  319. mode: pendingEditor ? 'read-only' : 'read-write',
  320. projectId: project._id.toString(),
  321. ...(pendingEditor && { pendingEditor: true }),
  322. })
  323. await CollaboratorsHandler.promises.addUserIdToProject(
  324. project._id,
  325. undefined,
  326. userId,
  327. pendingEditor
  328. ? PrivilegeLevels.READ_ONLY
  329. : PrivilegeLevels.READ_AND_WRITE,
  330. { pendingEditor }
  331. )
  332. // remove pending invite and notification
  333. const userEmails = await UserGetter.promises.getUserConfirmedEmails(userId)
  334. await CollaboratorsInviteHandler.promises.revokeInviteForUser(
  335. project._id,
  336. userEmails
  337. )
  338. // Should be a noop if the user is already a member,
  339. // and would redirect transparently into the project.
  340. EditorRealTimeController.emitToRoom(
  341. project._id,
  342. 'project:membership:changed',
  343. { members: true, invites: true }
  344. )
  345. return res.json({
  346. redirect: `/project/${project._id}`,
  347. })
  348. } catch (err) {
  349. return next(
  350. OError.tag(
  351. err,
  352. 'error while trying to grant read-and-write token access',
  353. { token }
  354. )
  355. )
  356. }
  357. }
  358. async function grantTokenAccessReadOnly(req, res, next) {
  359. const { token } = req.params
  360. const { confirmedByUser, tokenHashPrefix } = req.body
  361. const userId = SessionManager.getLoggedInUserId(req.session)
  362. if (!TokenAccessHandler.isReadOnlyToken(token)) {
  363. return res.sendStatus(400)
  364. }
  365. const tokenType = TokenAccessHandler.TOKEN_TYPES.READ_ONLY
  366. const docPublishedInfo =
  367. await TokenAccessHandler.promises.getV1DocPublishedInfo(token)
  368. if (docPublishedInfo.allow === false) {
  369. return res.json({ redirect: docPublishedInfo.published_path })
  370. }
  371. try {
  372. const [project, action, logData] = await checkAndGetProjectOrResponseAction(
  373. tokenType,
  374. token,
  375. userId,
  376. tokenHashPrefix,
  377. req,
  378. res,
  379. next
  380. )
  381. TokenAccessHandler.checkTokenHashPrefix(
  382. token,
  383. tokenHashPrefix,
  384. tokenType,
  385. userId,
  386. logData
  387. )
  388. if (action) {
  389. return action()
  390. }
  391. if (!project) {
  392. return next(new Errors.NotFoundError())
  393. }
  394. if (!confirmedByUser) {
  395. return res.json({
  396. requireAccept: {
  397. projectName: project.name,
  398. },
  399. })
  400. }
  401. if (!project.tokenAccessReadOnly_refs.some(id => id.equals(userId))) {
  402. await ProjectAuditLogHandler.promises.addEntry(
  403. project._id,
  404. 'join-via-token',
  405. userId,
  406. req.ip,
  407. { privileges: 'readOnly' }
  408. )
  409. }
  410. await TokenAccessHandler.promises.addReadOnlyUserToProject(
  411. userId,
  412. project._id
  413. )
  414. return res.json({
  415. redirect: `/project/${project._id}`,
  416. tokenAccessGranted: tokenType,
  417. })
  418. } catch (err) {
  419. return next(
  420. OError.tag(err, 'error while trying to grant read-only token access', {
  421. token,
  422. })
  423. )
  424. }
  425. }
  426. async function ensureUserCanUseSharingUpdatesConsentPage(req, res, next) {
  427. const { Project_id: projectId } = req.params
  428. const userId = SessionManager.getLoggedInUserId(req.session)
  429. const project = await ProjectGetter.promises.getProject(projectId, {
  430. owner_ref: 1,
  431. })
  432. if (!project) {
  433. throw new Errors.NotFoundError()
  434. }
  435. const isReadWriteTokenMember =
  436. await CollaboratorsGetter.promises.userIsReadWriteTokenMember(
  437. userId,
  438. projectId
  439. )
  440. if (!isReadWriteTokenMember) {
  441. // If the user is not a read write token member, there are no actions to take
  442. return AsyncFormHelper.redirect(req, res, `/project/${projectId}`)
  443. }
  444. const isReadWriteMember =
  445. await CollaboratorsGetter.promises.isUserInvitedReadWriteMemberOfProject(
  446. userId,
  447. projectId
  448. )
  449. if (isReadWriteMember) {
  450. // If the user is already an invited editor, the actions don't make sense
  451. return AsyncFormHelper.redirect(req, res, `/project/${projectId}`)
  452. }
  453. next()
  454. }
  455. async function sharingUpdatesConsent(req, res, next) {
  456. const { Project_id: projectId } = req.params
  457. AnalyticsManager.recordEventForSession(req.session, 'notification-prompt', {
  458. page: req.path,
  459. name: 'link-sharing-collaborator',
  460. })
  461. res.render('project/token/sharing-updates', {
  462. projectId,
  463. })
  464. }
  465. async function moveReadWriteToCollaborators(req, res, next) {
  466. const { Project_id: projectId } = req.params
  467. const userId = SessionManager.getLoggedInUserId(req.session)
  468. const project = await ProjectGetter.promises.getProject(projectId, {
  469. owner_ref: 1,
  470. })
  471. const isInvitedMember =
  472. await CollaboratorsGetter.promises.isUserInvitedMemberOfProject(
  473. userId,
  474. projectId
  475. )
  476. const pendingEditor =
  477. !(await LimitationsManager.promises.canAcceptEditCollaboratorInvite(
  478. project._id
  479. ))
  480. await ProjectAuditLogHandler.promises.addEntry(
  481. projectId,
  482. 'accept-via-link-sharing',
  483. userId,
  484. req.ip,
  485. {
  486. privileges: pendingEditor
  487. ? PrivilegeLevels.READ_ONLY
  488. : PrivilegeLevels.READ_AND_WRITE,
  489. tokenMember: true,
  490. invitedMember: isInvitedMember,
  491. ...(pendingEditor && { pendingEditor: true }),
  492. }
  493. )
  494. if (isInvitedMember) {
  495. // Read only invited viewer who is gaining edit access via link sharing
  496. await TokenAccessHandler.promises.removeReadAndWriteUserFromProject(
  497. userId,
  498. projectId
  499. )
  500. await CollaboratorsHandler.promises.setCollaboratorPrivilegeLevel(
  501. projectId,
  502. userId,
  503. pendingEditor
  504. ? PrivilegeLevels.READ_ONLY
  505. : PrivilegeLevels.READ_AND_WRITE,
  506. { pendingEditor }
  507. )
  508. } else {
  509. // Normal case, not invited, joining via link sharing
  510. await TokenAccessHandler.promises.removeReadAndWriteUserFromProject(
  511. userId,
  512. projectId
  513. )
  514. await CollaboratorsHandler.promises.addUserIdToProject(
  515. projectId,
  516. undefined,
  517. userId,
  518. pendingEditor
  519. ? PrivilegeLevels.READ_ONLY
  520. : PrivilegeLevels.READ_AND_WRITE,
  521. { pendingEditor }
  522. )
  523. }
  524. EditorRealTimeController.emitToRoom(projectId, 'project:membership:changed', {
  525. members: true,
  526. })
  527. res.sendStatus(204)
  528. }
  529. async function moveReadWriteToReadOnly(req, res, next) {
  530. const { Project_id: projectId } = req.params
  531. const userId = SessionManager.getLoggedInUserId(req.session)
  532. await ProjectAuditLogHandler.promises.addEntry(
  533. projectId,
  534. 'readonly-via-sharing-updates',
  535. userId,
  536. req.ip
  537. )
  538. await TokenAccessHandler.promises.moveReadAndWriteUserToReadOnly(
  539. userId,
  540. projectId
  541. )
  542. res.sendStatus(204)
  543. }
  544. export default {
  545. READ_ONLY_TOKEN_PATTERN: TokenAccessHandler.READ_ONLY_TOKEN_PATTERN,
  546. READ_AND_WRITE_TOKEN_PATTERN: TokenAccessHandler.READ_AND_WRITE_TOKEN_PATTERN,
  547. tokenAccessPage: expressify(tokenAccessPage),
  548. grantTokenAccessReadOnly: expressify(grantTokenAccessReadOnly),
  549. grantTokenAccessReadAndWrite: expressify(grantTokenAccessReadAndWrite),
  550. ensureUserCanUseSharingUpdatesConsentPage: expressify(
  551. ensureUserCanUseSharingUpdatesConsentPage
  552. ),
  553. sharingUpdatesConsent: expressify(sharingUpdatesConsent),
  554. moveReadWriteToCollaborators: expressify(moveReadWriteToCollaborators),
  555. moveReadWriteToReadOnly: expressify(moveReadWriteToReadOnly),
  556. }