ProjectEntityMongoUpdateHandler.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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 }
  306. )
  307. const { element: entity, path } = await ProjectLocator.promises.findElement({
  308. project,
  309. element_id: entityId,
  310. type: entityType
  311. })
  312. const newProject = await _removeElementFromMongoArray(
  313. Project,
  314. projectId,
  315. path.mongo,
  316. entityId
  317. )
  318. return { entity, path, projectBeforeDeletion: project, newProject }
  319. }
  320. async function renameEntity(
  321. projectId,
  322. entityId,
  323. entityType,
  324. newName,
  325. callback
  326. ) {
  327. const project = await ProjectGetter.promises.getProjectWithoutLock(
  328. projectId,
  329. { rootFolder: true, name: true, overleaf: true }
  330. )
  331. const {
  332. element: entity,
  333. path: entPath,
  334. folder: parentFolder
  335. } = await ProjectLocator.promises.findElement({
  336. project,
  337. element_id: entityId,
  338. type: entityType
  339. })
  340. const startPath = entPath.fileSystem
  341. const endPath = path.join(path.dirname(entPath.fileSystem), newName)
  342. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  343. if (_blockedFilename({ fileSystem: endPath }, entityType)) {
  344. throw new Errors.InvalidNameError('blocked element name')
  345. }
  346. // check if the new name already exists in the current folder
  347. _checkValidElementName(parentFolder, newName)
  348. const {
  349. docs: oldDocs,
  350. files: oldFiles
  351. } = await ProjectEntityHandler.promises.getAllEntitiesFromProject(project)
  352. // we need to increment the project version number for any structure change
  353. const newProject = await Project.findOneAndUpdate(
  354. { _id: projectId },
  355. { $set: { [`${entPath.mongo}.name`]: newName }, $inc: { version: 1 } },
  356. { new: true }
  357. ).exec()
  358. const {
  359. docs: newDocs,
  360. files: newFiles
  361. } = await ProjectEntityHandler.promises.getAllEntitiesFromProject(newProject)
  362. return {
  363. project,
  364. startPath,
  365. endPath,
  366. rev: entity.rev,
  367. changes: { oldDocs, newDocs, oldFiles, newFiles, newProject }
  368. }
  369. }
  370. async function _insertDeletedDocReference(projectId, doc) {
  371. await Project.updateOne(
  372. { _id: projectId },
  373. {
  374. $push: {
  375. deletedDocs: { _id: doc._id, name: doc.name, deletedAt: new Date() }
  376. }
  377. }
  378. ).exec()
  379. }
  380. async function _insertDeletedFileReference(projectId, fileRef) {
  381. await Project.updateOne(
  382. { _id: projectId },
  383. {
  384. $push: {
  385. deletedFiles: {
  386. _id: fileRef._id,
  387. name: fileRef.name,
  388. linkedFileData: fileRef.linkedFileData,
  389. hash: fileRef.hash,
  390. deletedAt: new Date()
  391. }
  392. }
  393. }
  394. ).exec()
  395. }
  396. async function _removeElementFromMongoArray(model, modelId, path, elementId) {
  397. const nonArrayPath = path.slice(0, path.lastIndexOf('.'))
  398. const newDoc = model
  399. .findOneAndUpdate(
  400. { _id: modelId },
  401. {
  402. $pull: { [nonArrayPath]: { _id: elementId } },
  403. $inc: { version: 1 }
  404. },
  405. { new: true }
  406. )
  407. .exec()
  408. return newDoc
  409. }
  410. function _countElements(project) {
  411. function countFolder(folder) {
  412. if (folder == null) {
  413. return 0
  414. }
  415. let total = 0
  416. if (folder.folders) {
  417. total += folder.folders.length
  418. for (const subfolder of folder.folders) {
  419. total += countFolder(subfolder)
  420. }
  421. }
  422. if (folder.docs) {
  423. total += folder.docs.length
  424. }
  425. if (folder.fileRefs) {
  426. total += folder.fileRefs.length
  427. }
  428. return total
  429. }
  430. return countFolder(project.rootFolder[0])
  431. }
  432. async function _putElement(project, folderId, element, type) {
  433. if (element == null || element._id == null) {
  434. logger.warn(
  435. { projectId: project._id, folderId, element, type },
  436. 'failed trying to insert element as it was null'
  437. )
  438. throw new Error('no element passed to be inserted')
  439. }
  440. const pathSegment = _getMongoPathSegmentFromType(type)
  441. // original check path.resolve("/", element.name) isnt "/#{element.name}" or element.name.match("/")
  442. // check if name is allowed
  443. if (!SafePath.isCleanFilename(element.name)) {
  444. logger.warn(
  445. { projectId: project._id, folderId, element, type },
  446. 'failed trying to insert element as name was invalid'
  447. )
  448. throw new Errors.InvalidNameError('invalid element name')
  449. }
  450. if (folderId == null) {
  451. folderId = project.rootFolder[0]._id
  452. }
  453. if (_countElements(project) > Settings.maxEntitiesPerProject) {
  454. logger.warn(
  455. { projectId: project._id },
  456. 'project too big, stopping insertions'
  457. )
  458. CooldownManager.putProjectOnCooldown(project._id)
  459. throw new Error('project_has_to_many_files')
  460. }
  461. const { element: folder, path } = await ProjectLocator.promises.findElement({
  462. project,
  463. element_id: folderId,
  464. type: 'folder'
  465. })
  466. const newPath = {
  467. fileSystem: `${path.fileSystem}/${element.name}`,
  468. mongo: path.mongo
  469. }
  470. // check if the path would be too long
  471. if (!SafePath.isAllowedLength(newPath.fileSystem)) {
  472. throw new Errors.InvalidNameError('path too long')
  473. }
  474. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  475. if (_blockedFilename(newPath, type)) {
  476. throw new Errors.InvalidNameError('blocked element name')
  477. }
  478. _checkValidElementName(folder, element.name)
  479. element._id = ObjectId(element._id.toString())
  480. const mongoPath = `${path.mongo}.${pathSegment}`
  481. const newProject = await Project.findOneAndUpdate(
  482. { _id: project._id },
  483. { $push: { [mongoPath]: element }, $inc: { version: 1 } },
  484. { new: true }
  485. ).exec()
  486. return { result: { path: newPath }, project: newProject }
  487. }
  488. function _blockedFilename(entityPath, entityType) {
  489. // check if name would be blocked in v1
  490. // javascript reserved names are forbidden for docs and files
  491. // at the top-level (but folders with reserved names are allowed).
  492. const isFolder = entityType === 'folder'
  493. const dir = path.dirname(entityPath.fileSystem)
  494. const file = path.basename(entityPath.fileSystem)
  495. const isTopLevel = dir === '/'
  496. if (isTopLevel && !isFolder && SafePath.isBlockedFilename(file)) {
  497. return true
  498. } else {
  499. return false
  500. }
  501. }
  502. function _getMongoPathSegmentFromType(type) {
  503. const pathSegment = ENTITY_TYPE_TO_MONGO_PATH_SEGMENT[type]
  504. if (pathSegment == null) {
  505. throw new Error(`Unknown entity type: ${type}`)
  506. }
  507. return pathSegment
  508. }
  509. /**
  510. * Check if the name is already taken by a doc, file or folder. If so, return an
  511. * error "file already exists".
  512. */
  513. function _checkValidElementName(folder, name) {
  514. if (folder == null) {
  515. return
  516. }
  517. const elements = []
  518. .concat(folder.docs || [])
  519. .concat(folder.fileRefs || [])
  520. .concat(folder.folders || [])
  521. for (const element of elements) {
  522. if (element.name === name) {
  523. throw new Errors.InvalidNameError('file already exists')
  524. }
  525. }
  526. }
  527. function _confirmFolder(project, folderId) {
  528. if (folderId == null) {
  529. return project.rootFolder[0]._id
  530. } else {
  531. return folderId
  532. }
  533. }
  534. async function _checkValidMove(
  535. project,
  536. entityType,
  537. entity,
  538. entityPath,
  539. destFolderId
  540. ) {
  541. const {
  542. element: destEntity,
  543. path: destFolderPath
  544. } = await ProjectLocator.promises.findElement({
  545. project,
  546. element_id: destFolderId,
  547. type: 'folder'
  548. })
  549. // check if there is already a doc/file/folder with the same name
  550. // in the destination folder
  551. _checkValidElementName(destEntity, entity.name)
  552. if (/folder/.test(entityType)) {
  553. const isNestedFolder =
  554. destFolderPath.fileSystem.slice(0, entityPath.fileSystem.length) ===
  555. entityPath.fileSystem
  556. if (isNestedFolder) {
  557. throw new Errors.InvalidNameError(
  558. 'destination folder is a child folder of me'
  559. )
  560. }
  561. }
  562. }
  563. async function createNewFolderStructure(projectId, docUploads, fileUploads) {
  564. try {
  565. const rootFolder = FolderStructureBuilder.buildFolderStructure(
  566. docUploads,
  567. fileUploads
  568. )
  569. const result = await Project.updateOne(
  570. {
  571. _id: projectId,
  572. 'rootFolder.0.folders.0': { $exists: false },
  573. 'rootFolder.0.docs.0': { $exists: false },
  574. 'rootFolder.0.files.0': { $exists: false }
  575. },
  576. {
  577. $set: { rootFolder: [rootFolder] },
  578. $inc: { version: 1 }
  579. }
  580. ).exec()
  581. if (result.n !== 1) {
  582. throw new OError({
  583. message: 'project not found or folder structure already exists',
  584. info: { projectId }
  585. })
  586. }
  587. } catch (err) {
  588. throw new OError({
  589. message: 'failed to create folder structure',
  590. info: { projectId }
  591. }).withCause(err)
  592. }
  593. }