0

I'm trying to upload a file to a S3 bucket. First I create an AmazonS3 client using InstanceProfileCredentialsProvider and I get IAM credentials from the instance metadata:

final AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
    .withCredentials(new InstanceProfileCredentialsProvider(false))
    .withRegion("eu-west-1").build();

The role associated to this instance has a policy to access and upload files to a bucket:

{  
    "Version":"2012-10-17",
       "Statement":{  
  "Action":[  
     "kms:Decrypt",
     "kms:DescribeKey",
     "kms:Encrypt",
     "kms:GenerateDataKey",
     "kms:ReEncryptFrom",
     "kms:ReEncryptTo",
     "s3:GetObject",
     "s3:ListBucket",
     "s3:PutObject*"
  ],
          "Effect":"Allow",
          "Resource":[  
          "arn:aws:kms:eu-west-1:[account-id]:key/[key-id]",
          "arn:aws:s3:::[bucket-name]",
          "arn:aws:s3:::[bucket-name]/[path-were-to-save-file]/*" 

  ]}}

I'm trying to upload the file like this:

final PutObjectRequest request = new PutObjectRequest("[bucket-name]", file.getName(), file);

s3Client.putObject(request);

but I get Access Denied AmazonS3ClientException. Any idea what I am missing?

I also tried to include the kms key to the request:

final PutObjectRequest request = new PutObjectRequest("[bucket-name]", file.getName(), file)
                .withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams("[key-id]"));

but it tries to retrieve the key from my account:

arn:aws:kms:eu-west-1:[my-account-id]:key/[key-id]

not the account specified in the policy:

arn:aws:kms:eu-west-1:[account-id]:key/[key-id]

and throws KMSNotFoundException

Jones
  • 1,036
  • 5
  • 20
  • 37

1 Answers1

1

It seems that I have to specify the full path were I want the file to be saved and I can discard the key:

final PutObjectRequest request = new PutObjectRequest("[bucket-name]", "[path-were-to-save-file]/" + file.getName(), file);

If passing the key is necessary the full arn needs to be supplied not only the key id:

final PutObjectRequest request = new PutObjectRequest("[bucket-name]", file.getName(), file)
    .withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams("arn:aws:kms:eu-west-1:[account-id]:key/[key-id]"));
Jones
  • 1,036
  • 5
  • 20
  • 37