Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Amazon IAM policy for s3 using Rails and Paperclip

What should my IAM policy look like in order to allow user my-user to access an Amazon S3 bucket called my-bucket?

Currently, I have the following policy assigned to my-user:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:ListBucket"],
      "Resource": ["arn:aws:s3:::my-bucket"]
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:PutObject",
        "s3:GetObject",
        "s3:DeleteObject"
      ],
      "Resource": ["arn:aws:s3:::my-bucket/*"]
    }
  ]
}

I got this policy from "Sample 1" on the following link:

http://blogs.aws.amazon.com/security/post/Tx3VRSWZ6B3SHAV/Writing-IAM-Policies-How-to-grant-access-to-an-Amazon-S3-bucket

In my production.rb file, I have implemented the configuration settings to tell paperclip to use S3:

config.paperclip_defaults = {
  :storage => :s3,
  :s3_credentials => {
    :bucket => 'my-bucket',
    :access_key_id => ENV['AWS_ACCESS_KEY_ID'],
    :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
  }
}

When I attempt to use my app to upload a photo, I receive an AWS::S3::Errors::AccessDenied exception.

Oddly, if I load up the rails console, and run the following code to manually upload a file, it works correctly:

s3 = AWS::S3.new(access_key_id: ENV['AWS_ACCESS_KEY_ID'], secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'])
bucket = s3.buckets['my-bucket']
obj = bucket.objects['new_file']
obj.write(Pathname.new('/path/to/file'))

This correctly uploads the file to my S3 bucket. I'm confused why I clearly have permission to upload a file this way, but when I try to do it via paperclip with the same credentials, I get the permission denied error.

Even more confusing, when I assign the AdministratorAccess policy to my-user, paperclip is able to successfully upload the file.

Any idea how I can resolve this?

like image 596
flyingL123 Avatar asked Feb 10 '16 21:02

flyingL123


1 Answers

The solution is here: https://stackoverflow.com/a/19185045/736864

When paperclip uploads the file to S3, it also tries to set the file to be publicly viewable, which means the user needs to be given access to set permissions. Adding the s3:PutObjectAcl permission to my IAM policy fixed the issue.

like image 90
flyingL123 Avatar answered Oct 20 '22 05:10

flyingL123