You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
2.1 KiB

11 months ago
  1. const { EncryptionWorker } = require("../utils/EncryptionWorker");
  2. const { CommunicationKey } = require("../utils/comKey");
  3. /**
  4. * Express Response Object interface with defined encryptionWorker attached to locals property.
  5. * @typedef {import("express").Response & import("express").Response['locals'] & {encryptionWorker: EncryptionWorker} } ResponseWithSigner
  6. */
  7. // You can use this middleware to assign the EncryptionWorker to the response locals
  8. // property so that if can be used to encrypt/decrypt arbitrary data via response object.
  9. // eg: Encrypting API keys in chunk sources.
  10. // The way this functions is that the rolling RSA Communication Key is used server-side to private-key encrypt the raw
  11. // key of the persistent EncryptionManager credentials. Since EncryptionManager credentials do _not_ roll, we should not send them
  12. // even between server<>collector in plaintext because if the user configured the server/collector to be public they could technically
  13. // be exposing the key in transit via the X-Payload-Signer header. Even if this risk is minimal we should not do this.
  14. // This middleware uses the CommunicationKey public key to first decrypt the base64 representation of the EncryptionManager credentials
  15. // and then loads that in to the EncryptionWorker as a buffer so we can use the same credentials across the system. Should we ever break the
  16. // collector out into its own service this would still work without SSL/TLS.
  17. /**
  18. *
  19. * @param {import("express").Request} request
  20. * @param {import("express").Response} response
  21. * @param {import("express").NextFunction} next
  22. */
  23. function setDataSigner(request, response, next) {
  24. const comKey = new CommunicationKey();
  25. const encryptedPayloadSigner = request.header("X-Payload-Signer");
  26. if (!encryptedPayloadSigner) console.log('Failed to find signed-payload to set encryption worker! Encryption calls will fail.');
  27. const decryptedPayloadSignerKey = comKey.decrypt(encryptedPayloadSigner);
  28. const encryptionWorker = new EncryptionWorker(decryptedPayloadSignerKey);
  29. response.locals.encryptionWorker = encryptionWorker;
  30. next();
  31. }
  32. module.exports = {
  33. setDataSigner
  34. }