AWS Rekognition Error - InvalidparameterException - node.js

const AWS = require('aws-sdk');
AWS.config.loadFromPath('./config.json');
const rekognition = new AWS.Rekognition({apiVersion: '2016-06-27'});
const constants = require('./constants');
const s3BucketName = constants.s3BucketName;
const s3BucketKeyName = constants.s3FacebookBucketKey;
const params = {
Image: {
S3Object: {
Bucket: "mastekinnoations3learning",
Name: "1527119837382460.jpeg"
}
}
};
rekognition.detectFaces(params, function(err, data) {
if (err)
console.log(err, err.stack); // an error occurred
else {
console.log(data); // successful response
}
});
I am trying to execute the above code which was running successfully last month but it has stopped running suddenly giving error "InvalidParameterException". Any help no what I am missing will be of great help!!
The image that I am using is this
https://s3-us-west-2.amazonaws.com/mastekinnoations3learning/1527119837382460.jpeg
Detailed Error:
{ InvalidParameterException: Request has Invalid Parameters
at Request.extractError (D:\Saurabh jain\Personal\nodejsprojects\ImageUpload\node_modules\aws-sdk\lib\protocol\json.js:48:27)
at Request.callListeners (D:\Saurabh jain\Personal\nodejsprojects\ImageUpload\node_modules\aws-sdk\lib\sequential_executor.js:106:20)
at Request.emit (D:\Saurabh jain\Personal\nodejsprojects\ImageUpload\node_modules\aws-sdk\lib\sequential_executor.js:77:10)
at Request.emit (D:\Saurabh jain\Personal\nodejsprojects\ImageUpload\node_modules\aws-sdk\lib\request.js:683:14)
at Request.transition (D:\Saurabh jain\Personal\nodejsprojects\ImageUpload\node_modules\aws-sdk\lib\request.js:22:10)
at AcceptorStateMachine.runTo (D:\Saurabh jain\Personal\nodejsprojects\ImageUpload\node_modules\aws-sdk\lib\state_machine.js:14:12)
at D:\Saurabh jain\Personal\nodejsprojects\ImageUpload\node_modules\aws-sdk\lib\state_machine.js:26:10
at Request.<anonymous> (D:\Saurabh jain\Personal\nodejsprojects\ImageUpload\node_modules\aws-sdk\lib\request.js:38:9)
at Request.<anonymous> (D:\Saurabh jain\Personal\nodejsprojects\ImageUpload\node_modules\aws-sdk\lib\request.js:685:12)
at Request.callListeners (D:\Saurabh jain\Personal\nodejsprojects\ImageUpload\node_modules\aws-sdk\lib\sequential_executor.js:116:18)

The issue was with the image. It seems its corrupt(still it opens perfectly in MSPaint). If I open the image in MSPaint and save it as JPEG and they try to pass it to AWS Rekognition , it works correctly. Hence I tried a different approach to download the image from facebook page and the application worked.
Thanks!!

In the config.json, there is something.
Try this out
AWS.config.update({region:'us-east-1',accessKeyId:'',secretAccessKey:''});
Let's change Bucket this.
const s3bucket = new AWS.S3({params: {Bucket: ''}}); //name Bucket you

Try this code. Required Attributes
const params = {
Image: {
S3Object: {
Bucket: "mastekinnoations3learning",
Name: "1527119837382460.jpeg"
}
},
Attributes:["ALL"]
};
Ref: AWS SDK for JavaScript - Class: AWS.Rekognition

Related

AWS Lambda Error: Validation Exception Value [] at 'names' failed to satisfy constraint: Member must have a length greater than or equal to 1

I have a lambda function which is triggered by an AWS SNS Topic. The function takes the information passed in from the SNS event and send's an email to a user using Nodemailer.
When I run my lambda function locally it works correctly. But once it's deployed I get the following error in my CloudWatch logs:
ValidationException: 1 validation error detected: Value '[]' at 'names' failed to satisfy constraint: Member must have length greater than or equal to 1.
at Request.extractError (/var/task/node_modules/aws-sdk/lib/protocol/json.js:52:27)
at Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
at Request.emit (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:78:10)
at Request.emit (/var/task/node_modules/aws-sdk/lib/request.js:688:14)
at Request.transition (/var/task/node_modules/aws-sdk/lib/request.js:22:10)
at AcceptorStateMachine.runTo (/var/task/node_modules/aws-sdk/lib/state_machine.js:14:12)
at /var/task/node_modules/aws-sdk/lib/state_machine.js:26:10
at Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:38:9)
at Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:690:12)
at Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:116:18) {
code: 'ValidationException',
time: 2021-10-01T18:02:30.538Z,
requestId: '023d6346-a49a-4dc6-a07f-92bd578a3601',
statusCode: 400,
retryable: false,
retryDelay: 94.04142545650443
}
This is the code for my lambda function:
const pug = require('pug');
const {newTransporter} = require('./handlers/emailTransporter');
exports.handler = async (event, context) => {
const message = event.Records[0].Sns.Message;
const mailAddressObj = {
'userEmail' : message.mail.commonHeaders.replyTo,
'clientEmail' : message.mail.commonHeaders.to[0],
}
const {userEmail, clientEmail} = mailAddressObj;
const html = pug.compileFile('./views/bounceNotificationEmail.pug');
const mailOptions = {
from: 'sendingEmail#email.com',
to: 'clientEmail,
subject: `Subject Header`,
html: html({
client_email: clientEmail
}),
};
try {
let transporter = await newTransporter();
let info = await transporter.sendMail(mailOptions);
console.log("Message sent: %s", info.messageId);
return info;
}
catch (e) {
console.log(e, 'error')
}
return console.log(mailAddressObj);
};
for starters in your example you don't close the quote after the "to" parameter :P
on a more serious note however, I reckon that when you run this locally, you wrote an JSON event that triggers your lambda manually and it doesn't have the same shape as the real life event produced by SNS. In your specific case, message that you initialize in the first line of your function is in fact a string, yet you use it as an object.
What you should have done is
const message = JSON.parse(event.Records[0].Sns.Message);

