Search code examples
ruby-on-railsrubyamazon-s3fine-uploader

Error on S3 Policy with FineUploader in Rails


I have been trying to implement direct upload to S3 using the FineUploader JS library. I have a post action in Rails that builds and returns a S3 policy and signature, I have tried many different options but I keep getting an error with the policy in FineUploader.

Here is the FineUploader JS I am using:

  <script>
    $('#fine-uploader-s3').fineUploaderS3({
        template: 'qq-template-s3',
        request: {
            endpoint: "https://mybucket.s3.amazonaws.com/",
            accessKey: MY_ACCESS_KEY
        },
        signature: {
            endpoint: "/generatesignature"
        },
       uploadSuccess: {
            endpoint: "/success",
            params: {
                isBrowserPreviewCapable: qq.supportedFeatures.imagePreviews
            }
        },
        iframeSupport: {
            localBlankPagePath: "/server/success.html"
        },
        cors: {
            expected: true
        },
        chunking: {
            enabled: true
        },
        resume: {
            enabled: true
        },
        deleteFile: {
            enabled: true,
            method: "POST",
            endpoint: "http://s3-demo.fineuploader.com/s3demo-thumbnails-cors.php"
        },
        validation: {
            itemLimit: 5,
            sizeLimit: 15000000
        },
        thumbnails: {
            placeholders: {
                notAvailablePath: "/plugins/fineuploader/placeholders/not_available-generic.png",
                waitingPath: "/plugins/fineuploader/placeholders/waiting-generic.png"
            }
        },
        callbacks: {
            onComplete: function(id, name, response) {
                var previewLink = qq(this.getItemByFileId(id)).getByClass('preview-link')[0];

                if (response.success) {
                    previewLink.setAttribute("href", response.tempLink)
                }
            }
        }
    });
</script>

Here is the generatesignature action serverside in Ruby

  def generatesignature
  bucket = MY_BUCKET
  access_key = MY_ACCESS_KEY
  secret = MY_SECRET_KEY
  key = "test.txt/"
  expiration = 5.minutes.from_now.utc.strftime('%Y-%m-%dT%H:%M:%S.000Z')
  max_filesize = 2.megabytes
  acl = 'public-read'
  sas = '200' # Tells amazon to redirect after success instead of returning xml
  policy = Base64.encode64(
    "{'expiration': '#{expiration}',
      'conditions': [
        {'bucket': '#{bucket}'},
        {'acl': '#{acl}'},
        {'Cache-Control': 'max-age=31536000'},
        ['starts-with', '$key', '#{key}'],
        ['content-length-range', 1, #{max_filesize}]
      ]}
    ").gsub(/\n|\r/, '')
  signature = Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha1'), secret, policy)).gsub(/\n| |\r/, '')
  {:access_key => access_key, :key => key, :policy => policy, :signature => signature, :sas => sas, :bucket => bucket, :acl => acl, :expiration => expiration}

params[:signature]= signature
params[:policy] = policy
render :json => params, :status => 200 and return
end

The error that I am receiving when trying to upload to S3 is: "Invalid according to Policy: Policy Condition failed: ["eq", "$acl", "public-read"]"


Solution

  • It appears as if you are generating a signature using an ACL value of "public-read", but the policy sent to S3 by Fine Uploader, by default, uses an ACL of "private". If you really want to use a "public-read" ACL, you will need to update the objectProperties.acl Fine Uploader S3 configuration value. For example:

    $('#fine-uploader-s3').fineUploaderS3({
      objectProperties: {
        acl: 'public-read'
      },
      ...
    })