#S3 bucket for codebuild output
resource "aws_s3_bucket" "artifacts" {
  bucket        = "xdr-codebuild-artifacts"
  force_destroy = true
  acl           = "private"

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

resource "aws_s3_bucket_policy" "artifacts" {
  bucket = aws_s3_bucket.artifacts.id
  policy = data.aws_iam_policy_document.artifacts.json
}

data "aws_iam_policy_document" "artifacts" {
  statement {
    sid = "AllowS3Access"
    actions = [ "s3:GetObject", "s3:GetObjectVersion" ]
    effect = "Allow"
    resources = [ "${aws_s3_bucket.artifacts.arn}/*" ]
    principals {
      type = "AWS"
      identifiers = [ for a in var.responsible_accounts[var.environment]: "arn:${var.aws_partition}:iam::${a}:root" ]
    }
  }
}

