S3Persistor.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. // @ts-check
  2. const http = require('node:http')
  3. const https = require('node:https')
  4. if (http.globalAgent.maxSockets < 300) {
  5. http.globalAgent.maxSockets = 300
  6. }
  7. if (https.globalAgent.maxSockets < 300) {
  8. https.globalAgent.maxSockets = 300
  9. }
  10. const Crypto = require('node:crypto')
  11. const Metrics = require('@overleaf/metrics')
  12. const AbstractPersistor = require('./AbstractPersistor')
  13. const PersistorHelper = require('./PersistorHelper')
  14. const { pipeline, PassThrough } = require('node:stream')
  15. const fs = require('node:fs')
  16. const S3 = require('aws-sdk/clients/s3')
  17. const { URL } = require('node:url')
  18. const { WriteError, ReadError, NotFoundError } = require('./Errors')
  19. /**
  20. * Wrapper with private fields to avoid revealing them on console, JSON.stringify or similar.
  21. */
  22. class SSECOptions {
  23. #keyAsBuffer
  24. #keyMD5
  25. /**
  26. * @param {Buffer} keyAsBuffer
  27. */
  28. constructor(keyAsBuffer) {
  29. this.#keyAsBuffer = keyAsBuffer
  30. this.#keyMD5 = Crypto.createHash('md5').update(keyAsBuffer).digest('base64')
  31. }
  32. getPutOptions() {
  33. return {
  34. SSECustomerKey: this.#keyAsBuffer,
  35. SSECustomerKeyMD5: this.#keyMD5,
  36. SSECustomerAlgorithm: 'AES256',
  37. }
  38. }
  39. getGetOptions() {
  40. return {
  41. SSECustomerKey: this.#keyAsBuffer,
  42. SSECustomerKeyMD5: this.#keyMD5,
  43. SSECustomerAlgorithm: 'AES256',
  44. }
  45. }
  46. getCopyOptions() {
  47. return {
  48. CopySourceSSECustomerKey: this.#keyAsBuffer,
  49. CopySourceSSECustomerKeyMD5: this.#keyMD5,
  50. CopySourceSSECustomerAlgorithm: 'AES256',
  51. }
  52. }
  53. }
  54. class S3Persistor extends AbstractPersistor {
  55. constructor(settings = {}) {
  56. super()
  57. this.settings = settings
  58. }
  59. /**
  60. * @param {string} bucketName
  61. * @param {string} key
  62. * @param {string} fsPath
  63. * @return {Promise<void>}
  64. */
  65. async sendFile(bucketName, key, fsPath) {
  66. await this.sendStream(bucketName, key, fs.createReadStream(fsPath))
  67. }
  68. /**
  69. * @param {string} bucketName
  70. * @param {string} key
  71. * @param {NodeJS.ReadableStream} readStream
  72. * @param {Object} opts
  73. * @param {string} [opts.contentType]
  74. * @param {string} [opts.contentEncoding]
  75. * @param {'*'} [opts.ifNoneMatch]
  76. * @param {SSECOptions} [opts.ssecOptions]
  77. * @param {string} [opts.sourceMd5]
  78. * @return {Promise<void>}
  79. */
  80. async sendStream(bucketName, key, readStream, opts = {}) {
  81. try {
  82. const observeOptions = {
  83. metric: 's3.egress', // egress from us to S3
  84. bucket: bucketName,
  85. }
  86. const observer = new PersistorHelper.ObserverStream(observeOptions)
  87. // observer will catch errors, clean up and log a warning
  88. pipeline(readStream, observer, () => {})
  89. // if we have an md5 hash, pass this to S3 to verify the upload
  90. const uploadOptions = {
  91. Bucket: bucketName,
  92. Key: key,
  93. Body: observer,
  94. }
  95. if (opts.contentType) {
  96. uploadOptions.ContentType = opts.contentType
  97. }
  98. if (opts.contentEncoding) {
  99. uploadOptions.ContentEncoding = opts.contentEncoding
  100. }
  101. if (opts.ifNoneMatch === '*') {
  102. uploadOptions.IfNoneMatch = '*'
  103. }
  104. if (opts.ssecOptions) {
  105. Object.assign(uploadOptions, opts.ssecOptions.getPutOptions())
  106. }
  107. // if we have an md5 hash, pass this to S3 to verify the upload - otherwise
  108. // we rely on the S3 client's checksum calculation to validate the upload
  109. const clientOptions = {}
  110. if (opts.sourceMd5) {
  111. uploadOptions.ContentMD5 = PersistorHelper.hexToBase64(opts.sourceMd5)
  112. } else {
  113. clientOptions.computeChecksums = true
  114. }
  115. await this._getClientForBucket(bucketName, clientOptions)
  116. .upload(uploadOptions, { partSize: this.settings.partSize })
  117. .promise()
  118. } catch (err) {
  119. throw PersistorHelper.wrapError(
  120. err,
  121. 'upload to S3 failed',
  122. { bucketName, key, ifNoneMatch: opts.ifNoneMatch },
  123. WriteError
  124. )
  125. }
  126. }
  127. /**
  128. * @param {string} bucketName
  129. * @param {string} key
  130. * @param {Object} opts
  131. * @param {number} [opts.start]
  132. * @param {number} [opts.end]
  133. * @param {string} [opts.contentEncoding]
  134. * @param {SSECOptions} [opts.ssecOptions]
  135. * @return {Promise<NodeJS.ReadableStream>}
  136. */
  137. async getObjectStream(bucketName, key, opts) {
  138. opts = opts || {}
  139. const params = {
  140. Bucket: bucketName,
  141. Key: key,
  142. }
  143. if (opts.start != null && opts.end != null) {
  144. params.Range = `bytes=${opts.start}-${opts.end}`
  145. }
  146. if (opts.ssecOptions) {
  147. Object.assign(params, opts.ssecOptions.getGetOptions())
  148. }
  149. const observer = new PersistorHelper.ObserverStream({
  150. metric: 's3.ingress', // ingress from S3 to us
  151. bucket: bucketName,
  152. })
  153. const req = this._getClientForBucket(bucketName).getObject(params)
  154. const stream = req.createReadStream()
  155. try {
  156. await new Promise((resolve, reject) => {
  157. req.on('httpHeaders', statusCode => {
  158. switch (statusCode) {
  159. case 200: // full response
  160. case 206: // partial response
  161. return resolve(undefined)
  162. case 403: // AccessDenied
  163. return // handled by stream.on('error') handler below
  164. case 404: // NoSuchKey
  165. return reject(new NotFoundError('not found'))
  166. default:
  167. // handled by stream.on('error') handler below
  168. }
  169. })
  170. // The AWS SDK is forwarding any errors from the request to the stream.
  171. // The AWS SDK is emitting additional errors on the stream ahead of starting to stream.
  172. stream.on('error', reject)
  173. // The AWS SDK is kicking off the request in the next event loop cycle.
  174. })
  175. } catch (err) {
  176. throw PersistorHelper.wrapError(
  177. err,
  178. 'error reading file from S3',
  179. { bucketName, key, opts },
  180. ReadError
  181. )
  182. }
  183. // Return a PassThrough stream with a minimal interface. It will buffer until the caller starts reading. It will emit errors from the source stream (Stream.pipeline passes errors along).
  184. const pass = new PassThrough()
  185. pipeline(stream, observer, pass, err => {
  186. if (err) req.abort()
  187. })
  188. return pass
  189. }
  190. /**
  191. * @param {string} bucketName
  192. * @param {string} key
  193. * @return {Promise<string>}
  194. */
  195. async getRedirectUrl(bucketName, key) {
  196. const expiresSeconds = Math.round(this.settings.signedUrlExpiryInMs / 1000)
  197. try {
  198. return await this._getClientForBucket(bucketName).getSignedUrlPromise(
  199. 'getObject',
  200. {
  201. Bucket: bucketName,
  202. Key: key,
  203. Expires: expiresSeconds,
  204. }
  205. )
  206. } catch (err) {
  207. throw PersistorHelper.wrapError(
  208. err,
  209. 'error generating signed url for S3 file',
  210. { bucketName, key },
  211. ReadError
  212. )
  213. }
  214. }
  215. /**
  216. * @param {string} bucketName
  217. * @param {string} key
  218. * @param {string} [continuationToken]
  219. * @return {Promise<void>}
  220. */
  221. async deleteDirectory(bucketName, key, continuationToken) {
  222. let response
  223. const options = { Bucket: bucketName, Prefix: key }
  224. if (continuationToken) {
  225. options.ContinuationToken = continuationToken
  226. }
  227. try {
  228. response = await this._getClientForBucket(bucketName)
  229. .listObjectsV2(options)
  230. .promise()
  231. } catch (err) {
  232. throw PersistorHelper.wrapError(
  233. err,
  234. 'failed to list objects in S3',
  235. { bucketName, key },
  236. ReadError
  237. )
  238. }
  239. const objects = response.Contents?.map(item => ({ Key: item.Key || '' }))
  240. if (objects?.length) {
  241. try {
  242. await this._getClientForBucket(bucketName)
  243. .deleteObjects({
  244. Bucket: bucketName,
  245. Delete: {
  246. Objects: objects,
  247. Quiet: true,
  248. },
  249. })
  250. .promise()
  251. } catch (err) {
  252. throw PersistorHelper.wrapError(
  253. err,
  254. 'failed to delete objects in S3',
  255. { bucketName, key },
  256. WriteError
  257. )
  258. }
  259. }
  260. if (response.IsTruncated) {
  261. await this.deleteDirectory(
  262. bucketName,
  263. key,
  264. response.NextContinuationToken
  265. )
  266. }
  267. }
  268. /**
  269. * @param {string} bucketName
  270. * @param {string} key
  271. * @param {Object} opts
  272. * @param {SSECOptions} [opts.ssecOptions]
  273. * @return {Promise<S3.HeadObjectOutput>}
  274. */
  275. async #headObject(bucketName, key, opts = {}) {
  276. const params = { Bucket: bucketName, Key: key }
  277. if (opts.ssecOptions) {
  278. Object.assign(params, opts.ssecOptions.getGetOptions())
  279. }
  280. try {
  281. return await this._getClientForBucket(bucketName)
  282. .headObject(params)
  283. .promise()
  284. } catch (err) {
  285. throw PersistorHelper.wrapError(
  286. err,
  287. 'error getting size of s3 object',
  288. { bucketName, key },
  289. ReadError
  290. )
  291. }
  292. }
  293. /**
  294. * @param {string} bucketName
  295. * @param {string} key
  296. * @param {Object} opts
  297. * @param {SSECOptions} [opts.ssecOptions]
  298. * @return {Promise<number>}
  299. */
  300. async getObjectSize(bucketName, key, opts = {}) {
  301. const response = await this.#headObject(bucketName, key, opts)
  302. return response.ContentLength || 0
  303. }
  304. /**
  305. * @param {string} bucketName
  306. * @param {string} key
  307. * @param {Object} opts
  308. * @param {SSECOptions} [opts.ssecOptions]
  309. * @param {boolean} [opts.etagIsNotMD5]
  310. * @return {Promise<string>}
  311. */
  312. async getObjectMd5Hash(bucketName, key, opts = {}) {
  313. try {
  314. if (!opts.etagIsNotMD5) {
  315. const response = await this.#headObject(bucketName, key, opts)
  316. const md5 = S3Persistor._md5FromResponse(response)
  317. if (md5) {
  318. return md5
  319. }
  320. }
  321. // etag is not in md5 format
  322. Metrics.inc('s3.md5Download')
  323. return await PersistorHelper.calculateStreamMd5(
  324. await this.getObjectStream(bucketName, key, opts)
  325. )
  326. } catch (err) {
  327. throw PersistorHelper.wrapError(
  328. err,
  329. 'error getting hash of s3 object',
  330. { bucketName, key },
  331. ReadError
  332. )
  333. }
  334. }
  335. /**
  336. * @param {string} bucketName
  337. * @param {string} key
  338. * @return {Promise<void>}
  339. */
  340. async deleteObject(bucketName, key) {
  341. try {
  342. await this._getClientForBucket(bucketName)
  343. .deleteObject({ Bucket: bucketName, Key: key })
  344. .promise()
  345. } catch (err) {
  346. // s3 does not give us a NotFoundError here
  347. throw PersistorHelper.wrapError(
  348. err,
  349. 'failed to delete file in S3',
  350. { bucketName, key },
  351. WriteError
  352. )
  353. }
  354. }
  355. /**
  356. * @param {string} bucketName
  357. * @param {string} sourceKey
  358. * @param {string} destKey
  359. * @param {Object} opts
  360. * @param {SSECOptions} [opts.ssecSrcOptions]
  361. * @param {SSECOptions} [opts.ssecOptions]
  362. * @return {Promise<void>}
  363. */
  364. async copyObject(bucketName, sourceKey, destKey, opts = {}) {
  365. const params = {
  366. Bucket: bucketName,
  367. Key: destKey,
  368. CopySource: `${bucketName}/${sourceKey}`,
  369. }
  370. if (opts.ssecSrcOptions) {
  371. Object.assign(params, opts.ssecSrcOptions.getCopyOptions())
  372. }
  373. if (opts.ssecOptions) {
  374. Object.assign(params, opts.ssecOptions.getPutOptions())
  375. }
  376. try {
  377. await this._getClientForBucket(bucketName).copyObject(params).promise()
  378. } catch (err) {
  379. throw PersistorHelper.wrapError(
  380. err,
  381. 'failed to copy file in S3',
  382. params,
  383. WriteError
  384. )
  385. }
  386. }
  387. /**
  388. * @param {string} bucketName
  389. * @param {string} key
  390. * @param {Object} opts
  391. * @param {SSECOptions} [opts.ssecOptions]
  392. * @return {Promise<boolean>}
  393. */
  394. async checkIfObjectExists(bucketName, key, opts) {
  395. try {
  396. await this.getObjectSize(bucketName, key, opts)
  397. return true
  398. } catch (err) {
  399. if (err instanceof NotFoundError) {
  400. return false
  401. }
  402. throw PersistorHelper.wrapError(
  403. err,
  404. 'error checking whether S3 object exists',
  405. { bucketName, key },
  406. ReadError
  407. )
  408. }
  409. }
  410. /**
  411. * @param {string} bucketName
  412. * @param {string} key
  413. * @param {string} [continuationToken]
  414. * @return {Promise<number>}
  415. */
  416. async directorySize(bucketName, key, continuationToken) {
  417. try {
  418. const options = {
  419. Bucket: bucketName,
  420. Prefix: key,
  421. }
  422. if (continuationToken) {
  423. options.ContinuationToken = continuationToken
  424. }
  425. const response = await this._getClientForBucket(bucketName)
  426. .listObjectsV2(options)
  427. .promise()
  428. const size =
  429. response.Contents?.reduce((acc, item) => (item.Size || 0) + acc, 0) || 0
  430. if (response.IsTruncated) {
  431. return (
  432. size +
  433. (await this.directorySize(
  434. bucketName,
  435. key,
  436. response.NextContinuationToken
  437. ))
  438. )
  439. }
  440. return size
  441. } catch (err) {
  442. throw PersistorHelper.wrapError(
  443. err,
  444. 'error getting directory size in S3',
  445. { bucketName, key },
  446. ReadError
  447. )
  448. }
  449. }
  450. /**
  451. * @param {string} bucket
  452. * @param {Object} [clientOptions]
  453. * @return {S3}
  454. * @private
  455. */
  456. _getClientForBucket(bucket, clientOptions) {
  457. return new S3(
  458. this._buildClientOptions(
  459. this.settings.bucketCreds?.[bucket],
  460. clientOptions
  461. )
  462. )
  463. }
  464. /**
  465. * @param {Object} bucketCredentials
  466. * @param {Object} clientOptions
  467. * @return {Object}
  468. * @private
  469. */
  470. _buildClientOptions(bucketCredentials, clientOptions) {
  471. const options = clientOptions || {}
  472. if (bucketCredentials) {
  473. options.credentials = {
  474. accessKeyId: bucketCredentials.auth_key,
  475. secretAccessKey: bucketCredentials.auth_secret,
  476. }
  477. } else if (this.settings.key) {
  478. options.credentials = {
  479. accessKeyId: this.settings.key,
  480. secretAccessKey: this.settings.secret,
  481. }
  482. } else {
  483. // Use the default credentials provider (process.env -> SSP -> ini -> IAM)
  484. // Docs: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CredentialProviderChain.html#defaultProviders-property
  485. }
  486. if (this.settings.endpoint) {
  487. const endpoint = new URL(this.settings.endpoint)
  488. options.endpoint = this.settings.endpoint
  489. options.sslEnabled = endpoint.protocol === 'https:'
  490. }
  491. // path-style access is only used for acceptance tests
  492. if (this.settings.pathStyle) {
  493. options.s3ForcePathStyle = true
  494. }
  495. for (const opt of ['httpOptions', 'maxRetries', 'region']) {
  496. if (this.settings[opt]) {
  497. options[opt] = this.settings[opt]
  498. }
  499. }
  500. if (options.sslEnabled && this.settings.ca && !options.httpOptions?.agent) {
  501. options.httpOptions = options.httpOptions || {}
  502. options.httpOptions.agent = new https.Agent({
  503. rejectUnauthorized: true,
  504. ca: this.settings.ca,
  505. })
  506. }
  507. return options
  508. }
  509. /**
  510. * @param {S3.HeadObjectOutput} response
  511. * @return {string|null}
  512. * @private
  513. */
  514. static _md5FromResponse(response) {
  515. const md5 = (response.ETag || '').replace(/[ "]/g, '')
  516. if (!md5.match(/^[a-f0-9]{32}$/)) {
  517. return null
  518. }
  519. return md5
  520. }
  521. }
  522. module.exports = {
  523. S3Persistor,
  524. SSECOptions,
  525. }