ProjectEntityMongoUpdateHandlerCanary.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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. logger.log(
  191. { projectId: project._id },
  192. 'mkdir is only trying to make path of / so sending back root folder'
  193. )
  194. return { newFolders: [], folder: project.rootFolder[0] }
  195. }
  196. const newFolders = []
  197. let builtUpPath = ''
  198. let lastFolder = null
  199. for (const folderName of folders) {
  200. builtUpPath += `/${folderName}`
  201. try {
  202. const {
  203. element: foundFolder
  204. } = await ProjectLocator.promises.findElementByPath({
  205. project,
  206. path: builtUpPath,
  207. exactCaseMatch: options.exactCaseMatch
  208. })
  209. lastFolder = foundFolder
  210. } catch (err) {
  211. // Folder couldn't be found. Create it.
  212. logger.log(
  213. { path, projectId: project._id, folderName },
  214. 'making folder from mkdirp'
  215. )
  216. const parentFolderId = lastFolder && lastFolder._id
  217. const {
  218. folder: newFolder,
  219. parentFolderId: newParentFolderId
  220. } = await addFolder(projectId, parentFolderId, folderName)
  221. newFolder.parentFolder_id = newParentFolderId
  222. lastFolder = newFolder
  223. newFolders.push(newFolder)
  224. }
  225. }
  226. return { folder: lastFolder, newFolders }
  227. }
  228. async function moveEntity(projectId, entityId, destFolderId, entityType) {
  229. const project = await ProjectGetter.promises.getProjectWithoutLock(
  230. projectId,
  231. { rootFolder: true, name: true, overleaf: true }
  232. )
  233. const {
  234. element: entity,
  235. path: entityPath
  236. } = await ProjectLocator.promises.findElement({
  237. project,
  238. element_id: entityId,
  239. type: entityType
  240. })
  241. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  242. if (_blockedFilename(entityPath, entityType)) {
  243. throw new Errors.InvalidNameError('blocked element name')
  244. }
  245. await _checkValidMove(project, entityType, entity, entityPath, destFolderId)
  246. const {
  247. docs: oldDocs,
  248. files: oldFiles
  249. } = await ProjectEntityHandler.promises.getAllEntitiesFromProject(project)
  250. // For safety, insert the entity in the destination
  251. // location first, and then remove the original. If
  252. // there is an error the entity may appear twice. This
  253. // will cause some breakage but is better than being
  254. // lost, which is what happens if this is done in the
  255. // opposite order.
  256. const { result } = await _putElement(
  257. project,
  258. destFolderId,
  259. entity,
  260. entityType
  261. )
  262. // Note: putElement always pushes onto the end of an
  263. // array so it will never change an existing mongo
  264. // path. Therefore it is safe to remove an element
  265. // from the project with an existing path after
  266. // calling putElement. But we must be sure that we
  267. // have not moved a folder subfolder of itself (which
  268. // is done by _checkValidMove above) because that
  269. // would lead to it being deleted.
  270. const newProject = await _removeElementFromMongoArray(
  271. Project,
  272. projectId,
  273. entityPath.mongo,
  274. entityId
  275. )
  276. const {
  277. docs: newDocs,
  278. files: newFiles
  279. } = await ProjectEntityHandler.promises.getAllEntitiesFromProject(newProject)
  280. const startPath = entityPath.fileSystem
  281. const endPath = result.path.fileSystem
  282. const changes = {
  283. oldDocs,
  284. newDocs,
  285. oldFiles,
  286. newFiles,
  287. newProject
  288. }
  289. // check that no files have been lost (or duplicated)
  290. if (
  291. oldFiles.length !== newFiles.length ||
  292. oldDocs.length !== newDocs.length
  293. ) {
  294. logger.warn(
  295. {
  296. projectId,
  297. oldDocs: oldDocs.length,
  298. newDocs: newDocs.length,
  299. oldFiles: oldFiles.length,
  300. newFiles: newFiles.length,
  301. origProject: project,
  302. newProject
  303. },
  304. "project corrupted moving files - shouldn't happen"
  305. )
  306. throw new Error('unexpected change in project structure')
  307. }
  308. return { project, startPath, endPath, rev: entity.rev, changes }
  309. }
  310. async function deleteEntity(projectId, entityId, entityType, callback) {
  311. const project = await ProjectGetter.promises.getProjectWithoutLock(
  312. projectId,
  313. { name: true, rootFolder: true, overleaf: true }
  314. )
  315. const { element: entity, path } = await ProjectLocator.promises.findElement({
  316. project,
  317. element_id: entityId,
  318. type: entityType
  319. })
  320. const newProject = await _removeElementFromMongoArray(
  321. Project,
  322. projectId,
  323. path.mongo,
  324. entityId
  325. )
  326. return { entity, path, projectBeforeDeletion: project, newProject }
  327. }
  328. async function renameEntity(
  329. projectId,
  330. entityId,
  331. entityType,
  332. newName,
  333. callback
  334. ) {
  335. const project = await ProjectGetter.promises.getProjectWithoutLock(
  336. projectId,
  337. { rootFolder: true, name: true, overleaf: true }
  338. )
  339. const {
  340. element: entity,
  341. path: entPath,
  342. folder: parentFolder
  343. } = await ProjectLocator.promises.findElement({
  344. project,
  345. element_id: entityId,
  346. type: entityType
  347. })
  348. const startPath = entPath.fileSystem
  349. const endPath = path.join(path.dirname(entPath.fileSystem), newName)
  350. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  351. if (_blockedFilename({ fileSystem: endPath }, entityType)) {
  352. throw new Errors.InvalidNameError('blocked element name')
  353. }
  354. // check if the new name already exists in the current folder
  355. _checkValidElementName(parentFolder, newName)
  356. const {
  357. docs: oldDocs,
  358. files: oldFiles
  359. } = await ProjectEntityHandler.promises.getAllEntitiesFromProject(project)
  360. // we need to increment the project version number for any structure change
  361. const newProject = await Project.findOneAndUpdate(
  362. { _id: projectId },
  363. { $set: { [`${entPath.mongo}.name`]: newName }, $inc: { version: 1 } },
  364. { new: true }
  365. ).exec()
  366. const {
  367. docs: newDocs,
  368. files: newFiles
  369. } = await ProjectEntityHandler.promises.getAllEntitiesFromProject(newProject)
  370. return {
  371. project,
  372. startPath,
  373. endPath,
  374. rev: entity.rev,
  375. changes: { oldDocs, newDocs, oldFiles, newFiles, newProject }
  376. }
  377. }
  378. async function _insertDeletedDocReference(projectId, doc) {
  379. await Project.updateOne(
  380. { _id: projectId },
  381. {
  382. $push: {
  383. deletedDocs: { _id: doc._id, name: doc.name, deletedAt: new Date() }
  384. }
  385. }
  386. ).exec()
  387. }
  388. async function _insertDeletedFileReference(projectId, fileRef) {
  389. await Project.updateOne(
  390. { _id: projectId },
  391. {
  392. $push: {
  393. deletedFiles: {
  394. _id: fileRef._id,
  395. name: fileRef.name,
  396. linkedFileData: fileRef.linkedFileData,
  397. hash: fileRef.hash,
  398. deletedAt: new Date()
  399. }
  400. }
  401. }
  402. ).exec()
  403. }
  404. async function _removeElementFromMongoArray(model, modelId, path, elementId) {
  405. const nonArrayPath = path.slice(0, path.lastIndexOf('.'))
  406. const newDoc = model
  407. .findOneAndUpdate(
  408. { _id: modelId },
  409. {
  410. $pull: { [nonArrayPath]: { _id: elementId } },
  411. $inc: { version: 1 }
  412. },
  413. { new: true }
  414. )
  415. .exec()
  416. return newDoc
  417. }
  418. function _countElements(project) {
  419. function countFolder(folder) {
  420. if (folder == null) {
  421. return 0
  422. }
  423. let total = 0
  424. if (folder.folders) {
  425. total += folder.folders.length
  426. for (const subfolder of folder.folders) {
  427. total += countFolder(subfolder)
  428. }
  429. }
  430. if (folder.docs) {
  431. total += folder.docs.length
  432. }
  433. if (folder.fileRefs) {
  434. total += folder.fileRefs.length
  435. }
  436. return total
  437. }
  438. return countFolder(project.rootFolder[0])
  439. }
  440. async function _putElement(project, folderId, element, type) {
  441. if (element == null || element._id == null) {
  442. logger.warn(
  443. { projectId: project._id, folderId, element, type },
  444. 'failed trying to insert element as it was null'
  445. )
  446. throw new Error('no element passed to be inserted')
  447. }
  448. const pathSegment = _getMongoPathSegmentFromType(type)
  449. // original check path.resolve("/", element.name) isnt "/#{element.name}" or element.name.match("/")
  450. // check if name is allowed
  451. if (!SafePath.isCleanFilename(element.name)) {
  452. logger.warn(
  453. { projectId: project._id, folderId, element, type },
  454. 'failed trying to insert element as name was invalid'
  455. )
  456. throw new Errors.InvalidNameError('invalid element name')
  457. }
  458. if (folderId == null) {
  459. folderId = project.rootFolder[0]._id
  460. }
  461. if (_countElements(project) > Settings.maxEntitiesPerProject) {
  462. logger.warn(
  463. { projectId: project._id },
  464. 'project too big, stopping insertions'
  465. )
  466. CooldownManager.putProjectOnCooldown(project._id)
  467. throw new Error('project_has_to_many_files')
  468. }
  469. const { element: folder, path } = await ProjectLocator.promises.findElement({
  470. project,
  471. element_id: folderId,
  472. type: 'folder'
  473. })
  474. const newPath = {
  475. fileSystem: `${path.fileSystem}/${element.name}`,
  476. mongo: path.mongo
  477. }
  478. // check if the path would be too long
  479. if (!SafePath.isAllowedLength(newPath.fileSystem)) {
  480. throw new Errors.InvalidNameError('path too long')
  481. }
  482. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  483. if (_blockedFilename(newPath, type)) {
  484. throw new Errors.InvalidNameError('blocked element name')
  485. }
  486. _checkValidElementName(folder, element.name)
  487. element._id = ObjectId(element._id.toString())
  488. const mongoPath = `${path.mongo}.${pathSegment}`
  489. const newProject = await Project.findOneAndUpdate(
  490. { _id: project._id },
  491. { $push: { [mongoPath]: element }, $inc: { version: 1 } },
  492. { new: true }
  493. ).exec()
  494. return { result: { path: newPath }, project: newProject }
  495. }
  496. function _blockedFilename(entityPath, entityType) {
  497. // check if name would be blocked in v1
  498. // javascript reserved names are forbidden for docs and files
  499. // at the top-level (but folders with reserved names are allowed).
  500. const isFolder = entityType === 'folder'
  501. const dir = path.dirname(entityPath.fileSystem)
  502. const file = path.basename(entityPath.fileSystem)
  503. const isTopLevel = dir === '/'
  504. if (isTopLevel && !isFolder && SafePath.isBlockedFilename(file)) {
  505. return true
  506. } else {
  507. return false
  508. }
  509. }
  510. function _getMongoPathSegmentFromType(type) {
  511. const pathSegment = ENTITY_TYPE_TO_MONGO_PATH_SEGMENT[type]
  512. if (pathSegment == null) {
  513. throw new Error(`Unknown entity type: ${type}`)
  514. }
  515. return pathSegment
  516. }
  517. /**
  518. * Check if the name is already taken by a doc, file or folder. If so, return an
  519. * error "file already exists".
  520. */
  521. function _checkValidElementName(folder, name) {
  522. if (folder == null) {
  523. return
  524. }
  525. const elements = []
  526. .concat(folder.docs || [])
  527. .concat(folder.fileRefs || [])
  528. .concat(folder.folders || [])
  529. for (const element of elements) {
  530. if (element.name === name) {
  531. throw new Errors.InvalidNameError('file already exists')
  532. }
  533. }
  534. }
  535. function _confirmFolder(project, folderId) {
  536. if (folderId == null) {
  537. return project.rootFolder[0]._id
  538. } else {
  539. return folderId
  540. }
  541. }
  542. async function _checkValidMove(
  543. project,
  544. entityType,
  545. entity,
  546. entityPath,
  547. destFolderId
  548. ) {
  549. const {
  550. element: destEntity,
  551. path: destFolderPath
  552. } = await ProjectLocator.promises.findElement({
  553. project,
  554. element_id: destFolderId,
  555. type: 'folder'
  556. })
  557. // check if there is already a doc/file/folder with the same name
  558. // in the destination folder
  559. _checkValidElementName(destEntity, entity.name)
  560. if (/folder/.test(entityType)) {
  561. logger.log(
  562. {
  563. destFolderPath: destFolderPath.fileSystem,
  564. folderPath: entityPath.fileSystem
  565. },
  566. 'checking folder is not moving into child folder'
  567. )
  568. const isNestedFolder =
  569. destFolderPath.fileSystem.slice(0, entityPath.fileSystem.length) ===
  570. entityPath.fileSystem
  571. if (isNestedFolder) {
  572. throw new Errors.InvalidNameError(
  573. 'destination folder is a child folder of me'
  574. )
  575. }
  576. }
  577. }
  578. async function createNewFolderStructure(projectId, docUploads, fileUploads) {
  579. try {
  580. const rootFolder = FolderStructureBuilder.buildFolderStructure(
  581. docUploads,
  582. fileUploads
  583. )
  584. const result = await Project.updateOne(
  585. {
  586. _id: projectId,
  587. 'rootFolder.0.folders.0': { $exists: false },
  588. 'rootFolder.0.docs.0': { $exists: false },
  589. 'rootFolder.0.files.0': { $exists: false }
  590. },
  591. {
  592. $set: { rootFolder: [rootFolder] },
  593. $inc: { version: 1 }
  594. }
  595. ).exec()
  596. if (result.n !== 1) {
  597. throw new OError({
  598. message: 'project not found or folder structure already exists',
  599. info: { projectId }
  600. })
  601. }
  602. } catch (err) {
  603. throw new OError({
  604. message: 'failed to create folder structure',
  605. info: { projectId }
  606. }).withCause(err)
  607. }
  608. }