PerProjectEncryptedS3Persistor.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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<void>}
  164. */
  165. async generateDataEncryptionKey(bucketName, path) {
  166. await this.#generateDataEncryptionKeyOptions(bucketName, path)
  167. }
  168. /**
  169. * @param {string} bucketName
  170. * @param {string} path
  171. * @return {Promise<SSECOptions>}
  172. */
  173. async #generateDataEncryptionKeyOptions(bucketName, path) {
  174. const dataEncryptionKey = (
  175. await generateKey('aes', { length: 256 })
  176. ).export()
  177. const { projectFolder, dekPath } = this.#buildProjectPaths(bucketName, path)
  178. await super.sendStream(
  179. this.#settings.dataEncryptionKeyBucketName,
  180. dekPath,
  181. Stream.Readable.from([dataEncryptionKey]),
  182. {
  183. // Do not overwrite any objects if already created
  184. ifNoneMatch: '*',
  185. ssecOptions: await this.#getCurrentKeyEncryptionKey(projectFolder),
  186. contentLength: 32,
  187. }
  188. )
  189. return new SSECOptions(dataEncryptionKey)
  190. }
  191. /**
  192. * @param {string} bucketName
  193. * @param {string} path
  194. * @return {Promise<SSECOptions>}
  195. */
  196. async #getExistingDataEncryptionKeyOptions(bucketName, path) {
  197. const { projectFolder, dekPath } = this.#buildProjectPaths(bucketName, path)
  198. let res
  199. let kekIndex = 0
  200. for (const rootKEK of await this.#availableKeyEncryptionKeysPromise) {
  201. const ssecOptions = await rootKEK.forProject(projectFolder)
  202. try {
  203. res = await super.getObjectStream(
  204. this.#settings.dataEncryptionKeyBucketName,
  205. dekPath,
  206. { ssecOptions }
  207. )
  208. break
  209. } catch (err) {
  210. if (isForbiddenError(err)) {
  211. kekIndex++
  212. continue
  213. }
  214. throw err
  215. }
  216. }
  217. if (!res) throw new NoKEKMatchedError('no kek matched')
  218. const buf = new WritableBuffer()
  219. await Stream.promises.pipeline(res, buf)
  220. if (kekIndex !== 0 && this.#settings.automaticallyRotateDEKEncryption) {
  221. const ssecOptions = await this.#getCurrentKeyEncryptionKey(projectFolder)
  222. try {
  223. await super.sendStream(
  224. this.#settings.dataEncryptionKeyBucketName,
  225. dekPath,
  226. Stream.Readable.from([buf.getContents()]),
  227. { ssecOptions }
  228. )
  229. } catch (err) {
  230. if (this.#settings.ignoreErrorsFromDEKReEncryption) {
  231. logger.warn({ err, dekPath }, 'failed to persist re-encrypted DEK')
  232. } else {
  233. throw err
  234. }
  235. }
  236. }
  237. return new SSECOptions(buf.getContents())
  238. }
  239. /**
  240. * @param {string} bucketName
  241. * @param {string} path
  242. * @return {Promise<SSECOptions>}
  243. */
  244. async #getDataEncryptionKeyOptions(bucketName, path) {
  245. try {
  246. return await this.#getExistingDataEncryptionKeyOptions(bucketName, path)
  247. } catch (err) {
  248. if (err instanceof NotFoundError) {
  249. try {
  250. return await this.#generateDataEncryptionKeyOptions(bucketName, path)
  251. } catch (err2) {
  252. if (err2 instanceof AlreadyWrittenError) {
  253. // Concurrent initial write
  254. return await this.#getExistingDataEncryptionKeyOptions(
  255. bucketName,
  256. path
  257. )
  258. }
  259. throw err2
  260. }
  261. }
  262. throw err
  263. }
  264. }
  265. async sendStream(bucketName, path, sourceStream, opts = {}) {
  266. const ssecOptions =
  267. opts.ssecOptions ||
  268. (await this.#getDataEncryptionKeyOptions(bucketName, path))
  269. return await super.sendStream(bucketName, path, sourceStream, {
  270. ...opts,
  271. ssecOptions,
  272. })
  273. }
  274. async getObjectStream(bucketName, path, opts = {}) {
  275. const ssecOptions =
  276. opts.ssecOptions ||
  277. (await this.#getExistingDataEncryptionKeyOptions(bucketName, path))
  278. return await super.getObjectStream(bucketName, path, {
  279. ...opts,
  280. ssecOptions,
  281. })
  282. }
  283. async getObjectSize(bucketName, path, opts = {}) {
  284. const ssecOptions =
  285. opts.ssecOptions ||
  286. (await this.#getExistingDataEncryptionKeyOptions(bucketName, path))
  287. return await super.getObjectSize(bucketName, path, { ...opts, ssecOptions })
  288. }
  289. async getObjectStorageClass(bucketName, path, opts = {}) {
  290. const ssecOptions =
  291. opts.ssecOptions ||
  292. (await this.#getExistingDataEncryptionKeyOptions(bucketName, path))
  293. return await super.getObjectStorageClass(bucketName, path, {
  294. ...opts,
  295. ssecOptions,
  296. })
  297. }
  298. async directorySize(bucketName, path, continuationToken) {
  299. // Note: Listing a bucket does not require SSE-C credentials.
  300. return await super.directorySize(bucketName, path, continuationToken)
  301. }
  302. async deleteDirectory(bucketName, path, continuationToken) {
  303. // Note: Listing/Deleting a prefix does not require SSE-C credentials.
  304. await super.deleteDirectory(bucketName, path, continuationToken)
  305. const { projectFolder, dekPath } = this.#buildProjectPaths(bucketName, path)
  306. if (projectFolder === path) {
  307. await super.deleteObject(
  308. this.#settings.dataEncryptionKeyBucketName,
  309. dekPath
  310. )
  311. }
  312. }
  313. async getObjectMd5Hash(bucketName, path, opts = {}) {
  314. // The ETag in object metadata is not the MD5 content hash, skip the HEAD request.
  315. opts = { ...opts, etagIsNotMD5: true }
  316. return await super.getObjectMd5Hash(bucketName, path, opts)
  317. }
  318. async copyObject(bucketName, sourcePath, destinationPath, opts = {}) {
  319. const ssecOptions =
  320. opts.ssecOptions ||
  321. (await this.#getDataEncryptionKeyOptions(bucketName, destinationPath))
  322. const ssecSrcOptions =
  323. opts.ssecSrcOptions ||
  324. (await this.#getExistingDataEncryptionKeyOptions(bucketName, sourcePath))
  325. return await super.copyObject(bucketName, sourcePath, destinationPath, {
  326. ...opts,
  327. ssecOptions,
  328. ssecSrcOptions,
  329. })
  330. }
  331. /**
  332. * @param {string} bucketName
  333. * @param {string} path
  334. * @return {Promise<string>}
  335. */
  336. async getRedirectUrl(bucketName, path) {
  337. throw new NotImplementedError('signed links are not supported with SSE-C')
  338. }
  339. }
  340. /**
  341. * Helper class for batch updates to avoid repeated fetching of the project path.
  342. *
  343. * A general "cache" for project keys is another alternative. For now, use a helper class.
  344. */
  345. class CachedPerProjectEncryptedS3Persistor {
  346. /** @type SSECOptions */
  347. #projectKeyOptions
  348. /** @type PerProjectEncryptedS3Persistor */
  349. #parent
  350. /**
  351. * @param {PerProjectEncryptedS3Persistor} parent
  352. * @param {SSECOptions} projectKeyOptions
  353. */
  354. constructor(parent, projectKeyOptions) {
  355. this.#parent = parent
  356. this.#projectKeyOptions = projectKeyOptions
  357. }
  358. /**
  359. * @param {string} bucketName
  360. * @param {string} path
  361. * @param {string} fsPath
  362. */
  363. async sendFile(bucketName, path, fsPath) {
  364. return await this.sendStream(bucketName, path, fs.createReadStream(fsPath))
  365. }
  366. /**
  367. * @param {string} bucketName
  368. * @param {string} path
  369. * @param {NodeJS.ReadableStream} sourceStream
  370. * @param {Object} opts
  371. * @param {string} [opts.contentType]
  372. * @param {string} [opts.contentEncoding]
  373. * @param {number} [opts.contentLength]
  374. * @param {'*'} [opts.ifNoneMatch]
  375. * @param {SSECOptions} [opts.ssecOptions]
  376. * @param {string} [opts.sourceMd5]
  377. * @return {Promise<void>}
  378. */
  379. async sendStream(bucketName, path, sourceStream, opts = {}) {
  380. return await this.#parent.sendStream(bucketName, path, sourceStream, {
  381. ...opts,
  382. ssecOptions: this.#projectKeyOptions,
  383. })
  384. }
  385. /**
  386. * @param {string} bucketName
  387. * @param {string} path
  388. * @param {Object} opts
  389. * @param {number} [opts.start]
  390. * @param {number} [opts.end]
  391. * @param {boolean} [opts.autoGunzip]
  392. * @param {SSECOptions} [opts.ssecOptions]
  393. * @return {Promise<NodeJS.ReadableStream>}
  394. */
  395. async getObjectStream(bucketName, path, opts = {}) {
  396. return await this.#parent.getObjectStream(bucketName, path, {
  397. ...opts,
  398. ssecOptions: this.#projectKeyOptions,
  399. })
  400. }
  401. }
  402. module.exports = {
  403. PerProjectEncryptedS3Persistor,
  404. CachedPerProjectEncryptedS3Persistor,
  405. RootKeyEncryptionKey,
  406. }