
/////////////////////////////////
// CENTRAL CLOUDTRAIL S3 BUCKET
/////////////////////////////////
resource aws_s3_bucket nfcisbenchmark_cloudtrail {
  bucket        = "${local.bucket_prefix}-cloudtrail"
  acl           = "private"
  force_destroy = true
  # 3.6 Ensure S3 bucket access logging is enabled on the CloudTrail S3 bucket (Automated)
  logging {
    target_bucket = aws_s3_bucket.log_bucket_cloudtrail.id
    target_prefix = "log/"
  }

  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        kms_master_key_id = aws_kms_key.nfcisbenchmark.arn
        sse_algorithm     = "aws:kms"
      }
    }
  }

  // Tags
  tags = local.cost_tags
}

resource aws_kms_key nfcisbenchmark {
  description         = "kms key used for encrypting log files at rest"
  enable_key_rotation = true
  policy              = data.aws_iam_policy_document.cmk.json

  // Tags
  tags = local.cost_tags
}

resource "aws_s3_bucket_notification" "cloudtrail" {

  bucket = aws_s3_bucket.nfcisbenchmark_cloudtrail.bucket

  queue {
    queue_arn   = data.terraform_remote_state.security.outputs.cloudtrail_bucket_notifications_sqs_arn
    events      = ["s3:ObjectCreated:*"]
  }
}

resource aws_s3_bucket_policy nfcisbenchmark {
  bucket = aws_s3_bucket.nfcisbenchmark_cloudtrail.id
  policy = data.aws_iam_policy_document.s3.json
  depends_on = [aws_s3_bucket.nfcisbenchmark_cloudtrail]
}

# 3.3 Ensure the S3 bucket used to store CloudTrail logs is not publicly accessible (Automated)
resource aws_s3_bucket_public_access_block cloudtrial {
  bucket = aws_s3_bucket.nfcisbenchmark_cloudtrail.id

  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

# 3.3 Ensure the S3 bucket used to store CloudTrail logs is not publicly accessible (Automated)
resource aws_s3_bucket_public_access_block log_bucket_cloudtrial {
  bucket = aws_s3_bucket.log_bucket_cloudtrail.id

  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}



////////////////////////////////////////
// Access Logging to Cloud Trail Bucket
////////////////////////////////////////

// This bucket logs access to the Cloudtrail log bucket above
resource aws_s3_bucket log_bucket_cloudtrail {
  bucket = "${local.bucket_prefix}-log"
  acl    = "log-delivery-write"
  // Tags
  tags = local.cost_tags
}


