StaticServerForbidSymlinks.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /* eslint-disable
  2. no-cond-assign,
  3. no-unused-vars,
  4. n/no-deprecated-api,
  5. */
  6. // TODO: This file was created by bulk-decaffeinate.
  7. // Fix any style issues and re-enable lint.
  8. /*
  9. * decaffeinate suggestions:
  10. * DS101: Remove unnecessary use of Array.from
  11. * DS102: Remove unnecessary code created because of implicit returns
  12. * DS207: Consider shorter variations of null checks
  13. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  14. */
  15. let ForbidSymlinks
  16. const Path = require('path')
  17. const fs = require('fs')
  18. const Settings = require('@overleaf/settings')
  19. const logger = require('@overleaf/logger')
  20. module.exports = ForbidSymlinks = function (staticFn, root, options) {
  21. const expressStatic = staticFn(root, options)
  22. const basePath = Path.resolve(root)
  23. return function (req, res, next) {
  24. let file, projectId, result
  25. const path = req.url
  26. // check that the path is of the form /project_id_or_name/path/to/file.log
  27. if ((result = path.match(/^\/?([a-zA-Z0-9_-]+)\/(.*)/))) {
  28. projectId = result[1]
  29. file = result[2]
  30. } else {
  31. logger.warn({ path }, 'unrecognized file request')
  32. return res.sendStatus(404)
  33. }
  34. // check that the file does not use a relative path
  35. for (const dir of Array.from(file.split('/'))) {
  36. if (dir === '..') {
  37. logger.warn({ path }, 'attempt to use a relative path')
  38. return res.sendStatus(404)
  39. }
  40. }
  41. // check that the requested path is normalized
  42. const requestedFsPath = `${basePath}/${projectId}/${file}`
  43. if (requestedFsPath !== Path.normalize(requestedFsPath)) {
  44. logger.error(
  45. { path: requestedFsPath },
  46. 'requestedFsPath is not normalized'
  47. )
  48. return res.sendStatus(404)
  49. }
  50. // check that the requested path is not a symlink
  51. return fs.realpath(requestedFsPath, function (err, realFsPath) {
  52. if (err != null) {
  53. if (err.code === 'ENOENT') {
  54. return res.sendStatus(404)
  55. } else {
  56. logger.error(
  57. {
  58. err,
  59. requestedFsPath,
  60. realFsPath,
  61. path: req.params[0],
  62. projectId: req.params.project_id,
  63. },
  64. 'error checking file access'
  65. )
  66. return res.sendStatus(500)
  67. }
  68. } else if (requestedFsPath !== realFsPath) {
  69. logger.warn(
  70. {
  71. requestedFsPath,
  72. realFsPath,
  73. path: req.params[0],
  74. projectId: req.params.project_id,
  75. },
  76. 'trying to access a different file (symlink), aborting'
  77. )
  78. return res.sendStatus(404)
  79. } else {
  80. return expressStatic(req, res, next)
  81. }
  82. })
  83. }
  84. }