Issue
I've an images/:key route with this controller:
public getImage(request: Request, response: Response): Response {
try {
const key = request.params.key;
const read = getFileStream(key);
return read.pipe(response);
} catch (error) {
return response.status(404).json({
message: 'Image not found.'
});
}
}
And the following function:
// aws.ts
export function getFileStream(fileKey: any) {
const downloadParams = {
Key: fileKey,
Bucket: bucketName
};
return s3.getObject(downloadParams).createReadStream();
}
So, the problem is when I get an unexpected key that doesn't exist in the S3 bucket because the try/catch doesn't work and then my app crash with an error code that say 'Access denied', How can i fix that?. A lot of thanks 😁
Solution
I had to validate first of the key refers to a valid object, so i get the object data before get the object and if it doesn't exist it throws an error who i'm able to catch, like this:
// aws.ts
export async function getFileStream(key: string) {
const downloadParams = {
Key: key,
Bucket: bucketName
};
try {
// Verify if exists
const head = await s3.headObject(downloadParams).promise();
// Return object
return s3.getObject(downloadParams).createReadStream();
} catch (headErr: any) {
// If get an error returns null
return null;
}
}
And then in the controller:
public async getFile(request: Request, response: Response) {
const key = request.params.key;
const read = await getFileStream(key);
if (read != null) return read.pipe(response);
else return response.sendStatus(404);
}
Yo have to put in the s3 policy the list bucket option, it's required for be able to use headObject(), this is an example of the policy required:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:DeleteObject",
// The following actions are required
"s3:GetObject",
"s3:ListBucket",
],
"Resource": [
"arn:aws:s3:::YOUR-BUCKET-NAME-HERE",
"arn:aws:s3:::YOUR-BUCKET-NAME-HERE/*"
]
}
]
}
Answered By - JuanDa237
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.