How to use MFA in Javascript aws-sdk?

I have an infrastructure where AWS login happens on a Role basis requires MFA from MS authenticator which pops up on Mobile device for Accept or Decline. Normally on CLI, we use saml2aws and it generates temporary access key secret key with assume role.
I am trying to use aws-sdk in my nodejs and trying to validate the credentials but not getting any popup and gets below error.
Please suggest the method or way to achieve this.
const AWS = require('aws-sdk');
var eks = new AWS.EKS({ accessKeyId: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", secretAccessKey : "gsdhjfkjbkbfvfkqbvfhvqhfvqhfv", region: "us-west-2"});
var params = { name: "testing" };
eks.describeCluster(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
After executing the above code: I am receiving the below error:
UnrecognizedClientException: The security token included in the request is invalid.
at Object.extractError (D:\Prashant\kubernetes-app\node_modules\aws-sdk\lib\protocol\json.js:52:27)
at Request.extractError (D:\Prashant\kubernetes-app\node_modules\aws-sdk\lib\protocol\rest_json.js:55:8)
at Request.callListeners (D:\Prashant\kubernetes-app\node_modules\aws-sdk\lib\sequential_executor.js:106:20)
at Request.emit (D:\Prashant\kubernetes-app\node_modules\aws-sdk\lib\sequential_executor.js:78:10)
at Request.emit (D:\Prashant\kubernetes-app\node_modules\aws-sdk\lib\request.js:688:14)
at Request.transition (D:\Prashant\kubernetes-app\node_modules\aws-sdk\lib\request.js:22:10)
at AcceptorStateMachine.runTo (D:\Prashant\kubernetes-app\node_modules\aws-sdk\lib\state_machine.js:14:12)
at D:\Prashant\kubernetes-app\node_modules\aws-sdk\lib\state_machine.js:26:10
at Request.<anonymous> (D:\Prashant\kubernetes-app\node_modules\aws-sdk\lib\request.js:38:9)
at Request.<anonymous> (D:\Prashant\kubernetes-app\node_modules\aws-sdk\lib\request.js:690:12) {
code: 'UnrecognizedClientException',
time: 2020-11-03T22:36:19.516Z,
requestId: '2e3486d0-3219-410c-8963-970958c5c14d',
statusCode: 403,
retryable: false,
retryDelay: 91.55836550904752
}
This request is completed. Was a bit tricky but done. Comment if anyone else facing the issue will let you know the solution.

Getting 403 forbidden when Uploading file to DO spaces using Node + Express

I am trying to upload file to DO s3 space using Node + Express.
But I am getting 403 forbidden issue.
Following is my uploading source code.
const aws = require('aws-sdk')
const multer = require('multer')
const multerS3 = require('multer-s3')
const space_ep = new aws.Endpoint('nyc3.digitaloceanspaces.com')
const s3 = new aws.S3({
endpoint: space_ep,
accessKeyId: 'my-access-key',
secretAccessKey: 'my-secret-access-key'
})
const uploader = multer({
storage: multerS3({
s3: s3,
bucket: 'my-bucket',
acl: 'public-read',
key: function(request, file, cb) {
console.log(file)
cb(null, file.originalname)
}
})
}).array('upload', 1)
export function upload(req, res, next) {
uploader(req, res, function(error) {
if (error) {
console.log(error)
return res.redirect('/error')
}
console.log('upload success')
response.redirect('/success')
})
}
...
let router = require('express').Router()
router.post('/upload', upload)
And when I try to upload, I am getting error in console as following
{ UserSuspended: null
at Request.extractError (path\node_modules\aws-sdk\lib\services\s3.js:831:35)
at Request.callListeners (path\node_modules\aws-sdk\lib\sequential_executor.js:106:20)
at Request.emit (path\node_modules\aws-sdk\lib\sequential_executor.js:78:10)
at Request.emit (path\node_modules\aws-sdk\lib\request.js:683:14)
at Request.transition (path\node_modules\aws-sdk\lib\request.js:22:10)
at AcceptorStateMachine.runTo (path\node_modules\aws-sdk\lib\state_machine.js:14:12)
at path\node_modules\aws-sdk\lib\state_machine.js:26:10
at Request.<anonymous> (path\node_modules\aws-sdk\lib\request.js:38:9)
at Request.<anonymous> (path\node_modules\aws-sdk\lib\request.js:685:12)
at Request.callListeners (path\node_modules\aws-sdk\lib\sequential_executor.js:116:18)
message: null,
code: 'UserSuspended',
region: null,
time: 2020-05-30T07:00:19.383Z,
requestId: 'tx000000000000011987442-005ed20482-21a2fa-nyc3b',
extendedRequestId: undefined,
cfId: undefined,
statusCode: 403,
retryable: false,
retryDelay: 17.163587715908,
storageErrors: [] }
How can I fix this issue?
What’s the reason?
Please help me.
Regards.
Your account must have been suspended or you have expired your subscription.
OK. I solved it.
My source code was not problem.
I contacted to DO support team, and they solved their issue and told me try again.
After that I success.

call and send data to an aws-lambda function using a node.js script

I have a lambda function running on amazon aws cloud. Now I want to make a node.js script to send data from my local system to aws lambda and use callback function to print the same value sent from my node.js code.
Now, to trigger my lambda function from my node.js code, I'm using the following code:
var AWS = require('aws-sdk');
// you shouldn't hardcode your keys in production! See http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html
AWS.config.update({accessKeyId: 'myaccessKeyId', secretAccessKey: 'mysecretAccessKey',region:'region',correctClockSkew: true});
var lambda = new AWS.Lambda({apiVersion: '2015-03-31'});
var params = {
FunctionName: 'myLambdaFunction', /* required */
Payload: 'true',
};
lambda.invoke(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
I am new to this lambda function concept, so can anyone help me by telling how to send data to the required lambda function from the above mentioned code? Using the above code I am able to trigger my lambda function and I am getting in my node app whatever I am printing in it's payload.
I am getting the following error, when I am using a custom string value ( other than 'true', 'false' or 'null') in payload and the api version which I am using is: apiVersion: '2015-03-31' , and the aws-sdk node module was recently installed, so I guess it's up-to-date.
Error message:
{ InvalidRequestContentException: Could not parse request body into json: Unrecognized token 'custom_data': was expecting ('true', 'false' or 'null')
at [Source: [B#7d2214ec; line: 1, column: 23]
at Object.extractError (/usr/lib/node_modules/aws-sdk/lib/protocol/json.js:43:27)
at Request.extractError (/usr/lib/node_modules/aws-sdk/lib/protocol/rest_json.js:37:8)
at Request.callListeners (/usr/lib/node_modules/aws-sdk/lib/sequential_executor.js:105:20)
at Request.emit (/usr/lib/node_modules/aws-sdk/lib/sequential_executor.js:77:10)
at Request.emit (/usr/lib/node_modules/aws-sdk/lib/request.js:668:14)
at Request.transition (/usr/lib/node_modules/aws-sdk/lib/request.js:22:10)
at AcceptorStateMachine.runTo (/usr/lib/node_modules/aws-sdk/lib/state_machine.js:14:12)
at /usr/lib/node_modules/aws-sdk/lib/state_machine.js:26:10
at Request.<anonymous> (/usr/lib/node_modules/aws-sdk/lib/request.js:38:9)
at Request.<anonymous> (/usr/lib/node_modules/aws-sdk/lib/request.js:670:12)
message: 'Could not parse request body into json: Unrecognized token \'custom_data\': was expecting (\'true\', \'false\' or \'null\')\n at [Source: [B#7d2214ec; line: 1, column: 23]',
code: 'InvalidRequestContentException',
time: 2017-01-16T16:48:38.514Z,
requestId: '3bee0e2c-dd39-11e6-9df3-5f7a24f73b9d',
statusCode: 400,
retryable: false,
retryDelay: 26.112914258191733 } 'InvalidRequestContentException: Could not parse request body into json: Unrecognized token \'custom_data\': was expecting (\'true\', \'false\' or \'null\')\n at [Source: [B#7d2214ec; line: 1, column: 23]\n at Object.extractError (/usr/lib/node_modules/aws-sdk/lib/protocol/json.js:43:27)\n at Request.extractError (/usr/lib/node_modules/aws-sdk/lib/protocol/rest_json.js:37:8)\n at Request.callListeners (/usr/lib/node_modules/aws-sdk/lib/sequential_executor.js:105:20)\n at Request.emit (/usr/lib/node_modules/aws-sdk/lib/sequential_executor.js:77:10)\n at Request.emit (/usr/lib/node_modules/aws-sdk/lib/request.js:668:14)\n at Request.transition (/usr/lib/node_modules/aws-sdk/lib/request.js:22:10)\n at AcceptorStateMachine.runTo (/usr/lib/node_modules/aws-sdk/lib/state_machine.js:14:12)\n at /usr/lib/node_modules/aws-sdk/lib/state_machine.js:26:10\n at Request.<anonymous> (/usr/lib/node_modules/aws-sdk/lib/request.js:38:9)\n at Request.<anonymous> (/usr/lib/node_modules/aws-sdk/lib/request.js:670:12)'
Kindly help.
To extend the the answer provided by Mark B, have the data that will be loaded into payload constructed as:
var data = {
key: value,
key: value,
key: value
}
var datapayload = JSON.stringify(data);
var datalambda= {
FunctionName: 'LambdaFunctionName',
InvocationType: 'RequestResponse',
Payload: datapayload,
LogType: 'None'
};
// create variable to hold data returned by the Lambda function
var returndata;
lambda.invoke(datalambda, function(error, data) {
if (error) {
console.log(error);
}
else {
returndata = JSON.parse(data.Payload);
var log = JSON.stringify(returndata);
console.log(log);
}
You are currently sending data to the Lambda function. The data you are sending is the string 'true'. You send data via the Payload property. From the documentation:
Payload — (Buffer, Typed Array, Blob, String)
JSON that you want to provide to your Lambda function as input.

AWS file upload with loopback: Failed to create a multipart upload on S3

Trying to upload multiple image files to AWS using loopback-component-storage
Here are the methods :
Game.add = function(ctx,options,cb)
{
var status = ctx.req.query.status,
defaultLangCode = ctx.req.query.defaultLangCode,
nameEn = ctx.req.query.nameEn;
var rec = new Object();
rec.parentHouseId = houseId;
rec.status = status;
rec.defaultLangCode = defaultLangCode;
rec.nameEn = nameEn;
if(!options) options = {forceIframeTransport : true};
ctx.req.params.container = 'common';
Game.app.models.container.upload(ctx.req,ctx.result,options,function (err,fileObj) {
if(err) {
cb(err);
} else {
var fileInfo = fileObj.files.file[0];
console.log(fileInfo);
}
});
};
AND
Game.remoteMethod(
'add',
{
http:{path: '/add', verb: 'post', status: 200, errorStatus: 400},
accepts: [
{ arg: 'ctx', type: 'object', http: { source:'context' } },
{ arg: 'options', type: 'object', http:{ source: 'query'} }
],
returns: {
arg: 'fileObject', type: 'object', root: true
}
}
);
I am trying to upload two image files there. Posting data/image produces this error twice:
Failed to create a multipart upload on S3: {"message":"Access
Denied","stack":"AccessDenied: Access Denied\n at
Request.extractError
(/vagrant/node_modules/aws-sdk/lib/services/s3.js:538:35)\n at
Request.callListeners
(/vagrant/node_modules/aws-sdk/lib/sequential_executor.js:105:20)\n
at Request.emit
(/vagrant/node_modules/aws-sdk/lib/sequential_executor.js:77:10)\n
at Request.emit
(/vagrant/node_modules/aws-sdk/lib/request.js:668:14)\n at
Request.transition
(/vagrant/node_modules/aws-sdk/lib/request.js:22:10)\n at
AcceptorStateMachine.runTo
(/vagrant/node_modules/aws-sdk/lib/state_machine.js:14:12)\n at
/vagrant/node_modules/aws-sdk/lib/state_machine.js:26:10\n at
Request.
(/vagrant/node_modules/aws-sdk/lib/request.js:38:9)\n at
Request.
(/vagrant/node_modules/aws-sdk/lib/request.js:670:12)\n at
Request.callListeners
(/vagrant/node_modules/aws-sdk/lib/sequential_executor.js:115:18)","code":"AccessDenied","region":null,"time":"2016-08-24T19:43:28.415Z","requestId":"2802978376D53185","extendedRequestId":"LhRlXP6H2EQo8M0ECUlL8js4W9CP99h5fvsSHjVSs3mhB9OupvWpz7UdB1HhN0Ntxf6sFLYoHdk=","statusCode":403,"retryable":false,"retryDelay":44.73750370088965}
Second one is of-course different.
I tried using empty options object without luck.
Any kind of advice is welcome. Thanks in advance.
Tried working with different key/key id , same result. And how do I get the uploaded file's url? That of-course after I can successfully upload images :p
Try enabling permission for the user in s3 bucket (permission)policy.
Have you assigned a role to instance where you are running the code? (If using EC2 as your workstation)
This should have been a comment. But, unfortunately i donot have privileges to comment.

Resources