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);
}
};
You can't do that if your lambda is triggered by an s3 notification, simply because in that case you don't control the file upload in any way. It is simply called to do some processing based on the file upload. If you want to control the upload of the file, your upload should be done through the lambda function
What you can actually do in your current situation is that you can delete the file if you see the size is larger than the required limit, but you can't prevent the file from uploading.