简体   繁体   中英

Error in signer.addAuthorization(credentials, new Date()) while signing opensearch request in Nodejs Lambda

I'm uploading document to AWS Openseach using AWS Lambda.

Here's my code, I'm first getting credentials from AWS using EnvironmentCredentials and then passing it to AWS.Signers.V4().addAuthorization() method

const AWS = require('aws-sdk');
var path = require('path');

const esDomain = {
  endpoint: 'https://search-ddbsearch-xxxxxxx.us-east-2.es.amazonaws.com',
  region: process.env.LAMBDA_REAGION,
  index: 'type',
  doctype: '_doc'
};

async function saveInOs(doc) {
  const endpoint =  new AWS.Endpoint(esDomain.endpoint);
  let req = new AWS.HttpRequest(endpoint);

  req.method = 'POST';
  req.path = path.join('/', esDomain.index, esDomain.doctype);
  req.region = esDomain.region;
  req.body = doc;
  req.headers['presigned-expires'] = false;
  req.headers['Content-Type'] = 'application/json';
  req.headers['Host'] = endpoint.host;

  const credentials = new AWS.EnvironmentCredentials('AWS');

  let signer = new AWS.Signers.V4(req, 'es');
  signer.addAuthorization(credentials, new Date());

  let send = new AWS.NodeHttpClient();
  send.handleRequest(req, null, function(httpResp) {
      let body = '';
      httpResp.on('data', function (chunk) {
        body += chunk;
      });
      httpResp.on('end', function (chunk) {
        return {
          message: "Document saved"
        }
      });
  }, function(err) {
      return {
        message: err.message
      };
  });
}

module.exports ={
  saveInOs
}

And I'm getting the following error (in line 26)

TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of ArrayBuffer, Buffer, TypedArray, DataView, KeyObject, or CryptoKey. Received undefined
      at new NodeError (node:internal/errors:372:5)
      at prepareSecretKey (node:internal/crypto/keys:580:11)
      at new Hmac (node:internal/crypto/hash:132:9)
      at Object.createHmac (node:crypto:162:10)
      at Object.hmac (/var/runtime/node_modules/aws-sdk/lib/util.js:428:30)
      at Object.getSigningKey (/var/runtime/node_modules/aws-sdk/lib/signers/v4_credentials.js:62:8)
      at V4.signature (/var/runtime/node_modules/aws-sdk/lib/signers/v4.js:98:36)
      at V4.authorization (/var/runtime/node_modules/aws-sdk/lib/signers/v4.js:93:36)
      at V4.addAuthorization (/var/runtime/node_modules/aws-sdk/lib/signers/v4.js:35:12)
      at saveInOs (/var/task/saveInOs.js:26:10) {
    code: 'ERR_INVALID_ARG_TYPE'
  }
}

Anything I'm missing here?

I took reference from this repo: https://github.com/aws-samples/amazon-elasticsearch-lambda-samples

You should use [AWS.util.date.getDate()] instead of new Date() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM