PerProjectEncryptedS3Persistor.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. // @ts-check
  2. const Crypto = require('node:crypto')
  3. const Stream = require('node:stream')
  4. const fs = require('node:fs')
  5. const { promisify } = require('node:util')
  6. const { WritableBuffer } = require('@overleaf/stream-utils')
  7. const { S3Persistor, SSECOptions } = require('./S3Persistor.js')
  8. const {
  9. AlreadyWrittenError,
  10. NoKEKMatchedError,
  11. NotFoundError,
  12. NotImplementedError,
  13. ReadError,
  14. } = require('./Errors')
  15. const logger = require('@overleaf/logger')
  16. const Path = require('node:path')
  17. const generateKey = promisify(Crypto.generateKey)
  18. const hkdf = promisify(Crypto.hkdf)
  19. const AES256_KEY_LENGTH = 32
  20. /**
  21. * @typedef {import('aws-sdk').AWSError} AWSError
  22. */
  23. /**
  24. * @typedef {Object} Settings
  25. * @property {boolean} automaticallyRotateDEKEncryption
  26. * @property {string} dataEncryptionKeyBucketName
  27. * @property {boolean} ignoreErrorsFromDEKReEncryption
  28. * @property {(bucketName: string, path: string) => string} pathToProjectFolder
  29. * @property {() => Promise<Array<RootKeyEncryptionKey>>} getRootKeyEncryptionKeys
  30. */
  31. /**
  32. * Helper function to make TS happy when accessing error properties
  33. * AWSError is not an actual class, so we cannot use instanceof.
  34. * @param {any} err
  35. * @return {err is AWSError}
  36. */
  37. function isAWSError(err) {
  38. return !!err
  39. }
  40. /**
  41. * @param {any} err
  42. * @return {boolean}
  43. */
  44. function isForbiddenError(err) {
  45. if (!err || !(err instanceof ReadError || err instanceof NotFoundError)) {
  46. return false
  47. }
  48. const cause = err.cause
  49. if (!isAWSError(cause)) return false
  50. return cause.statusCode === 403
  51. }
  52. class RootKeyEncryptionKey {
  53. /** @type {Buffer} */
  54. #keyEncryptionKey
  55. /** @type {Buffer} */
  56. #salt
  57. /**
  58. * @param {Buffer} keyEncryptionKey
  59. * @param {Buffer} salt
  60. */
  61. constructor(keyEncryptionKey, salt) {
  62. if (keyEncryptionKey.byteLength !== AES256_KEY_LENGTH) {
  63. throw new Error(`kek is not ${AES256_KEY_LENGTH} bytes long`)
  64. }
  65. this.#keyEncryptionKey = keyEncryptionKey
  66. this.#salt = salt
  67. }
  68. /**
  69. * @param {string} prefix
  70. * @return {Promise<SSECOptions>}
  71. */
  72. async forProject(prefix) {
  73. return new SSECOptions(
  74. Buffer.from(
  75. await hkdf(
  76. 'sha256',
  77. this.#keyEncryptionKey,
  78. this.#salt,
  79. prefix,
  80. AES256_KEY_LENGTH
  81. )
  82. )
  83. )
  84. }
  85. }
  86. class PerProjectEncryptedS3Persistor extends S3Persistor {
  87. /** @type {Settings} */
  88. #settings
  89. /** @type {Promise<Array<RootKeyEncryptionKey>>} */
  90. #availableKeyEncryptionKeysPromise
  91. /**
  92. * @param {Settings} settings
  93. */
  94. constructor(settings) {
  95. if (!settings.dataEncryptionKeyBucketName) {
  96. throw new Error('settings.dataEncryptionKeyBucketName is missing')
  97. }
  98. super(settings)
  99. this.#settings = settings
  100. this.#availableKeyEncryptionKeysPromise = settings
  101. .getRootKeyEncryptionKeys()
  102. .then(rootKEKs => {
  103. if (rootKEKs.length === 0) throw new Error('no root kek provided')
  104. return rootKEKs
  105. })
  106. }
  107. async ensureKeyEncryptionKeysLoaded() {
  108. await this.#availableKeyEncryptionKeysPromise
  109. }
  110. /**
  111. * @param {string} bucketName
  112. * @param {string} path
  113. * @return {{dekPath: string, projectFolder: string}}
  114. */
  115. #buildProjectPaths(bucketName, path) {
  116. const projectFolder = this.#settings.pathToProjectFolder(bucketName, path)
  117. const dekPath = Path.join(projectFolder, 'dek')
  118. return { projectFolder, dekPath }
  119. }
  120. /**
  121. * @param {string} projectFolder
  122. * @return {Promise<SSECOptions>}
  123. */
  124. async #getCurrentKeyEncryptionKey(projectFolder) {
  125. const [currentRootKEK] = await this.#availableKeyEncryptionKeysPromise
  126. return await currentRootKEK.forProject(projectFolder)
  127. }
  128. /**
  129. * @param {string} bucketName
  130. * @param {string} path
  131. */
  132. async getDataEncryptionKeySize(bucketName, path) {
  133. const { projectFolder, dekPath } = this.#buildProjectPaths(bucketName, path)
  134. for (const rootKEK of await this.#availableKeyEncryptionKeysPromise) {
  135. const ssecOptions = await rootKEK.forProject(projectFolder)
  136. try {
  137. return await super.getObjectSize(
  138. this.#settings.dataEncryptionKeyBucketName,
  139. dekPath,
  140. { ssecOptions }
  141. )
  142. } catch (err) {
  143. if (isForbiddenError(err)) continue
  144. throw err
  145. }
  146. }
  147. throw new NoKEKMatchedError('no kek matched')
  148. }
  149. /**
  150. * @param {string} bucketName
  151. * @param {string} path
  152. * @return {Promise<CachedPerProjectEncryptedS3Persistor>}
  153. */
  154. async forProject(bucketName, path) {
  155. return new CachedPerProjectEncryptedS3Persistor(
  156. this,
  157. await this.#getDataEncryptionKeyOptions(bucketName, path)
  158. )
  159. }
  160. /**
  161. * @param {string} bucketName
  162. * @param {string} path
  163. * @return {Promise<CachedPerProjectEncryptedS3Persistor>}
  164. */
  165. async forProjectRO(bucketName, path) {
  166. return new CachedPerProjectEncryptedS3Persistor(
  167. this,
  168. await this.#getExistingDataEncryptionKeyOptions(bucketName, path)
  169. )
  170. }
  171. /**
  172. * @param {string} bucketName
  173. * @param {string} path
  174. * @return {Promise<CachedPerProjectEncryptedS3Persistor>}
  175. */
  176. async generateDataEncryptionKey(bucketName, path) {
  177. return new CachedPerProjectEncryptedS3Persistor(
  178. this,
  179. await this.#generateDataEncryptionKeyOptions(bucketName, path)
  180. )
  181. }
  182. /**
  183. * @param {string} bucketName
  184. * @param {string} path
  185. * @return {Promise<SSECOptions>}
  186. */
  187. async #generateDataEncryptionKeyOptions(bucketName, path) {
  188. const dataEncryptionKey = (
  189. await generateKey('aes', { length: 256 })
  190. ).export()
  191. const { projectFolder, dekPath } = this.#buildProjectPaths(bucketName, path)
  192. await super.sendStream(
  193. this.#settings.dataEncryptionKeyBucketName,
  194. dekPath,
  195. Stream.Readable.from([dataEncryptionKey]),
  196. {
  197. // Do not overwrite any objects if already created
  198. ifNoneMatch: '*',
  199. ssecOptions: await this.#getCurrentKeyEncryptionKey(projectFolder),
  200. contentLength: 32,
  201. }
  202. )
  203. return new SSECOptions(dataEncryptionKey)
  204. }
  205. /**
  206. * @param {string} bucketName
  207. * @param {string} path
  208. * @return {Promise<SSECOptions>}
  209. */
  210. async #getExistingDataEncryptionKeyOptions(bucketName, path) {
  211. const { projectFolder, dekPath } = this.#buildProjectPaths(bucketName, path)
  212. let res
  213. let kekIndex = 0
  214. for (const rootKEK of await this.#availableKeyEncryptionKeysPromise) {
  215. const ssecOptions = await rootKEK.forProject(projectFolder)
  216. try {
  217. res = await super.getObjectStream(
  218. this.#settings.dataEncryptionKeyBucketName,
  219. dekPath,
  220. { ssecOptions }
  221. )
  222. break
  223. } catch (err) {
  224. if (isForbiddenError(err)) {
  225. kekIndex++
  226. continue
  227. }
  228. throw err
  229. }
  230. }
  231. if (!res) throw new NoKEKMatchedError('no kek matched')
  232. const buf = new WritableBuffer()
  233. await Stream.promises.pipeline(res, buf)
  234. if (kekIndex !== 0 && this.#settings.automaticallyRotateDEKEncryption) {
  235. const ssecOptions = await this.#getCurrentKeyEncryptionKey(projectFolder)
  236. try {
  237. await super.sendStream(
  238. this.#settings.dataEncryptionKeyBucketName,
  239. dekPath,
  240. Stream.Readable.from([buf.getContents()]),
  241. { ssecOptions }
  242. )
  243. } catch (err) {
  244. if (this.#settings.ignoreErrorsFromDEKReEncryption) {
  245. logger.warn({ err, dekPath }, 'failed to persist re-encrypted DEK')
  246. } else {
  247. throw err
  248. }
  249. }
  250. }
  251. return new SSECOptions(buf.getContents())
  252. }
  253. /**
  254. * @param {string} bucketName
  255. * @param {string} path
  256. * @return {Promise<SSECOptions>}
  257. */
  258. async #getDataEncryptionKeyOptions(bucketName, path) {
  259. try {
  260. return await this.#getExistingDataEncryptionKeyOptions(bucketName, path)
  261. } catch (err) {
  262. if (err instanceof NotFoundError) {
  263. try {
  264. return await this.#generateDataEncryptionKeyOptions(bucketName, path)
  265. } catch (err2) {
  266. if (err2 instanceof AlreadyWrittenError) {
  267. // Concurrent initial write
  268. return await this.#getExistingDataEncryptionKeyOptions(
  269. bucketName,
  270. path
  271. )
  272. }
  273. throw err2
  274. }
  275. }
  276. throw err
  277. }
  278. }
  279. async sendStream(bucketName, path, sourceStream, opts = {}) {
  280. const ssecOptions =
  281. opts.ssecOptions ||
  282. (await this.#getDataEncryptionKeyOptions(bucketName, path))
  283. return await super.sendStream(bucketName, path, sourceStream, {
  284. ...opts,
  285. ssecOptions,
  286. })
  287. }
  288. async getObjectStream(bucketName, path, opts = {}) {
  289. const ssecOptions =
  290. opts.ssecOptions ||
  291. (await this.#getExistingDataEncryptionKeyOptions(bucketName, path))
  292. return await super.getObjectStream(bucketName, path, {
  293. ...opts,
  294. ssecOptions,
  295. })
  296. }
  297. async getObjectSize(bucketName, path, opts = {}) {
  298. const ssecOptions =
  299. opts.ssecOptions ||
  300. (await this.#getExistingDataEncryptionKeyOptions(bucketName, path))
  301. return await super.getObjectSize(bucketName, path, { ...opts, ssecOptions })
  302. }
  303. async getObjectStorageClass(bucketName, path, opts = {}) {
  304. const ssecOptions =
  305. opts.ssecOptions ||
  306. (await this.#getExistingDataEncryptionKeyOptions(bucketName, path))
  307. return await super.getObjectStorageClass(bucketName, path, {
  308. ...opts,
  309. ssecOptions,
  310. })
  311. }
  312. async directorySize(bucketName, path, continuationToken) {
  313. // Note: Listing a bucket does not require SSE-C credentials.
  314. return await super.directorySize(bucketName, path, continuationToken)
  315. }
  316. async deleteDirectory(bucketName, path, continuationToken) {
  317. // Note: Listing/Deleting a prefix does not require SSE-C credentials.
  318. await super.deleteDirectory(bucketName, path, continuationToken)
  319. const { projectFolder, dekPath } = this.#buildProjectPaths(bucketName, path)
  320. if (projectFolder === path) {
  321. await super.deleteObject(
  322. this.#settings.dataEncryptionKeyBucketName,
  323. dekPath
  324. )
  325. }
  326. }
  327. async getObjectMd5Hash(bucketName, path, opts = {}) {
  328. // The ETag in object metadata is not the MD5 content hash, skip the HEAD request.
  329. opts = { ...opts, etagIsNotMD5: true }
  330. return await super.getObjectMd5Hash(bucketName, path, opts)
  331. }
  332. async copyObject(bucketName, sourcePath, destinationPath, opts = {}) {
  333. const ssecOptions =
  334. opts.ssecOptions ||
  335. (await this.#getDataEncryptionKeyOptions(bucketName, destinationPath))
  336. const ssecSrcOptions =
  337. opts.ssecSrcOptions ||
  338. (await this.#getExistingDataEncryptionKeyOptions(bucketName, sourcePath))
  339. return await super.copyObject(bucketName, sourcePath, destinationPath, {
  340. ...opts,
  341. ssecOptions,
  342. ssecSrcOptions,
  343. })
  344. }
  345. /**
  346. * @param {string} bucketName
  347. * @param {string} path
  348. * @return {Promise<string>}
  349. */
  350. async getRedirectUrl(bucketName, path) {
  351. throw new NotImplementedError('signed links are not supported with SSE-C')
  352. }
  353. }
  354. /**
  355. * Helper class for batch updates to avoid repeated fetching of the project path.
  356. *
  357. * A general "cache" for project keys is another alternative. For now, use a helper class.
  358. */
  359. class CachedPerProjectEncryptedS3Persistor {
  360. /** @type SSECOptions */
  361. #projectKeyOptions
  362. /** @type PerProjectEncryptedS3Persistor */
  363. #parent
  364. /**
  365. * @param {PerProjectEncryptedS3Persistor} parent
  366. * @param {SSECOptions} projectKeyOptions
  367. */
  368. constructor(parent, projectKeyOptions) {
  369. this.#parent = parent
  370. this.#projectKeyOptions = projectKeyOptions
  371. }
  372. /**
  373. * @param {string} bucketName
  374. * @param {string} path
  375. * @param {string} fsPath
  376. */
  377. async sendFile(bucketName, path, fsPath) {
  378. return await this.sendStream(bucketName, path, fs.createReadStream(fsPath))
  379. }
  380. /**
  381. * @param {string} bucketName
  382. * @param {string} path
  383. * @param {NodeJS.ReadableStream} sourceStream
  384. * @param {Object} opts
  385. * @param {string} [opts.contentType]
  386. * @param {string} [opts.contentEncoding]
  387. * @param {number} [opts.contentLength]
  388. * @param {'*'} [opts.ifNoneMatch]
  389. * @param {SSECOptions} [opts.ssecOptions]
  390. * @param {string} [opts.sourceMd5]
  391. * @return {Promise<void>}
  392. */
  393. async sendStream(bucketName, path, sourceStream, opts = {}) {
  394. return await this.#parent.sendStream(bucketName, path, sourceStream, {
  395. ...opts,
  396. ssecOptions: this.#projectKeyOptions,
  397. })
  398. }
  399. /**
  400. * @param {string} bucketName
  401. * @param {string} path
  402. * @param {Object} opts
  403. * @param {number} [opts.start]
  404. * @param {number} [opts.end]
  405. * @param {boolean} [opts.autoGunzip]
  406. * @param {SSECOptions} [opts.ssecOptions]
  407. * @return {Promise<NodeJS.ReadableStream>}
  408. */
  409. async getObjectStream(bucketName, path, opts = {}) {
  410. return await this.#parent.getObjectStream(bucketName, path, {
  411. ...opts,
  412. ssecOptions: this.#projectKeyOptions,
  413. })
  414. }
  415. }
  416. module.exports = {
  417. PerProjectEncryptedS3Persistor,
  418. CachedPerProjectEncryptedS3Persistor,
  419. RootKeyEncryptionKey,
  420. }