AWS s3 create pre signed post does not work on deploy - amazon-s3

I am creating presigned url using aws-sdk’s nodejs/createPresignedPost method. Its all working via serverless-offline plugin on my local, cause my personal accesskey has all accesses. But when I deploy it via serverless framework it errors out with HTTP 403 and the error in browser reads as follows
The AWS Access Key Id you provided does not exist in our records.
The key starts with ASIA ASIAQDGRI5OSPEXMAPLE
I have granted all action permission to my lambda on target bucket.
My Api gateway and lambdas that return the signed url are in ‘us-east-1’ region and the bucket is in ‘ap-south-1’ region.
I am sure I am missing some IAM permissions but I can not figure it our. Can some one help me here?
Here is my function that returns a promise on getting pre signed post url
function getSignedUploadUrl() {
const params = {
Expires: 600,
Bucket: process.env.AWS_S3_BUCKET_NAME,
Fields: {
key: s3FilePathKey,
acl: acl,
"content-type": contentType,
},
conditions: [
{ acl: acl },
{ "content-type": contentType },
["content-length-range", 1000000, 75000000],
],
};
return new Promise((resolve, reject) => {
const s3 = new S3({
region: AWS_REGION
});
s3.createPresignedPost(params, (err, data) => {
if (err) {
console.log(err);
reject({
message: "Something went wrong",
});
}
resolve(data);
});
});
}

The fields to include in the formdata varies based on where the code is run, at least that was the case in my problem. In Elastic Beanstalk environment, there was an additional x-amz-security-token field (alongside the AWSAccessKeyId, key etc), which was not present in the fields returned by Boto3 create_presigned_post while run on local env.

Related

AWS Upload Fails on 2nd and next few tries to s3 with s3.upload function

