PersistorHelper.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. const Crypto = require('crypto')
  2. const Stream = require('stream')
  3. const { pipeline } = require('stream/promises')
  4. const Logger = require('@overleaf/logger')
  5. const { WriteError, NotFoundError } = require('./Errors')
  6. // Observes data that passes through and computes some metadata for it
  7. // - specifically, it computes the number of bytes transferred, and optionally
  8. // computes a cryptographic hash based on the 'hash' option. e.g., pass
  9. // { hash: 'md5' } to compute the md5 hash of the stream
  10. // - if 'metric' is supplied as an option, this metric will be incremented by
  11. // the number of bytes transferred
  12. class ObserverStream extends Stream.Transform {
  13. constructor(options) {
  14. super({ autoDestroy: true, ...options })
  15. this.bytes = 0
  16. if (options.hash) {
  17. this.hash = Crypto.createHash(options.hash)
  18. }
  19. if (options.metric && options.Metrics) {
  20. const onEnd = () => {
  21. options.Metrics.count(options.metric, this.bytes)
  22. }
  23. this.once('error', onEnd)
  24. this.once('end', onEnd)
  25. }
  26. }
  27. _transform(chunk, encoding, done) {
  28. if (this.hash) {
  29. this.hash.update(chunk)
  30. }
  31. this.bytes += chunk.length
  32. this.push(chunk)
  33. done()
  34. }
  35. getHash() {
  36. return this.hash && this.hash.digest('hex')
  37. }
  38. }
  39. module.exports = {
  40. ObserverStream,
  41. calculateStreamMd5,
  42. verifyMd5,
  43. wrapError,
  44. hexToBase64,
  45. base64ToHex,
  46. }
  47. // returns a promise which resolves with the md5 hash of the stream
  48. // - consumes the stream
  49. async function calculateStreamMd5(stream) {
  50. const hash = Crypto.createHash('md5')
  51. hash.setEncoding('hex')
  52. await pipeline(stream, hash)
  53. return hash.read()
  54. }
  55. // verifies the md5 hash of a file against the supplied md5 or the one stored in
  56. // storage if not supplied - deletes the new file if the md5 does not match and
  57. // throws an error
  58. async function verifyMd5(persistor, bucket, key, sourceMd5, destMd5 = null) {
  59. if (!destMd5) {
  60. destMd5 = await persistor.getObjectMd5Hash(bucket, key)
  61. }
  62. if (sourceMd5 !== destMd5) {
  63. try {
  64. await persistor.deleteObject(bucket, key)
  65. } catch (err) {
  66. Logger.warn(err, 'error deleting file for invalid upload')
  67. }
  68. throw new WriteError('source and destination hashes do not match', {
  69. sourceMd5,
  70. destMd5,
  71. bucket,
  72. key,
  73. })
  74. }
  75. }
  76. function wrapError(error, message, params, ErrorType) {
  77. if (
  78. error instanceof NotFoundError ||
  79. ['NoSuchKey', 'NotFound', 404, 'AccessDenied', 'ENOENT'].includes(
  80. error.code
  81. ) ||
  82. (error.response && error.response.statusCode === 404)
  83. ) {
  84. return new NotFoundError('no such file', params, error)
  85. } else {
  86. return new ErrorType(message, params, error)
  87. }
  88. }
  89. function base64ToHex(base64) {
  90. return Buffer.from(base64, 'base64').toString('hex')
  91. }
  92. function hexToBase64(hex) {
  93. return Buffer.from(hex, 'hex').toString('base64')
  94. }