Insufficient log-delivery permissions when using AWS-cdk and aws lambda

Viewed 871

I am trying to create a centralized logging bucket to then log all of other s3 buckets to using lambda and the aws-cdk. The centralized logging bucket has been created but there is an error when using lambda on it to write to it. Here is my code: import boto3

s3 = boto3.resource('s3')

def handler(event, context):
    setBucketPolicy(target_bucket='s3baselinestack-targetloggingbucketbab31bd5-b6y2hkvqz0of')

def setBucketPolicy(target_bucket):
    for bucket in s3.buckets.all():
        bucket_logging = s3.BucketLogging(bucket.name)
        if not bucket_logging.logging_enabled:
            reponse = bucket_logging.put(
                BucketLoggingStatus={
                    'LoggingEnabled': {
                        'TargetBucket': target_bucket,
                        'TargetPrefix': f'{bucket.name}/'
                    }
                },
            )
    print(reponse)



Here is my error:
START RequestId: 320e83c0-ba5e-4d54-a78c-a462d6e0cb87 Version: $LATEST
An error occurred (InvalidTargetBucketForLogging) when calling the PutBucketLogging operation: You must give the log-delivery group WRITE and READ_ACP permissions to the target bucket: ClientError
Traceback (most recent call last):

Note: Everything works but this log-delivery permission as when I enable it through the aws console it works fine but, I need to do it programmatically! Thank you in advance.

1 Answers

According to the documentation for S3 logging, you must grant the Log Delivery group WRITE and READ_ACP permissions on the target bucket for logs, and this is done using the S3 ACLs.

https://docs.aws.amazon.com/AmazonS3/latest/dev/enable-logging-programming.html#grant-log-delivery-permissions-general

When creating a new bucket with CDK, this is set using the accessControl property. The default value is BucketAccessControl.PRIVATE.

new s3.Bucket(this, 'bucket', {
  accessControl: s3.BucketAccessControl.LOG_DELIVERY_WRITE
})

Since CloudFormation has no way to add ACLs to existing buckets this means that CDK also has no such method. With an existing bucket, add Log Delivery via the web console, the API, or the CLI with aws s3api put-bucket-acl.

Other services, such as CloudFront, don't use ACLs anymore and use IAM policies which can be added using bucket.addToResourcePolicy().

https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.IBucket.html#add-wbr-to-wbr-resource-wbr-policypermission

Related