StaticServerForbidSymlinks.js 2.7 KB

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