Извлеките KMS-зашифрованный ZIP-файл из AWS S3

Я хочу использовать лямбда-функцию для извлечения конкретного файла ZIP из AWS S3, расшифровки и извлечения.

Вот код, который у меня есть:

const AWS = require('aws-sdk');
const zlib = require('zlib');
const fs = require('fs');
const stream = require('stream');

exports.handler = function (event, context) {
  const jobInfo = event['CodePipeline.job'].data;
  const artifactsInfo = jobInfo.inputArtifacts[0].location;
  const bucket = artifactsInfo.s3Location.bucketName;
  const key = artifactsInfo.s3Location.objectKey;

  const credentials = jobInfo.artifactCredentials;
  const s3 = new AWS.S3({
    credentials: credentials,
  });
  const kms = new AWS.KMS({
    credentials: credentials,
    region: 'eu-central-1',
  });

  s3.getObject({
    Bucket: bucket,
    Key: key,
  }, function(err, data) {
    if (err) {
      // context.done(err);
      console.error(err);
      return;
    }

    console.log('Received file', key);

    const buff = new stream.PassThrough();

    kms.decrypt({CiphertextBlob: data.Body}, function(err, decryptData) {
      if (err) {
        console.error(err);
        return;
      }

      buff.end(decryptData.Plaintext);

      console.log('Decoded S3 object encrypted with KMS ID', decryptData.KeyId);

      buff
      .pipe(zlib.createGunzip())
      .on('error', console.error)
      .on('entry', function(entry) {
        console.log(entry);
      });
    });

  });
};

Тем не менее, ZIP-файл похож на 5MiB и я получаю следующую ошибку из запроса KMS:

ValidationException: 1 validation error detected: Value 'java.nio.HeapByteBuffer[pos=0 lim=128011 cap=128011]' at 'ciphertextBlob' failed to satisfy constraint: Member must have length less than or equal to 6144
    at Request.extractError (/home/victor/dev/s3-zip-extract/node_modules/aws-sdk/lib/protocol/json.js:48:27)
    at Request.callListeners (/home/victor/dev/s3-zip-extract/node_modules/aws-sdk/lib/sequential_executor.js:105:20)
    at Request.emit (/home/victor/dev/s3-zip-extract/node_modules/aws-sdk/lib/sequential_executor.js:77:10)
    at Request.emit (/home/victor/dev/s3-zip-extract/node_modules/aws-sdk/lib/request.js:683:14)
    at Request.transition (/home/victor/dev/s3-zip-extract/node_modules/aws-sdk/lib/request.js:22:10)
    at AcceptorStateMachine.runTo (/home/victor/dev/s3-zip-extract/node_modules/aws-sdk/lib/state_machine.js:14:12)
    at /home/victor/dev/s3-zip-extract/node_modules/aws-sdk/lib/state_machine.js:26:10
    at Request.<anonymous> (/home/victor/dev/s3-zip-extract/node_modules/aws-sdk/lib/request.js:38:9)
    at Request.<anonymous> (/home/victor/dev/s3-zip-extract/node_modules/aws-sdk/lib/request.js:685:12)
    at Request.callListeners (/home/victor/dev/s3-zip-extract/node_modules/aws-sdk/lib/sequential_executor.js:115:18)
  message: '1 validation error detected: Value \'java.nio.HeapByteBuffer[pos=0 lim=128011 cap=128011]\' at \'ciphertextBlob\' failed to satisfy constraint: Member must have length less than or equal to 6144'

Как я мог справиться с этим? Спасибо!

1 ответ

Решение

После более глубокого погружения в документацию я обнаружил, что мне не нужно было самому дешифровать объект, так как он был открытым текстом для клиента. Я удалил шаг расшифровки и попал в точку, где мой код выглядел так:

buff.end(data.Body);
buff
  .pipe(zlib.createGunzip())
  .on('error', console.error)
  .on('entry', function(entry) {
    console.log(entry);
  });

Примечание (я констатирую это, отмечая это, потому что мне потребовалось некоторое время, чтобы понять это). Amazon экспортирует свою .zip файлы в PKZIP формат, который zlib не может работать с

Другие вопросы по тегам