PersistorHelper.js 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. const crypto = require('crypto')
  2. const Stream = require('stream')
  3. const logger = require('logger-sharelatex')
  4. const metrics = require('metrics-sharelatex')
  5. const { WriteError, ReadError, NotFoundError } = require('./Errors')
  6. const { promisify } = require('util')
  7. const pipeline = promisify(Stream.pipeline)
  8. // Observes data that passes through and computes some metadata for it
  9. // - specifically, it computes the number of bytes transferred, and optionally
  10. // computes a cryptographic hash based on the 'hash' option. e.g., pass
  11. // { hash: 'md5' } to compute the md5 hash of the stream
  12. // - if 'metric' is supplied as an option, this metric will be incremented by
  13. // the number of bytes transferred
  14. class ObserverStream extends Stream.Transform {
  15. constructor(options) {
  16. options.autoDestroy = true
  17. super(options)
  18. this.bytes = 0
  19. if (options.hash) {
  20. this.hash = crypto.createHash(options.hash)
  21. }
  22. if (options.metric) {
  23. const onEnd = () => {
  24. metrics.count(options.metric, this.bytes)
  25. }
  26. this.once('error', onEnd)
  27. this.once('end', onEnd)
  28. }
  29. }
  30. _transform(chunk, encoding, done) {
  31. if (this.hash) {
  32. this.hash.update(chunk)
  33. }
  34. this.bytes += chunk.length
  35. this.push(chunk)
  36. done()
  37. }
  38. getHash() {
  39. return this.hash && this.hash.digest('hex')
  40. }
  41. }
  42. module.exports = {
  43. ObserverStream,
  44. calculateStreamMd5,
  45. verifyMd5,
  46. getReadyPipeline,
  47. wrapError,
  48. hexToBase64,
  49. base64ToHex
  50. }
  51. // returns a promise which resolves with the md5 hash of the stream
  52. // - consumes the stream
  53. function calculateStreamMd5(stream) {
  54. const hash = crypto.createHash('md5')
  55. hash.setEncoding('hex')
  56. return pipeline(stream, hash).then(() => hash.read())
  57. }
  58. // verifies the md5 hash of a file against the supplied md5 or the one stored in
  59. // storage if not supplied - deletes the new file if the md5 does not match and
  60. // throws an error
  61. async function verifyMd5(persistor, bucket, key, sourceMd5, destMd5 = null) {
  62. if (!destMd5) {
  63. destMd5 = await persistor.promises.getFileMd5Hash(bucket, key)
  64. }
  65. if (sourceMd5 !== destMd5) {
  66. try {
  67. await persistor.promises.deleteFile(bucket, key)
  68. } catch (err) {
  69. logger.warn(err, 'error deleting file for invalid upload')
  70. }
  71. throw new WriteError({
  72. message: 'source and destination hashes do not match',
  73. info: {
  74. sourceMd5,
  75. destMd5,
  76. bucket,
  77. key
  78. }
  79. })
  80. }
  81. }
  82. // resolves when a stream is 'readable', or rejects if the stream throws an error
  83. // before that happens - this lets us handle protocol-level errors before trying
  84. // to read them
  85. function getReadyPipeline(...streams) {
  86. return new Promise((resolve, reject) => {
  87. const lastStream = streams.slice(-1)[0]
  88. let resolvedOrErrored = false
  89. const handler = function(err) {
  90. if (!resolvedOrErrored) {
  91. resolvedOrErrored = true
  92. lastStream.removeListener('readable', handler)
  93. if (err) {
  94. return reject(
  95. wrapError(err, 'error before stream became ready', {}, ReadError)
  96. )
  97. }
  98. resolve(lastStream)
  99. }
  100. if (err) {
  101. for (const stream of streams) {
  102. if (!stream.destroyed) {
  103. stream.destroy()
  104. }
  105. }
  106. }
  107. }
  108. pipeline(...streams).catch(handler)
  109. lastStream.on('readable', handler)
  110. })
  111. }
  112. function wrapError(error, message, params, ErrorType) {
  113. if (
  114. error instanceof NotFoundError ||
  115. ['NoSuchKey', 'NotFound', 404, 'AccessDenied', 'ENOENT'].includes(
  116. error.code
  117. ) ||
  118. (error.response && error.response.statusCode === 404)
  119. ) {
  120. return new NotFoundError({
  121. message: 'no such file',
  122. info: params
  123. }).withCause(error)
  124. } else {
  125. return new ErrorType({
  126. message: message,
  127. info: params
  128. }).withCause(error)
  129. }
  130. }
  131. function base64ToHex(base64) {
  132. return Buffer.from(base64, 'base64').toString('hex')
  133. }
  134. function hexToBase64(hex) {
  135. return Buffer.from(hex, 'hex').toString('base64')
  136. }