I am using the following code to upload multiple images to s3 bucket using AWS API gateway.
And a strange issue is happening that when I upload image for the first time it uploads fine but when I try to upload again it fails the upload to s3 bucket.
After some time when I try again it works and again fails.
const s3Client = new AWS.S3({
credentials: {
accessKeyId: process.env.AWS_S3_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_S3_SECRET_ACCESS_KEY,
region: ''
},
});
And when it fails it does not print any logs which are after s3Client.upload() function call. Not sure How to debug this? I have tried to add progress check but it never goes into that check when upload fails.
Maybe its upload frequency limit on s3? I didn't find any such limit on aws docs though.
if (contentType && contentType.includes('multipart/form-data;')) {
const result = await parser.parse(event);
body = await schema.parseAsync(JSON.parse(result.JsonData))
console.log('DEBUG>>>>> HandlerTS File: JSON.parse(result.JsonData): ', body)
console.log('DEBUG>>>>> HandlerTS File: Result: ', result)
if (result.files) {
result.files.forEach(f => {
console.log("DEBUG>>>>> Uploading file")
console.log(f)
s3Client.upload(
{
Bucket: bucket,
Key: `${body.name}/${f.filename}`,
Body: f.content,
},
(err, data) => {
console.log(err, data);
},
).on("httpUploadProgress", (progress) => {
const uploaded = Math.round(progress.loaded / progress.total * 100);
console.log('DEBUG>>>>>>>>>> checking http upload progress ', uploaded)
}).send(function (err, data) {
if (err) {
// an error occurred, handle the error
console.log('DEBUG>>>>>>>>>>>>>> Error Upload')
console.log(err, err.stack);
return;
}
const fileUrl = data.Location;
console.log('DEBUG>>>>>>>>>>>>>> File URL:', fileUrl);
});
})
}
P.s: I am using API gateway and lambda functions.

cesium Ion REST API upload to S3 access denied

I’m using the cesium ion rest api to upload las file to cesium. It's a 3 part process. First you have to make a call to create the asset in ion, then it respond with the upload location access infos.
Then you have to use those infos to upload the file to S3.
My problem is that I get AccessDenied: Access Denied
at S3ServiceException.ServiceException [as constructor]
If I use my own bucket, with my own credential, it’s working, but that’s not what I want for now.
When I console log uploadLocation, I have an accessKey, a sessionToken etc.
Every thing is in order, that’s why I don’t understand why I get an AccessDenied.
What am I missing ? Thanks for the help.
const S3ClientCred = {
accessKeyId: uploadLocation.accessKey,
secretAccessKey: uploadLocation.secretAccessKey,
sessionToken: uploadLocation.sessionToken
}
const params = {
Bucket: uploadLocation.bucket,
Prefix: uploadLocation.prefix,
Key: selectedFile.name,
Body: selectedFile
};
try {
const parallelUploads3 = new Upload({
client: new S3Client({apiVersion: '2006-03-01', region: 'us-east-1',signatureVersion: 'v4',endpoint: uploadLocation.endpoint, credentials: S3ClientCred}),
params: params,
});
parallelUploads3.on("httpUploadProgress", (progress) => {
console.log(progress);
});
await parallelUploads3.done();
console.log('parallelUploads3.done()');
} catch (e) {
console.log(e);
}

Meteor how to upload image via rest api to aws s3?

I am working on api to upload images on aws s3. First i need to save images to aws and then need to save url to mongo database.But when i am trying to upload image getting this error. I am using lepozepo:s3 library on clinet side and want to use same at server side. Code that i had mentioned below is with lepozepo library. http://prntscr.com/ohareb
Meteor.call('uploadProfilePic', this.request.body, function (error, resp) {
if (error) {
response = {
"errorCode": true,
"statusMessage": error.message,
}
}else{
response = {
"errorCode": false,
"statusMessage": "Picture uploaded successfully",
}
}
});
this.response.setHeader('Content-Type', 'application/json');
this.response.end(JSON.stringify(response));
});
and in methods i have created this method.
uploadProfilePic:function(image){
var files = image;
userId = "MMKKK79KQ7eMs6777Hh";
import {S3} from "meteor/lepozepo:s3";
console.log(files);
S3.uploadFile({
files:files,
path:"avatars"
},function(e,r){
if (!e) {
var $set={};
$set[templ.data.picType]=r.secure_url;
Meteor.users.update({
_id: userId
}, {
$set: $set
}, function(err) {
if (!err) {
console.log( "Image uploaded");
} else {
console.log("Error updating image");
}
});
} else {
console.log( "Error updating image");
}
});
}
I maintain this package: https://github.com/activitree/s3up-meta.
With it you can upload and delete files to/from S3. You can also set metadata for cacheing and expire which you can anyway overwrite from your Cloudfront CDN (in case you distribute your images via Cloudfront).
The package is based on the AWS sdk and all requests are signed by the Meteor server, however, files are moved from client straight to S3.
Open a question on the Git if you need.
Cheers

Saving base64 string to Amazon S3

