ProjectEntityMongoUpdateHandler.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. /* NOTE: this file is an async/await version of
  2. * ProjectEntityMongoUpdateHandler.js. It's temporarily separate from the
  3. * callback-style version so that we can test it in production for some code
  4. * paths only.
  5. */
  6. const { callbackify } = require('util')
  7. const { callbackifyMultiResult } = require('../../util/promises')
  8. const _ = require('underscore')
  9. const logger = require('logger-sharelatex')
  10. const path = require('path')
  11. const { ObjectId } = require('mongodb')
  12. const Settings = require('settings-sharelatex')
  13. const OError = require('@overleaf/o-error')
  14. const CooldownManager = require('../Cooldown/CooldownManager')
  15. const Errors = require('../Errors/Errors')
  16. const { Folder } = require('../../models/Folder')
  17. const LockManager = require('../../infrastructure/LockManager')
  18. const { Project } = require('../../models/Project')
  19. const ProjectEntityHandler = require('./ProjectEntityHandler')
  20. const ProjectGetter = require('./ProjectGetter')
  21. const ProjectLocator = require('./ProjectLocator')
  22. const FolderStructureBuilder = require('./FolderStructureBuilder')
  23. const SafePath = require('./SafePath')
  24. const LOCK_NAMESPACE = 'mongoTransaction'
  25. const ENTITY_TYPE_TO_MONGO_PATH_SEGMENT = {
  26. doc: 'docs',
  27. docs: 'docs',
  28. file: 'fileRefs',
  29. files: 'fileRefs',
  30. fileRefs: 'fileRefs',
  31. folder: 'folders',
  32. folders: 'folders'
  33. }
  34. module.exports = {
  35. LOCK_NAMESPACE,
  36. addDoc: callbackifyMultiResult(wrapWithLock(addDoc), ['result', 'project']),
  37. addFile: callbackifyMultiResult(wrapWithLock(addFile), ['result', 'project']),
  38. addFolder: callbackifyMultiResult(wrapWithLock(addFolder), [
  39. 'folder',
  40. 'parentFolderId'
  41. ]),
  42. replaceFileWithNew: callbackifyMultiResult(wrapWithLock(replaceFileWithNew), [
  43. 'oldFileRef',
  44. 'project',
  45. 'path',
  46. 'newProject'
  47. ]),
  48. mkdirp: callbackifyMultiResult(wrapWithLock(mkdirp), [
  49. 'newFolders',
  50. 'folder'
  51. ]),
  52. moveEntity: callbackifyMultiResult(wrapWithLock(moveEntity), [
  53. 'project',
  54. 'startPath',
  55. 'endPath',
  56. 'rev',
  57. 'changes'
  58. ]),
  59. deleteEntity: callbackifyMultiResult(wrapWithLock(deleteEntity), [
  60. 'entity',
  61. 'path',
  62. 'projectBeforeDeletion',
  63. 'newProject'
  64. ]),
  65. renameEntity: callbackifyMultiResult(wrapWithLock(renameEntity), [
  66. 'project',
  67. 'startPath',
  68. 'endPath',
  69. 'rev',
  70. 'changes'
  71. ]),
  72. createNewFolderStructure: callbackify(wrapWithLock(createNewFolderStructure)),
  73. _insertDeletedDocReference: callbackify(_insertDeletedDocReference),
  74. _insertDeletedFileReference: callbackify(_insertDeletedFileReference),
  75. _putElement: callbackifyMultiResult(_putElement, ['result', 'project']),
  76. _confirmFolder,
  77. promises: {
  78. addDoc: wrapWithLock(addDoc),
  79. addFile: wrapWithLock(addFile),
  80. addFolder: wrapWithLock(addFolder),
  81. replaceFileWithNew: wrapWithLock(replaceFileWithNew),
  82. mkdirp: wrapWithLock(mkdirp),
  83. moveEntity: wrapWithLock(moveEntity),
  84. deleteEntity: wrapWithLock(deleteEntity),
  85. renameEntity: wrapWithLock(renameEntity),
  86. createNewFolderStructure: wrapWithLock(createNewFolderStructure),
  87. _insertDeletedDocReference,
  88. _insertDeletedFileReference,
  89. _putElement
  90. }
  91. }
  92. function wrapWithLock(methodWithoutLock) {
  93. // This lock is used whenever we read or write to an existing project's
  94. // structure. Some operations to project structure cannot be done atomically
  95. // in mongo, this lock is used to prevent reading the structure between two
  96. // parts of a staged update.
  97. async function methodWithLock(projectId, ...rest) {
  98. return LockManager.promises.runWithLock(LOCK_NAMESPACE, projectId, () =>
  99. methodWithoutLock(projectId, ...rest)
  100. )
  101. }
  102. return methodWithLock
  103. }
  104. async function addDoc(projectId, folderId, doc) {
  105. const project = await ProjectGetter.promises.getProjectWithoutLock(
  106. projectId,
  107. {
  108. rootFolder: true,
  109. name: true,
  110. overleaf: true
  111. }
  112. )
  113. folderId = _confirmFolder(project, folderId)
  114. const { result, project: newProject } = await _putElement(
  115. project,
  116. folderId,
  117. doc,
  118. 'doc'
  119. )
  120. return { result, project: newProject }
  121. }
  122. async function addFile(projectId, folderId, fileRef) {
  123. const project = await ProjectGetter.promises.getProjectWithoutLock(
  124. projectId,
  125. { rootFolder: true, name: true, overleaf: true }
  126. )
  127. folderId = _confirmFolder(project, folderId)
  128. const { result, project: newProject } = await _putElement(
  129. project,
  130. folderId,
  131. fileRef,
  132. 'file'
  133. )
  134. return { result, project: newProject }
  135. }
  136. async function addFolder(projectId, parentFolderId, folderName) {
  137. const project = await ProjectGetter.promises.getProjectWithoutLock(
  138. projectId,
  139. { rootFolder: true, name: true, overleaf: true }
  140. )
  141. parentFolderId = _confirmFolder(project, parentFolderId)
  142. const folder = new Folder({ name: folderName })
  143. await _putElement(project, parentFolderId, folder, 'folder')
  144. return { folder, parentFolderId }
  145. }
  146. async function replaceFileWithNew(projectId, fileId, newFileRef) {
  147. const project = await ProjectGetter.promises.getProjectWithoutLock(
  148. projectId,
  149. { rootFolder: true, name: true, overleaf: true }
  150. )
  151. const { element: fileRef, path } = await ProjectLocator.promises.findElement({
  152. project,
  153. element_id: fileId,
  154. type: 'file'
  155. })
  156. await _insertDeletedFileReference(projectId, fileRef)
  157. const newProject = await Project.findOneAndUpdate(
  158. { _id: project._id },
  159. {
  160. $set: {
  161. [`${path.mongo}._id`]: newFileRef._id,
  162. [`${path.mongo}.created`]: new Date(),
  163. [`${path.mongo}.linkedFileData`]: newFileRef.linkedFileData,
  164. [`${path.mongo}.hash`]: newFileRef.hash
  165. },
  166. $inc: {
  167. version: 1,
  168. [`${path.mongo}.rev`]: 1
  169. }
  170. },
  171. { new: true }
  172. ).exec()
  173. // Note: Mongoose uses new:true to return the modified document
  174. // https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
  175. // but Mongo uses returnNewDocument:true instead
  176. // https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/
  177. // We are using Mongoose here, but if we ever switch to a direct mongo call
  178. // the next line will need to be updated.
  179. return { oldFileRef: fileRef, project, path, newProject }
  180. }
  181. async function mkdirp(projectId, path, options = {}) {
  182. // defaults to case insensitive paths, use options {exactCaseMatch:true}
  183. // to make matching case-sensitive
  184. let folders = path.split('/')
  185. folders = _.select(folders, folder => folder.length !== 0)
  186. const project = await ProjectGetter.promises.getProjectWithOnlyFolders(
  187. projectId
  188. )
  189. if (path === '/') {
  190. return { newFolders: [], folder: project.rootFolder[0] }
  191. }
  192. const newFolders = []
  193. let builtUpPath = ''
  194. let lastFolder = null
  195. for (const folderName of folders) {
  196. builtUpPath += `/${folderName}`
  197. try {
  198. const {
  199. element: foundFolder
  200. } = await ProjectLocator.promises.findElementByPath({
  201. project,
  202. path: builtUpPath,
  203. exactCaseMatch: options.exactCaseMatch
  204. })
  205. lastFolder = foundFolder
  206. } catch (err) {
  207. // Folder couldn't be found. Create it.
  208. const parentFolderId = lastFolder && lastFolder._id
  209. const {
  210. folder: newFolder,
  211. parentFolderId: newParentFolderId
  212. } = await addFolder(projectId, parentFolderId, folderName)
  213. newFolder.parentFolder_id = newParentFolderId
  214. lastFolder = newFolder
  215. newFolders.push(newFolder)
  216. }
  217. }
  218. return { folder: lastFolder, newFolders }
  219. }
  220. async function moveEntity(projectId, entityId, destFolderId, entityType) {
  221. const project = await ProjectGetter.promises.getProjectWithoutLock(
  222. projectId,
  223. { rootFolder: true, name: true, overleaf: true }
  224. )
  225. const {
  226. element: entity,
  227. path: entityPath
  228. } = await ProjectLocator.promises.findElement({
  229. project,
  230. element_id: entityId,
  231. type: entityType
  232. })
  233. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  234. if (_blockedFilename(entityPath, entityType)) {
  235. throw new Errors.InvalidNameError('blocked element name')
  236. }
  237. await _checkValidMove(project, entityType, entity, entityPath, destFolderId)
  238. const {
  239. docs: oldDocs,
  240. files: oldFiles
  241. } = await ProjectEntityHandler.promises.getAllEntitiesFromProject(project)
  242. // For safety, insert the entity in the destination
  243. // location first, and then remove the original. If
  244. // there is an error the entity may appear twice. This
  245. // will cause some breakage but is better than being
  246. // lost, which is what happens if this is done in the
  247. // opposite order.
  248. const { result } = await _putElement(
  249. project,
  250. destFolderId,
  251. entity,
  252. entityType
  253. )
  254. // Note: putElement always pushes onto the end of an
  255. // array so it will never change an existing mongo
  256. // path. Therefore it is safe to remove an element
  257. // from the project with an existing path after
  258. // calling putElement. But we must be sure that we
  259. // have not moved a folder subfolder of itself (which
  260. // is done by _checkValidMove above) because that
  261. // would lead to it being deleted.
  262. const newProject = await _removeElementFromMongoArray(
  263. Project,
  264. projectId,
  265. entityPath.mongo,
  266. entityId
  267. )
  268. const {
  269. docs: newDocs,
  270. files: newFiles
  271. } = await ProjectEntityHandler.promises.getAllEntitiesFromProject(newProject)
  272. const startPath = entityPath.fileSystem
  273. const endPath = result.path.fileSystem
  274. const changes = {
  275. oldDocs,
  276. newDocs,
  277. oldFiles,
  278. newFiles,
  279. newProject
  280. }
  281. // check that no files have been lost (or duplicated)
  282. if (
  283. oldFiles.length !== newFiles.length ||
  284. oldDocs.length !== newDocs.length
  285. ) {
  286. logger.warn(
  287. {
  288. projectId,
  289. oldDocs: oldDocs.length,
  290. newDocs: newDocs.length,
  291. oldFiles: oldFiles.length,
  292. newFiles: newFiles.length,
  293. origProject: project,
  294. newProject
  295. },
  296. "project corrupted moving files - shouldn't happen"
  297. )
  298. throw new Error('unexpected change in project structure')
  299. }
  300. return { project, startPath, endPath, rev: entity.rev, changes }
  301. }
  302. async function deleteEntity(projectId, entityId, entityType, callback) {
  303. const project = await ProjectGetter.promises.getProjectWithoutLock(
  304. projectId,
  305. { name: true, rootFolder: true, overleaf: true, rootDoc_id: true }
  306. )
  307. const deleteRootDoc = project.rootDoc_id && entityId && project.rootDoc_id.toString() === entityId.toString()
  308. const { element: entity, path } = await ProjectLocator.promises.findElement({
  309. project,
  310. element_id: entityId,
  311. type: entityType
  312. })
  313. const newProject = await _removeElementFromMongoArray(
  314. Project,
  315. projectId,
  316. path.mongo,
  317. entityId,
  318. deleteRootDoc
  319. )
  320. return { entity, path, projectBeforeDeletion: project, newProject }
  321. }
  322. async function renameEntity(
  323. projectId,
  324. entityId,
  325. entityType,
  326. newName,
  327. callback
  328. ) {
  329. const project = await ProjectGetter.promises.getProjectWithoutLock(
  330. projectId,
  331. { rootFolder: true, name: true, overleaf: true }
  332. )
  333. const {
  334. element: entity,
  335. path: entPath,
  336. folder: parentFolder
  337. } = await ProjectLocator.promises.findElement({
  338. project,
  339. element_id: entityId,
  340. type: entityType
  341. })
  342. const startPath = entPath.fileSystem
  343. const endPath = path.join(path.dirname(entPath.fileSystem), newName)
  344. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  345. if (_blockedFilename({ fileSystem: endPath }, entityType)) {
  346. throw new Errors.InvalidNameError('blocked element name')
  347. }
  348. // check if the new name already exists in the current folder
  349. _checkValidElementName(parentFolder, newName)
  350. const {
  351. docs: oldDocs,
  352. files: oldFiles
  353. } = await ProjectEntityHandler.promises.getAllEntitiesFromProject(project)
  354. // we need to increment the project version number for any structure change
  355. const newProject = await Project.findOneAndUpdate(
  356. { _id: projectId },
  357. { $set: { [`${entPath.mongo}.name`]: newName }, $inc: { version: 1 } },
  358. { new: true }
  359. ).exec()
  360. const {
  361. docs: newDocs,
  362. files: newFiles
  363. } = await ProjectEntityHandler.promises.getAllEntitiesFromProject(newProject)
  364. return {
  365. project,
  366. startPath,
  367. endPath,
  368. rev: entity.rev,
  369. changes: { oldDocs, newDocs, oldFiles, newFiles, newProject }
  370. }
  371. }
  372. async function _insertDeletedDocReference(projectId, doc) {
  373. await Project.updateOne(
  374. { _id: projectId },
  375. {
  376. $push: {
  377. deletedDocs: { _id: doc._id, name: doc.name, deletedAt: new Date() }
  378. }
  379. }
  380. ).exec()
  381. }
  382. async function _insertDeletedFileReference(projectId, fileRef) {
  383. await Project.updateOne(
  384. { _id: projectId },
  385. {
  386. $push: {
  387. deletedFiles: {
  388. _id: fileRef._id,
  389. name: fileRef.name,
  390. linkedFileData: fileRef.linkedFileData,
  391. hash: fileRef.hash,
  392. deletedAt: new Date()
  393. }
  394. }
  395. }
  396. ).exec()
  397. }
  398. async function _removeElementFromMongoArray(model, modelId, path, elementId, deleteRootDoc=false) {
  399. const nonArrayPath = path.slice(0, path.lastIndexOf('.'))
  400. const options = { new: true }
  401. const query = { _id: modelId }
  402. const update = {
  403. $pull: { [nonArrayPath]: { _id: elementId } },
  404. $inc: { version: 1 }
  405. }
  406. if (deleteRootDoc) {
  407. update.$unset = { rootDoc_id: 1 }
  408. }
  409. return model.findOneAndUpdate(query, update, options).exec()
  410. }
  411. function _countElements(project) {
  412. function countFolder(folder) {
  413. if (folder == null) {
  414. return 0
  415. }
  416. let total = 0
  417. if (folder.folders) {
  418. total += folder.folders.length
  419. for (const subfolder of folder.folders) {
  420. total += countFolder(subfolder)
  421. }
  422. }
  423. if (folder.docs) {
  424. total += folder.docs.length
  425. }
  426. if (folder.fileRefs) {
  427. total += folder.fileRefs.length
  428. }
  429. return total
  430. }
  431. return countFolder(project.rootFolder[0])
  432. }
  433. async function _putElement(project, folderId, element, type) {
  434. if (element == null || element._id == null) {
  435. logger.warn(
  436. { projectId: project._id, folderId, element, type },
  437. 'failed trying to insert element as it was null'
  438. )
  439. throw new Error('no element passed to be inserted')
  440. }
  441. const pathSegment = _getMongoPathSegmentFromType(type)
  442. // original check path.resolve("/", element.name) isnt "/#{element.name}" or element.name.match("/")
  443. // check if name is allowed
  444. if (!SafePath.isCleanFilename(element.name)) {
  445. logger.warn(
  446. { projectId: project._id, folderId, element, type },
  447. 'failed trying to insert element as name was invalid'
  448. )
  449. throw new Errors.InvalidNameError('invalid element name')
  450. }
  451. if (folderId == null) {
  452. folderId = project.rootFolder[0]._id
  453. }
  454. if (_countElements(project) > Settings.maxEntitiesPerProject) {
  455. logger.warn(
  456. { projectId: project._id },
  457. 'project too big, stopping insertions'
  458. )
  459. CooldownManager.putProjectOnCooldown(project._id)
  460. throw new Error('project_has_to_many_files')
  461. }
  462. const { element: folder, path } = await ProjectLocator.promises.findElement({
  463. project,
  464. element_id: folderId,
  465. type: 'folder'
  466. })
  467. const newPath = {
  468. fileSystem: `${path.fileSystem}/${element.name}`,
  469. mongo: path.mongo
  470. }
  471. // check if the path would be too long
  472. if (!SafePath.isAllowedLength(newPath.fileSystem)) {
  473. throw new Errors.InvalidNameError('path too long')
  474. }
  475. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  476. if (_blockedFilename(newPath, type)) {
  477. throw new Errors.InvalidNameError('blocked element name')
  478. }
  479. _checkValidElementName(folder, element.name)
  480. element._id = ObjectId(element._id.toString())
  481. const mongoPath = `${path.mongo}.${pathSegment}`
  482. const newProject = await Project.findOneAndUpdate(
  483. { _id: project._id },
  484. { $push: { [mongoPath]: element }, $inc: { version: 1 } },
  485. { new: true }
  486. ).exec()
  487. return { result: { path: newPath }, project: newProject }
  488. }
  489. function _blockedFilename(entityPath, entityType) {
  490. // check if name would be blocked in v1
  491. // javascript reserved names are forbidden for docs and files
  492. // at the top-level (but folders with reserved names are allowed).
  493. const isFolder = entityType === 'folder'
  494. const dir = path.dirname(entityPath.fileSystem)
  495. const file = path.basename(entityPath.fileSystem)
  496. const isTopLevel = dir === '/'
  497. if (isTopLevel && !isFolder && SafePath.isBlockedFilename(file)) {
  498. return true
  499. } else {
  500. return false
  501. }
  502. }
  503. function _getMongoPathSegmentFromType(type) {
  504. const pathSegment = ENTITY_TYPE_TO_MONGO_PATH_SEGMENT[type]
  505. if (pathSegment == null) {
  506. throw new Error(`Unknown entity type: ${type}`)
  507. }
  508. return pathSegment
  509. }
  510. /**
  511. * Check if the name is already taken by a doc, file or folder. If so, return an
  512. * error "file already exists".
  513. */
  514. function _checkValidElementName(folder, name) {
  515. if (folder == null) {
  516. return
  517. }
  518. const elements = []
  519. .concat(folder.docs || [])
  520. .concat(folder.fileRefs || [])
  521. .concat(folder.folders || [])
  522. for (const element of elements) {
  523. if (element.name === name) {
  524. throw new Errors.InvalidNameError('file already exists')
  525. }
  526. }
  527. }
  528. function _confirmFolder(project, folderId) {
  529. if (folderId == null) {
  530. return project.rootFolder[0]._id
  531. } else {
  532. return folderId
  533. }
  534. }
  535. async function _checkValidMove(
  536. project,
  537. entityType,
  538. entity,
  539. entityPath,
  540. destFolderId
  541. ) {
  542. const {
  543. element: destEntity,
  544. path: destFolderPath
  545. } = await ProjectLocator.promises.findElement({
  546. project,
  547. element_id: destFolderId,
  548. type: 'folder'
  549. })
  550. // check if there is already a doc/file/folder with the same name
  551. // in the destination folder
  552. _checkValidElementName(destEntity, entity.name)
  553. if (/folder/.test(entityType)) {
  554. const isNestedFolder =
  555. destFolderPath.fileSystem.slice(0, entityPath.fileSystem.length) ===
  556. entityPath.fileSystem
  557. if (isNestedFolder) {
  558. throw new Errors.InvalidNameError(
  559. 'destination folder is a child folder of me'
  560. )
  561. }
  562. }
  563. }
  564. async function createNewFolderStructure(projectId, docUploads, fileUploads) {
  565. try {
  566. const rootFolder = FolderStructureBuilder.buildFolderStructure(
  567. docUploads,
  568. fileUploads
  569. )
  570. const result = await Project.updateOne(
  571. {
  572. _id: projectId,
  573. 'rootFolder.0.folders.0': { $exists: false },
  574. 'rootFolder.0.docs.0': { $exists: false },
  575. 'rootFolder.0.files.0': { $exists: false }
  576. },
  577. {
  578. $set: { rootFolder: [rootFolder] },
  579. $inc: { version: 1 }
  580. }
  581. ).exec()
  582. if (result.n !== 1) {
  583. throw new OError({
  584. message: 'project not found or folder structure already exists',
  585. info: { projectId }
  586. })
  587. }
  588. } catch (err) {
  589. throw new OError({
  590. message: 'failed to create folder structure',
  591. info: { projectId }
  592. }).withCause(err)
  593. }
  594. }