TokenAccessController.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. const AuthenticationController = require('../Authentication/AuthenticationController')
  2. const SessionManager = require('../Authentication/SessionManager')
  3. const TokenAccessHandler = require('./TokenAccessHandler')
  4. const Errors = require('../Errors/Errors')
  5. const logger = require('@overleaf/logger')
  6. const settings = require('@overleaf/settings')
  7. const OError = require('@overleaf/o-error')
  8. const { expressify } = require('@overleaf/promise-utils')
  9. const AuthorizationManager = require('../Authorization/AuthorizationManager')
  10. const PrivilegeLevels = require('../Authorization/PrivilegeLevels')
  11. const {
  12. handleAdminDomainRedirect,
  13. } = require('../Authorization/AuthorizationMiddleware')
  14. const ProjectAuditLogHandler = require('../Project/ProjectAuditLogHandler')
  15. const SplitTestHandler = require('../SplitTests/SplitTestHandler')
  16. const orderedPrivilegeLevels = [
  17. PrivilegeLevels.NONE,
  18. PrivilegeLevels.READ_ONLY,
  19. PrivilegeLevels.READ_AND_WRITE,
  20. PrivilegeLevels.OWNER,
  21. ]
  22. async function _userAlreadyHasHigherPrivilege(userId, projectId, tokenType) {
  23. if (!Object.values(TokenAccessHandler.TOKEN_TYPES).includes(tokenType)) {
  24. throw new Error('bad token type')
  25. }
  26. if (!userId) {
  27. return false
  28. }
  29. const privilegeLevel =
  30. await AuthorizationManager.promises.getPrivilegeLevelForProject(
  31. userId,
  32. projectId
  33. )
  34. return (
  35. orderedPrivilegeLevels.indexOf(privilegeLevel) >=
  36. orderedPrivilegeLevels.indexOf(tokenType)
  37. )
  38. }
  39. const makePostUrl = token => {
  40. if (TokenAccessHandler.isReadAndWriteToken(token)) {
  41. return `/${token}/grant`
  42. } else if (TokenAccessHandler.isReadOnlyToken(token)) {
  43. return `/read/${token}/grant`
  44. } else {
  45. throw new Error('invalid token type')
  46. }
  47. }
  48. async function _handleV1Project(token, userId) {
  49. if (!userId) {
  50. return { v1Import: { status: 'mustLogin' } }
  51. } else {
  52. const docInfo = await TokenAccessHandler.promises.getV1DocInfo(
  53. token,
  54. userId
  55. )
  56. // This should not happen anymore, but it does show
  57. // a nice "contact support" message, so it can stay
  58. if (!docInfo) {
  59. return { v1Import: { status: 'cannotImport' } }
  60. }
  61. if (!docInfo.exists) {
  62. return null
  63. }
  64. if (docInfo.exported) {
  65. return null
  66. }
  67. return {
  68. v1Import: {
  69. status: 'canDownloadZip',
  70. projectId: token,
  71. hasOwner: docInfo.has_owner,
  72. name: docInfo.name || 'Untitled',
  73. brandInfo: docInfo.brand_info,
  74. },
  75. }
  76. }
  77. }
  78. async function tokenAccessPage(req, res, next) {
  79. const { token } = req.params
  80. if (!TokenAccessHandler.isValidToken(token)) {
  81. return next(new Errors.NotFoundError())
  82. }
  83. if (handleAdminDomainRedirect(req, res)) {
  84. // Admin users do not join the project, but view it on the admin domain.
  85. return
  86. }
  87. try {
  88. if (TokenAccessHandler.isReadOnlyToken(token)) {
  89. const docPublishedInfo =
  90. await TokenAccessHandler.promises.getV1DocPublishedInfo(token)
  91. if (docPublishedInfo.allow === false) {
  92. return res.redirect(302, docPublishedInfo.published_path)
  93. }
  94. }
  95. const { variant } = await SplitTestHandler.promises.getAssignment(
  96. req,
  97. res,
  98. 'token-access-page'
  99. )
  100. const view =
  101. variant === 'react'
  102. ? 'project/token/access-react'
  103. : 'project/token/access'
  104. res.render(view, {
  105. postUrl: makePostUrl(token),
  106. })
  107. } catch (err) {
  108. return next(
  109. OError.tag(err, 'error while rendering token access page', { token })
  110. )
  111. }
  112. }
  113. async function checkAndGetProjectOrResponseAction(
  114. tokenType,
  115. token,
  116. userId,
  117. tokenHashPrefix,
  118. req,
  119. res,
  120. next
  121. ) {
  122. const isAnonymousUser = !userId
  123. if (
  124. isAnonymousUser &&
  125. tokenType === TokenAccessHandler.TOKEN_TYPES.READ_AND_WRITE &&
  126. !TokenAccessHandler.ANONYMOUS_READ_AND_WRITE_ENABLED
  127. ) {
  128. logger.warn('[TokenAccess] deny anonymous read-and-write token access')
  129. let projectUrlWithToken = TokenAccessHandler.makeTokenUrl(token)
  130. if (tokenHashPrefix && tokenHashPrefix.startsWith('#')) {
  131. projectUrlWithToken += `${tokenHashPrefix}`
  132. }
  133. AuthenticationController.setRedirectInSession(req, projectUrlWithToken)
  134. return [
  135. null,
  136. () => {
  137. res.json({
  138. redirect: '/restricted',
  139. anonWriteAccessDenied: true,
  140. })
  141. },
  142. { action: 'denied anonymous read-and-write token access' },
  143. ]
  144. }
  145. // Try to get the project, and/or an alternative action to take.
  146. // Returns a tuple of [project, action]
  147. const project = await TokenAccessHandler.promises.getProjectByToken(
  148. tokenType,
  149. token
  150. )
  151. if (!project) {
  152. if (settings.overleaf) {
  153. const v1ImportData = await _handleV1Project(token, userId)
  154. return [
  155. null,
  156. () => {
  157. if (v1ImportData) {
  158. res.json(v1ImportData)
  159. } else {
  160. res.sendStatus(404)
  161. }
  162. },
  163. { action: v1ImportData ? 'import v1' : '404' },
  164. ]
  165. } else {
  166. return [null, null, { action: '404' }]
  167. }
  168. }
  169. const projectId = project._id
  170. const tokenAccessEnabled =
  171. TokenAccessHandler.tokenAccessEnabledForProject(project)
  172. if (isAnonymousUser && tokenAccessEnabled) {
  173. if (tokenType === TokenAccessHandler.TOKEN_TYPES.READ_AND_WRITE) {
  174. if (TokenAccessHandler.ANONYMOUS_READ_AND_WRITE_ENABLED) {
  175. logger.debug({ projectId }, 'granting read-write anonymous access')
  176. TokenAccessHandler.grantSessionTokenAccess(req, projectId, token)
  177. return [
  178. null,
  179. () => {
  180. res.json({
  181. redirect: `/project/${projectId}`,
  182. grantAnonymousAccess: tokenType,
  183. })
  184. },
  185. { projectId, action: 'granting read-write anonymous access' },
  186. ]
  187. } else {
  188. // anonymous read-and-write token access should have been denied already
  189. throw new Error(
  190. 'unreachable: anonymous read-and-write token access bug'
  191. )
  192. }
  193. } else if (tokenType === TokenAccessHandler.TOKEN_TYPES.READ_ONLY) {
  194. logger.debug({ projectId }, 'granting read-only anonymous access')
  195. TokenAccessHandler.grantSessionTokenAccess(req, projectId, token)
  196. return [
  197. null,
  198. () => {
  199. res.json({
  200. redirect: `/project/${projectId}`,
  201. grantAnonymousAccess: tokenType,
  202. })
  203. },
  204. { projectId, action: 'granting read-only anonymous access' },
  205. ]
  206. } else {
  207. throw new Error('unreachable')
  208. }
  209. }
  210. const userHasPrivilege = await _userAlreadyHasHigherPrivilege(
  211. userId,
  212. projectId,
  213. tokenType
  214. )
  215. if (userHasPrivilege) {
  216. return [
  217. null,
  218. () => {
  219. res.json({ redirect: `/project/${project._id}`, higherAccess: true })
  220. },
  221. { projectId, action: 'user already has higher or same privilege' },
  222. ]
  223. }
  224. if (!tokenAccessEnabled) {
  225. return [
  226. null,
  227. () => {
  228. next(new Errors.NotFoundError())
  229. },
  230. { projectId, action: 'token access not enabled' },
  231. ]
  232. }
  233. return [project, null, { projectId, action: 'continue' }]
  234. }
  235. async function grantTokenAccessReadAndWrite(req, res, next) {
  236. const { token } = req.params
  237. const { confirmedByUser, tokenHashPrefix } = req.body
  238. const userId = SessionManager.getLoggedInUserId(req.session)
  239. if (!TokenAccessHandler.isReadAndWriteToken(token)) {
  240. return res.sendStatus(400)
  241. }
  242. const tokenType = TokenAccessHandler.TOKEN_TYPES.READ_AND_WRITE
  243. try {
  244. const [project, action, logData] = await checkAndGetProjectOrResponseAction(
  245. tokenType,
  246. token,
  247. userId,
  248. tokenHashPrefix,
  249. req,
  250. res,
  251. next
  252. )
  253. TokenAccessHandler.checkTokenHashPrefix(
  254. token,
  255. tokenHashPrefix,
  256. tokenType,
  257. userId,
  258. logData
  259. )
  260. if (action) {
  261. return action()
  262. }
  263. if (!project) {
  264. return next(new Errors.NotFoundError())
  265. }
  266. if (!confirmedByUser) {
  267. return res.json({
  268. requireAccept: {
  269. projectName: project.name,
  270. },
  271. })
  272. }
  273. if (!project.tokenAccessReadAndWrite_refs.some(id => id.equals(userId))) {
  274. await ProjectAuditLogHandler.promises.addEntry(
  275. project._id,
  276. 'join-via-token',
  277. userId,
  278. req.ip,
  279. { privileges: 'readAndWrite' }
  280. )
  281. }
  282. await TokenAccessHandler.promises.addReadAndWriteUserToProject(
  283. userId,
  284. project._id
  285. )
  286. return res.json({
  287. redirect: `/project/${project._id}`,
  288. tokenAccessGranted: tokenType,
  289. })
  290. } catch (err) {
  291. return next(
  292. OError.tag(
  293. err,
  294. 'error while trying to grant read-and-write token access',
  295. { token }
  296. )
  297. )
  298. }
  299. }
  300. async function grantTokenAccessReadOnly(req, res, next) {
  301. const { token } = req.params
  302. const { confirmedByUser, tokenHashPrefix } = req.body
  303. const userId = SessionManager.getLoggedInUserId(req.session)
  304. if (!TokenAccessHandler.isReadOnlyToken(token)) {
  305. return res.sendStatus(400)
  306. }
  307. const tokenType = TokenAccessHandler.TOKEN_TYPES.READ_ONLY
  308. const docPublishedInfo =
  309. await TokenAccessHandler.promises.getV1DocPublishedInfo(token)
  310. if (docPublishedInfo.allow === false) {
  311. return res.json({ redirect: docPublishedInfo.published_path })
  312. }
  313. try {
  314. const [project, action, logData] = await checkAndGetProjectOrResponseAction(
  315. tokenType,
  316. token,
  317. userId,
  318. tokenHashPrefix,
  319. req,
  320. res,
  321. next
  322. )
  323. TokenAccessHandler.checkTokenHashPrefix(
  324. token,
  325. tokenHashPrefix,
  326. tokenType,
  327. userId,
  328. logData
  329. )
  330. if (action) {
  331. return action()
  332. }
  333. if (!project) {
  334. return next(new Errors.NotFoundError())
  335. }
  336. if (!confirmedByUser) {
  337. return res.json({
  338. requireAccept: {
  339. projectName: project.name,
  340. },
  341. })
  342. }
  343. if (!project.tokenAccessReadOnly_refs.some(id => id.equals(userId))) {
  344. await ProjectAuditLogHandler.promises.addEntry(
  345. project._id,
  346. 'join-via-token',
  347. userId,
  348. req.ip,
  349. { privileges: 'readOnly' }
  350. )
  351. }
  352. await TokenAccessHandler.promises.addReadOnlyUserToProject(
  353. userId,
  354. project._id
  355. )
  356. return res.json({
  357. redirect: `/project/${project._id}`,
  358. tokenAccessGranted: tokenType,
  359. })
  360. } catch (err) {
  361. return next(
  362. OError.tag(err, 'error while trying to grant read-only token access', {
  363. token,
  364. })
  365. )
  366. }
  367. }
  368. module.exports = {
  369. READ_ONLY_TOKEN_PATTERN: TokenAccessHandler.READ_ONLY_TOKEN_PATTERN,
  370. READ_AND_WRITE_TOKEN_PATTERN: TokenAccessHandler.READ_AND_WRITE_TOKEN_PATTERN,
  371. tokenAccessPage: expressify(tokenAccessPage),
  372. grantTokenAccessReadOnly: expressify(grantTokenAccessReadOnly),
  373. grantTokenAccessReadAndWrite: expressify(grantTokenAccessReadAndWrite),
  374. }