I'm working on a React Native application where I'm trying to take images from a user's camera roll, convert them to a base64 string and store them to Amazon S3 for later use.
Following this blog post I'm able to take a user's camera roll and convert the images to base64:
react-native-creating-a-custom-module-to-upload-camera-roll-images
I'm then sending the base64 string image data to a simple Express server I have set up to post the data to my Amazon S3 bucket.
// Only getting first img in camera roll for testing purposes
CameraRoll.getPhotos({first: 1}).then((data) => {
for (let i = 0; i < data.edges.length; i++) {
NativeModules.ReadImageData.readImage(data.edges[i].node.image.uri, (imageBase64) => {
// Does the string have to be encoded?
// const encodeBase64data = encodeURIComponent(imageBase64);
const obj = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'img': imageBase64
})
}
fetch('http://localhost:3000/saveImg', obj)
.then((res) => {
console.log(JSON.parse(res._bodyInit));
})
})
}
My imageBase64 variable in this instance is a pretty large string reading like: /9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAA...abX+Yub/API3zf8A7G2Z/wDqdiD/AExyf/kT5R/2Kst/9QqB0x6H6GuBbr1R6D2foz+ZT/gof/yep8bf934f/wDqC6PX96+Cn/JruFf+6z/6t8UfwP4wf8nM4n9Mq/8AVbRPjOv1I/OAoA//2Q==
With the ... being several more characters.
I'm sending this base64 string to my express server and posting the data:
app.post('/saveImg', function(req, res) {
// this will be moved once testing is complete
var s3Bucket = new AWS.S3( { params: {Bucket: '[my_bucket_name]'} } );
// Do I need to append this string to the image?
var baseImg = 'data:image/png;base64,' + req.body.img;
var data = {
Key: test_img,
Body: req.body.img,
ContentEncoding: 'base64',
ContentType: 'image/png'
};
s3Bucket.putObject(data, function(err, data){
if (err) {
console.log(err);
console.log('Error uploading data: ', data);
} else {
res.send(data);
console.log('successfully uploaded the image!');
}
});
// res.send(base64data)
});
I successfully send the data to Amazon S3 and see my image file in the bucket however when I try to visit the link to see the actual image itself, or pull it into my React Native app, I get nothing.
ie If I visit the url to test_img above after it's in Amazon S3 I get:
https://s3.amazonaws.com/my_bucket_name/test_img
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>BCE6E07705CF61B0</RequestId>
<HostId>
aF2l+ucPPHRog1QaaXjEahZePF0A9ixKR0OTzlogWFHYXHUMUeOf2uP7D/wtn7hu3bLWG8ulKO0=
</HostId>
</Error>
I've uploaded images manually to this same bucket and their links appear fine, and I'm additionally able to pull them into my React Native application with no problem for viewing.
My question is what am I doing wrong between getting the base64 string data and sending it to my Express server for saving to my bucket?
Does the base64 string have to be encoded?
Do I need to convert the base64 string to a Blob before sending it to Express?
Thanks for the help!
I just ran into the same issue. You have to convert the base64 string to a Blob before uploading to S3.
This answer explains how to do this conversion. Using node-fetch, Here's how to integrate in your example :
require('node-fetch')
app.post('/saveImg', function(req, res) {
// this will be moved once testing is complete
var s3Bucket = new AWS.S3( { params: {Bucket: '[my_bucket_name]'} } );
var imageUri = 'data:image/png;base64,' + req.body.img;
fetch(imageUri)
.then(function(res){ return res.blob() })
.then(function(image){
var data = {
Key: test_img,
Body: image,
ContentEncoding: 'base64',
ContentType: 'image/png'
};
s3Bucket.putObject(data, function(err, data){
if (err) {
console.log(err);
console.log('Error uploading data: ', data);
} else {
res.send(data);
console.log('successfully uploaded the image!');
}
});
})
});
Once that's done, you may then preview the uploaded image on S3 or pull it into your app.
It's a permission thing and has nothing to do with ReactNative nor Base64-enconding.
You've got an "AccessDenied"-Error, that means that the image isn't publicly available. Only if you configure your bucket with the right permissions (or even the specific file, i'll explain below), you will receive the content of an image without having signed-urls.
To investigate if this is the root cause you can try to make an image public in the s3-console. Just go to your s3-bucket and have a right-mouse-click on an image-file:
In the context-menu are two interesting items listed for you: "make public", and "open".
If you choose "open", you'll get a "signed url" to the file, which means that the plain url to the image will be appened with specific parameters to make this file public available for a while:
Also you can try out "make public" and reload your image-url again to see if it will be available now for you.
1. Approach, bucket-wide:
One solution is to create an IAM-Policy for the whole bucket to make every object in it public:
{
"Version": "2008-10-17",
"Statement": [{
"Sid": "AllowPublicRead",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": [ "s3:GetObject" ],
"Resource": [ "arn:aws:s3:::YOUR_BUCKET_NAME/*" ]
}]
}
So go to your bucket in AWS console, click on the bucket, and on the right pane open up "permissions". You can create a new policy like the one above.
2. Second solution, object-specific
Another approach would be to add ACL-specific headers to the putObject-Method:
'ACL' => 'public-read'
I don't know your backend-sdk, but i'll guess something like this:
var data = {
Key: test_img,
Body: req.body.img,
ContentEncoding: 'base64',
ContentType: 'image/png',
ACL: 'public-read',
};
I just added the ACL-specific line here.
Depending of the SDK it could be necessary to use the plain aws-headers "x-amz-acl: public-read" instead of "ACL:public-read". Just try both.
Adding Bucket policy to your bucket will resolve the issue.

Loopback component storage aws s3 ACL Permissions

I'm working on this project and I've managed to upload an image through an end-point I created on my loopback model, the problem is I need the uploaded image to be publicly accessible and can't seem to find where to do that.
I've tried using the aws sdk to change the object permissions with putObjectACL but couldn't make it work, it said that I have build incorrectly the xml, since I can't even figure how to fill the properties that the method requires, so I found a way to change it and is to copy it and set the ACL to 'public-read' and then delete the original, then copying it again to it's original filename and delete again the other copy, seems like a pretty naughty solution, and I'm pretty sure there must be a more neat way to do it.
I do the upload with my remote method like this:
Container.upload(req,res,{container: "my-s3-bucket"},function(err,uploadInfo) { ... }
Container is my model connected to aws s3. And then I do the permission change like this (copying and deleting):
var AWS = require('aws-sdk');
AWS.config.update({accessKeyId:"my-key-id",secretAccessKey:"my-key", region:"us-east-1"});
var s3 = new AWS.S3();
s3.copyObject( {
Bucket:'my-s3-bucket',
CopySource: 'my-s3-bucket/'+filename,
Key: filename+"1",
ACL: 'public-read'
}, function(err,info) {
if (err) return cb(err);
s3.deleteObject( {
Bucket:'my-s3-bucket',
Key:filename
}, function(err,info) {
if (err) return cb(err);
s3.copyObject( {
Bucket: 'my-s3-bucket',
CopySource: 'my-s3-bucket/'+filename+"1",
Key: filename,
ACL: 'public-read'
}, function(err,info) {
if (err) return cb(err);
s3.deleteObject( {
Bucket: 'my-s3-bucket',
Key: my-s3-bucket+"1"
}, function(err,info) {
if (err) return cb(err);
cb(null,uploadInfo);
})
})
})
});
I wonder if there is something more clean like this:
Container.upload(req,res,{container: "my-s3-bucket", ACL:'public-read'},function(err,uploadInfo) { ... }
Thanks in advance :)
Sorry this comes a little late but the answer is in here:
https://github.com/strongloop/loopback-component-storage/pull/47
They added support for applying acls and some other stuff:
var dsImage = loopback.createDataSource({
connector: require('loopback-component-storage'),
provider: 'filesystem',
root: path.join(__dirname, 'images'),
getFilename: function(fileInfo) {
return 'image-' + fileInfo.name;
},
acl: 'public-read',
allowedContentTypes: ['image/png', 'image/jpeg'],
maxFileSize: 5 * 1024 * 1024
});
Putting that acl to 'public-read', does the trick.
So in the end I had to discard the whole loopback component storage, and since I also needed to get some extra params aside from the file, I parsed the form with formidable and upload the file directly with the aws sdk, like this:
var formidable = require('formidable');
var form = new formidable.IncomingForm();
form.parse(req, function(err,fields,files) {
if (err) return cb(err);
var fs = require('fs');
var AWS = require('aws-sdk');
AWS.config.update({
accessKeyId:"my-key-id",
secretAccessKey:"my-key",
region:"us-east-1"
});
var s3 = new AWS.S3();
s3.putObject({
Bucket:'shopika',
Key: files.file.name,
ACL:'public-read', //Public plz T^T
Body: fs.createReadStream(files.file.path),
ContentType:files.file.type
}, function(err,data) {
if (err) return cb(err);
//Upload success, now I have the params I wanted in 'fields' and do my stuff with them :P
cb(null,data);
});
});