Reputation: 83
I created the below aws lambda function and set the trigger on all S3 upload events on my target bucket. The function attempt to reject file uploads greater than 2000000 bytes. The error message was logged, but neither context.fail('upload rejected') or context.fail(new Error('upload rejected')) did not prevent the fail upload. How to reject file upload, or in general, "reject/stop" an event with aws lambda?
//// nodejs aws lambda code: /////
exports.handler = (event, context, callback) => {
var MAX_FILE_SIZE = 2000000;
var msg = '';
console.log('Received event:', JSON.stringify(event, null, 2));
if (event.Records && event.Records.length && event.Records.length>0 && event.Records[0].s3 && event.Records[0].s3.object
&& event.Records[0].s3.object.size && event.Records[0].s3.object.size > MAX_FILE_SIZE) {
msg = 'File ' + event.Records[0].s3.object.key + ' rejected, file size ' + event.Records[0].s3.object.size
+ ' is greater than ' + MAX_FILE_SIZE + ' bytes.';
console.log(msg);
var err = new Error(msg);
callback(err, {'disposition':'STOP_RULE'});
context.fail(err);
} else {
msg = 'Upload succeeded.';
console.log(msg);
callback(null, msg);
context.succeed(msg);
}
};
Upvotes: 1
Views: 846
Reputation: 11718
You can't do that if your lambda is triggered by s3 notification, simply because in that case it is not controlling the file upload in any way. It is simply called to do some processing based on file upload. If you want to control the file upload then your uploading should happen via the lambda function
What you can actually do in your current situation is that you can delete the file if you see that the size is greater than your required limit, but you cannot prevent the file from getting upload
Upvotes: 1