HistoryController.mjs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. // @ts-check
  2. import { setTimeout } from 'node:timers/promises'
  3. import { pipeline } from 'node:stream/promises'
  4. import OError from '@overleaf/o-error'
  5. import logger from '@overleaf/logger'
  6. import { expressify } from '@overleaf/promise-utils'
  7. import {
  8. fetchStream,
  9. fetchStreamWithResponse,
  10. fetchJson,
  11. fetchNothing,
  12. RequestFailedError,
  13. } from '@overleaf/fetch-utils'
  14. import settings from '@overleaf/settings'
  15. /** @type {any} */
  16. import SessionManager from '../Authentication/SessionManager.mjs'
  17. import UserGetter from '../User/UserGetter.mjs'
  18. /** @type {any} */
  19. import ProjectGetter from '../Project/ProjectGetter.mjs'
  20. import Errors from '../Errors/Errors.js'
  21. /** @type {any} */
  22. import HistoryManager from './HistoryManager.mjs'
  23. /** @type {any} */
  24. import ProjectDetailsHandler from '../Project/ProjectDetailsHandler.mjs'
  25. /** @type {any} */
  26. import ProjectEntityUpdateHandler from '../Project/ProjectEntityUpdateHandler.mjs'
  27. /** @type {any} */
  28. import RestoreManager from './RestoreManager.mjs'
  29. import { prepareZipAttachment } from '../../infrastructure/Response.mjs'
  30. import Features from '../../infrastructure/Features.mjs'
  31. import { z, zz, parseReq } from '../../infrastructure/Validation.mjs'
  32. /** @type {any} */
  33. import ProjectAuditLogHandler from '../Project/ProjectAuditLogHandler.mjs'
  34. // Number of seconds after which the browser should send a request to revalidate
  35. // blobs
  36. const REVALIDATE_BLOB_AFTER_SECONDS = 86400 // 1 day
  37. // Number of seconds during which the browser can serve a stale response while
  38. // revalidating
  39. const STALE_WHILE_REVALIDATE_SECONDS = 365 * 86400 // 1 year
  40. const MAX_HISTORY_ZIP_ATTEMPTS = 40
  41. /**
  42. * @param {any} req
  43. * @param {any} res
  44. */
  45. async function getBlob(req, res) {
  46. await requestBlob('GET', req, res)
  47. }
  48. /**
  49. * @param {any} req
  50. * @param {any} res
  51. */
  52. async function headBlob(req, res) {
  53. await requestBlob('HEAD', req, res)
  54. }
  55. const requestBlobSchema = z.object({
  56. params: z.object({
  57. project_id: zz.coercedObjectId(),
  58. hash: zz.hex().length(40),
  59. }),
  60. query: z.object({
  61. fallback: zz.coercedObjectId().optional(),
  62. }),
  63. })
  64. /**
  65. * @param {any} method
  66. * @param {any} req
  67. * @param {any} res
  68. */
  69. async function requestBlob(method, req, res) {
  70. const { params } = parseReq(req, requestBlobSchema)
  71. const { project_id: projectId, hash } = params
  72. // Handle conditional GET request
  73. if (req.get('If-None-Match') === hash) {
  74. setBlobCacheHeaders(res, hash)
  75. return res.status(304).end()
  76. }
  77. const range = req.get('Range')
  78. let stream, contentLength, contentRange
  79. try {
  80. ;({ stream, contentLength, contentRange } =
  81. await HistoryManager.promises.requestBlobWithProjectId(
  82. projectId,
  83. hash,
  84. method,
  85. range
  86. ))
  87. } catch (/** @type {any} */ err) {
  88. if (err instanceof Errors.NotFoundError) return res.status(404).end()
  89. throw err
  90. }
  91. if (contentLength) res.setHeader('Content-Length', contentLength)
  92. if (contentRange) {
  93. res.setHeader('Content-Range', contentRange)
  94. res.status(206) // Partial Content
  95. }
  96. res.setHeader('Content-Type', 'application/octet-stream')
  97. setBlobCacheHeaders(res, hash)
  98. // Disable buffering in nginx
  99. res.setHeader('X-Accel-Buffering', 'no')
  100. try {
  101. await pipeline(stream, res)
  102. } catch (/** @type {any} */ err) {
  103. // If the downstream request is cancelled, we get an
  104. // ERR_STREAM_PREMATURE_CLOSE, ignore these "errors".
  105. if (!isPrematureClose(err)) {
  106. throw err
  107. }
  108. }
  109. }
  110. /**
  111. * @param {any} res
  112. * @param {any} etag
  113. */
  114. function setBlobCacheHeaders(res, etag) {
  115. // Blobs are immutable, so they can in principle be cached indefinitely. Here,
  116. // we ask the browser to cache them for some time, but then check back
  117. // regularly in case they changed (even though they shouldn't). This is a
  118. // precaution in case a bug makes us send bad data through that endpoint.
  119. res.set(
  120. 'Cache-Control',
  121. `private, max-age=${REVALIDATE_BLOB_AFTER_SECONDS}, stale-while-revalidate=${STALE_WHILE_REVALIDATE_SECONDS}`
  122. )
  123. res.set('ETag', etag)
  124. }
  125. /**
  126. * @param {any} req
  127. * @param {any} res
  128. * @param {any} next
  129. */
  130. async function proxyToHistoryApi(req, res, next) {
  131. const userId = SessionManager.getLoggedInUserId(req.session)
  132. const url = settings.apis.project_history.url + req.url
  133. const { stream, response } = await fetchStreamWithResponse(url, {
  134. method: req.method,
  135. headers: { 'X-User-Id': userId },
  136. })
  137. const contentType = response.headers.get('Content-Type')
  138. const contentLength = response.headers.get('Content-Length')
  139. if (contentType != null) {
  140. res.set('Content-Type', contentType)
  141. }
  142. if (contentLength != null) {
  143. res.set('Content-Length', contentLength)
  144. }
  145. try {
  146. await pipeline(stream, res)
  147. } catch (/** @type {any} */ err) {
  148. // If the downstream request is cancelled, we get an
  149. // ERR_STREAM_PREMATURE_CLOSE.
  150. if (!isPrematureClose(err)) {
  151. throw err
  152. }
  153. }
  154. }
  155. /**
  156. * @param {any} req
  157. * @param {any} res
  158. * @param {any} next
  159. */
  160. async function proxyToHistoryApiAndInjectUserDetails(req, res, next) {
  161. const userId = SessionManager.getLoggedInUserId(req.session)
  162. const url = settings.apis.project_history.url + req.url
  163. const body = await fetchJson(url, {
  164. method: req.method,
  165. headers: { 'X-User-Id': userId },
  166. })
  167. const data = await HistoryManager.promises.injectUserDetails(body)
  168. res.json(data)
  169. }
  170. /**
  171. * @param {any} req
  172. * @param {any} res
  173. * @param {any} next
  174. */
  175. async function resyncProjectHistory(req, res, next) {
  176. // increase timeout to 6 minutes
  177. res.setTimeout(6 * 60 * 1000)
  178. const projectId = req.params.Project_id
  179. const opts = {}
  180. const historyRangesMigration = req.body.historyRangesMigration
  181. if (historyRangesMigration) {
  182. opts.historyRangesMigration = historyRangesMigration
  183. }
  184. if (req.body.resyncProjectStructureOnly) {
  185. opts.resyncProjectStructureOnly = req.body.resyncProjectStructureOnly
  186. }
  187. try {
  188. await ProjectEntityUpdateHandler.promises.resyncProjectHistory(
  189. projectId,
  190. opts
  191. )
  192. } catch (/** @type {any} */ err) {
  193. if (err instanceof Errors.ProjectHistoryDisabledError) {
  194. return res.sendStatus(404)
  195. } else {
  196. throw err
  197. }
  198. }
  199. res.sendStatus(204)
  200. }
  201. /**
  202. * @param {any} req
  203. * @param {any} res
  204. * @param {any} next
  205. */
  206. async function restoreFileFromV2(req, res, next) {
  207. const { project_id: projectId } = req.params
  208. const { version, pathname } = req.body
  209. const userId = SessionManager.getLoggedInUserId(req.session)
  210. const entity = await RestoreManager.promises.restoreFileFromV2(
  211. userId,
  212. projectId,
  213. version,
  214. pathname
  215. )
  216. ProjectAuditLogHandler.addEntryIfManagedInBackground(
  217. projectId,
  218. 'project-history-version-restored',
  219. userId,
  220. req.ip,
  221. {
  222. version,
  223. scope: 'file',
  224. pathname,
  225. restoredEntityId: entity._id,
  226. }
  227. )
  228. res.json({
  229. type: entity.type,
  230. id: entity._id,
  231. })
  232. }
  233. /**
  234. * @param {any} req
  235. * @param {any} res
  236. * @param {any} next
  237. */
  238. async function revertFile(req, res, next) {
  239. const { project_id: projectId } = req.params
  240. const { version, pathname } = req.body
  241. const userId = SessionManager.getLoggedInUserId(req.session)
  242. const entity = await RestoreManager.promises.revertFile(
  243. userId,
  244. projectId,
  245. version,
  246. pathname,
  247. {}
  248. )
  249. ProjectAuditLogHandler.addEntryIfManagedInBackground(
  250. projectId,
  251. 'project-history-version-restored',
  252. userId,
  253. req.ip,
  254. {
  255. version,
  256. scope: 'file',
  257. pathname,
  258. restoredEntityId: entity._id,
  259. }
  260. )
  261. res.json({
  262. type: entity.type,
  263. id: entity._id,
  264. })
  265. }
  266. /**
  267. * @param {any} req
  268. * @param {any} res
  269. * @param {any} next
  270. */
  271. async function revertProject(req, res, next) {
  272. const { project_id: projectId } = req.params
  273. const { version } = req.body
  274. const userId = SessionManager.getLoggedInUserId(req.session)
  275. const reverted = await RestoreManager.promises.revertProject(
  276. userId,
  277. projectId,
  278. version
  279. )
  280. ProjectAuditLogHandler.addEntryIfManagedInBackground(
  281. projectId,
  282. 'project-history-version-restored',
  283. userId,
  284. req.ip,
  285. {
  286. version,
  287. scope: 'project',
  288. restoredEntities: reverted,
  289. }
  290. )
  291. res.json(reverted)
  292. }
  293. /**
  294. * @param {any} req
  295. * @param {any} res
  296. * @param {any} next
  297. */
  298. async function getLabels(req, res, next) {
  299. const projectId = req.params.Project_id
  300. let labels = await fetchJson(
  301. `${settings.apis.project_history.url}/project/${projectId}/labels`
  302. )
  303. labels = await _enrichLabels(labels)
  304. res.json(labels)
  305. }
  306. /**
  307. * @param {any} req
  308. * @param {any} res
  309. * @param {any} next
  310. */
  311. async function createLabel(req, res, next) {
  312. const projectId = req.params.Project_id
  313. const { comment, version } = req.body
  314. const userId = SessionManager.getLoggedInUserId(req.session)
  315. let label = await fetchJson(
  316. `${settings.apis.project_history.url}/project/${projectId}/labels`,
  317. {
  318. method: 'POST',
  319. json: { comment, version, user_id: userId },
  320. }
  321. )
  322. label = await _enrichLabel(label)
  323. res.json(label)
  324. }
  325. /**
  326. * @param {any} label
  327. */
  328. async function _enrichLabel(label) {
  329. const newLabel = Object.assign({}, label)
  330. if (!label.user_id) {
  331. newLabel.user_display_name = _displayNameForUser(null)
  332. return newLabel
  333. }
  334. const user = await UserGetter.promises.getUser(label.user_id, {
  335. first_name: 1,
  336. last_name: 1,
  337. email: 1,
  338. })
  339. newLabel.user_display_name = _displayNameForUser(user)
  340. return newLabel
  341. }
  342. /**
  343. * @param {any} labels
  344. */
  345. async function _enrichLabels(labels) {
  346. if (!labels || !labels.length) {
  347. return []
  348. }
  349. const uniqueUsers = new Set(
  350. labels.map(/** @param {any} label */ label => label.user_id)
  351. )
  352. // For backwards compatibility, and for anonymously created labels in SP
  353. // expect missing user_id fields
  354. uniqueUsers.delete(undefined)
  355. if (!uniqueUsers.size) {
  356. return labels
  357. }
  358. const rawUsers = await UserGetter.promises.getUsers(Array.from(uniqueUsers), {
  359. first_name: 1,
  360. last_name: 1,
  361. email: 1,
  362. })
  363. const users = new Map(
  364. rawUsers.map(/** @param {any} user */ user => [String(user._id), user])
  365. )
  366. labels.forEach(
  367. /** @param {any} label */ label => {
  368. const user = users.get(label.user_id)
  369. label.user_display_name = _displayNameForUser(user)
  370. }
  371. )
  372. return labels
  373. }
  374. /**
  375. * @param {any} user
  376. */
  377. function _displayNameForUser(user) {
  378. if (user == null) {
  379. return 'Anonymous'
  380. }
  381. if (user.name) {
  382. return user.name
  383. }
  384. let name = [user.first_name, user.last_name]
  385. .filter(n => n != null)
  386. .join(' ')
  387. .trim()
  388. if (name === '') {
  389. name = user.email.split('@')[0]
  390. }
  391. if (!name) {
  392. return '?'
  393. }
  394. return name
  395. }
  396. /**
  397. * @param {any} req
  398. * @param {any} res
  399. * @param {any} next
  400. */
  401. async function deleteLabel(req, res, next) {
  402. const { Project_id: projectId, label_id: labelId } = req.params
  403. const userId = SessionManager.getLoggedInUserId(req.session)
  404. const project = await ProjectGetter.promises.getProject(projectId, {
  405. owner_ref: true,
  406. })
  407. // If the current user is the project owner, we can use the non-user-specific
  408. // delete label endpoint. Otherwise, we have to use the user-specific version
  409. // (which only deletes the label if it is owned by the user)
  410. const deleteEndpointUrl = project.owner_ref.equals(userId)
  411. ? `${settings.apis.project_history.url}/project/${projectId}/labels/${labelId}`
  412. : `${settings.apis.project_history.url}/project/${projectId}/user/${userId}/labels/${labelId}`
  413. await fetchNothing(deleteEndpointUrl, {
  414. method: 'DELETE',
  415. })
  416. res.sendStatus(204)
  417. }
  418. const downloadZipOfVersionSchema = z.object({
  419. params: z.object({
  420. project_id: zz.objectId(),
  421. version: z.coerce.number().int().min(0),
  422. }),
  423. })
  424. /**
  425. * @param {any} req
  426. * @param {any} res
  427. * @param {any} next
  428. */
  429. async function downloadZipOfVersion(req, res, next) {
  430. const { params } = parseReq(req, downloadZipOfVersionSchema)
  431. const { project_id: projectId, version } = params
  432. const userId = SessionManager.getLoggedInUserId(req.session)
  433. /** @type {any} */
  434. const project = await ProjectDetailsHandler.promises.getDetails(projectId)
  435. const v1Id =
  436. project.overleaf && project.overleaf.history && project.overleaf.history.id
  437. if (v1Id == null) {
  438. logger.error(
  439. { projectId, version },
  440. 'got request for zip version of non-v1 history project'
  441. )
  442. return res.sendStatus(402)
  443. }
  444. await _pipeHistoryZipToResponse(
  445. v1Id,
  446. version,
  447. `${project.name} (Version ${version})`,
  448. req,
  449. res
  450. )
  451. ProjectAuditLogHandler.addEntryIfManagedInBackground(
  452. projectId,
  453. 'project-history-version-downloaded',
  454. userId,
  455. req.ip,
  456. {
  457. version,
  458. projectName: project.name,
  459. }
  460. )
  461. }
  462. /**
  463. * @param {any} v1ProjectId
  464. * @param {any} version
  465. * @param {any} name
  466. * @param {any} req
  467. * @param {any} res
  468. */
  469. async function _pipeHistoryZipToResponse(v1ProjectId, version, name, req, res) {
  470. if (req.destroyed) {
  471. // client has disconnected -- skip project history api call and download
  472. return
  473. }
  474. // increase timeout to 6 minutes
  475. res.setTimeout(6 * 60 * 1000)
  476. const url = `${settings.apis.v1_history.url}/projects/${v1ProjectId}/version/${version}/zip`
  477. const basicAuth = {
  478. user: settings.apis.v1_history.user,
  479. password: settings.apis.v1_history.pass,
  480. }
  481. if (!Features.hasFeature('saas')) {
  482. let stream
  483. try {
  484. stream = await fetchStream(url, { basicAuth })
  485. } catch (/** @type {any} */ err) {
  486. if (err instanceof RequestFailedError && err.response.status === 404) {
  487. return res.sendStatus(404)
  488. } else {
  489. throw err
  490. }
  491. }
  492. prepareZipAttachment(res, `${name}.zip`)
  493. try {
  494. await pipeline(stream, res)
  495. } catch (/** @type {any} */ err) {
  496. // If the downstream request is cancelled, we get an
  497. // ERR_STREAM_PREMATURE_CLOSE.
  498. if (!isPrematureClose(err)) {
  499. throw err
  500. }
  501. }
  502. return
  503. }
  504. let body
  505. try {
  506. body = await fetchJson(url, { method: 'POST', basicAuth })
  507. } catch (/** @type {any} */ err) {
  508. if (err instanceof RequestFailedError && err.response.status === 404) {
  509. throw new Errors.NotFoundError('zip not found')
  510. } else {
  511. throw err
  512. }
  513. }
  514. if (req.destroyed) {
  515. // client has disconnected -- skip delayed s3 download
  516. return
  517. }
  518. if (!body.zipUrl) {
  519. throw new OError('Missing zipUrl, cannot fetch zip file', {
  520. v1ProjectId,
  521. body,
  522. })
  523. }
  524. // retry for about 6 minutes starting with short delay
  525. let retryDelay = 2000
  526. let attempt = 0
  527. while (true) {
  528. attempt += 1
  529. await setTimeout(retryDelay)
  530. if (req.destroyed) {
  531. // client has disconnected -- skip s3 download
  532. return
  533. }
  534. // increase delay by 1 second up to 10
  535. if (retryDelay < 10000) {
  536. retryDelay += 1000
  537. }
  538. try {
  539. const stream = await fetchStream(body.zipUrl)
  540. prepareZipAttachment(res, `${name}.zip`)
  541. await pipeline(stream, res)
  542. } catch (/** @type {any} */ err) {
  543. if (attempt > MAX_HISTORY_ZIP_ATTEMPTS) {
  544. throw err
  545. }
  546. if (err instanceof RequestFailedError && err.response.status === 404) {
  547. // File not ready yet. Retry.
  548. continue
  549. } else if (isPrematureClose(err)) {
  550. // Downstream request cancelled. Retry.
  551. continue
  552. } else {
  553. // Unknown error. Log and retry.
  554. logger.warn(
  555. { err, v1ProjectId, version, retryAttempt: attempt },
  556. 'history s3 proxying error'
  557. )
  558. continue
  559. }
  560. }
  561. // We made it through. No need to retry anymore. Exit loop
  562. break
  563. }
  564. }
  565. const getLatestHistorySchema = z.object({
  566. params: z.object({
  567. project_id: zz.objectId(),
  568. }),
  569. })
  570. /**
  571. * @param {any} req
  572. * @param {any} res
  573. * @param {any} next
  574. */
  575. async function getLatestHistory(req, res, next) {
  576. const { params } = parseReq(req, getLatestHistorySchema)
  577. const projectId = params.project_id
  578. const history = await HistoryManager.promises.getLatestHistory(projectId)
  579. res.json(history)
  580. }
  581. const getChangesSchema = z.object({
  582. params: z.object({
  583. project_id: zz.objectId(),
  584. }),
  585. query: z.object({
  586. since: z.coerce.number().int().min(0).optional(),
  587. paginated: z.stringbool().optional(),
  588. }),
  589. })
  590. /**
  591. * @param {any} req
  592. * @param {any} res
  593. * @param {any} next
  594. */
  595. async function getChanges(req, res, next) {
  596. const { params, query } = parseReq(req, getChangesSchema)
  597. const projectId = params.project_id
  598. let since = query.since
  599. // TODO: Transition flag; remove after a while
  600. const paginated = query.paginated
  601. if (paginated) {
  602. const changes = await HistoryManager.promises.getChanges(projectId, {
  603. since,
  604. })
  605. return res.json(changes)
  606. } else {
  607. // TODO: Remove this code path after a while
  608. let hasMore = true
  609. const allChanges = []
  610. while (hasMore) {
  611. const response = await HistoryManager.promises.getChanges(projectId, {
  612. since,
  613. })
  614. let changes
  615. if (Array.isArray(response)) {
  616. changes = response
  617. hasMore = false
  618. } else {
  619. changes = response.changes
  620. hasMore = response.hasMore
  621. since += changes.length
  622. }
  623. allChanges.push(...changes)
  624. }
  625. return res.json(allChanges)
  626. }
  627. }
  628. /**
  629. * @param {any} err
  630. */
  631. function isPrematureClose(err) {
  632. return (
  633. err instanceof Error &&
  634. 'code' in err &&
  635. (err.code === 'ERR_STREAM_PREMATURE_CLOSE' ||
  636. err.code === 'ERR_STREAM_UNABLE_TO_PIPE')
  637. )
  638. }
  639. export default {
  640. getBlob: expressify(getBlob),
  641. headBlob: expressify(headBlob),
  642. proxyToHistoryApi: expressify(proxyToHistoryApi),
  643. proxyToHistoryApiAndInjectUserDetails: expressify(
  644. proxyToHistoryApiAndInjectUserDetails
  645. ),
  646. resyncProjectHistory: expressify(resyncProjectHistory),
  647. restoreFileFromV2: expressify(restoreFileFromV2),
  648. revertFile: expressify(revertFile),
  649. revertProject: expressify(revertProject),
  650. getLabels: expressify(getLabels),
  651. createLabel: expressify(createLabel),
  652. deleteLabel: expressify(deleteLabel),
  653. downloadZipOfVersion: expressify(downloadZipOfVersion),
  654. getLatestHistory: expressify(getLatestHistory),
  655. getChanges: expressify(getChanges),
  656. _displayNameForUser,
  657. promises: {
  658. _pipeHistoryZipToResponse,
  659. },
  660. }