PerProjectEncryptedS3Persistor.js 12 KB

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