// KMS key for S3
resource "aws_kms_key" "s3" {
  description             = "KMS key for Teleport"
  enable_key_rotation     = true
  policy                  = data.aws_iam_policy_document.kms_key_encryption_policy.json
}

resource "aws_kms_alias" "s3" {
  name          = "alias/teleport-${var.instance_name}"
  target_key_id = aws_kms_key.s3.key_id
}

data "aws_iam_policy_document" "kms_key_encryption_policy" {
  #policy_id = "key-consolepolicy-3"
  statement {
    sid = "Enable IAM User Permissions"
    effect = "Allow"
    principals {
      type = "AWS"
      identifiers = [
        "arn:${var.aws_partition}:iam::${var.aws_account_id}:role/user/mdr_terraformer",
        "arn:${var.aws_partition}:iam::${var.aws_account_id}:user/MDRAdmin"
        ]
    }
    actions   = [ "kms:*" ]
    resources = [ "*" ]
  }

  statement {
    sid = "Allow access for Key Administrators"
    effect = "Allow"
    principals {
      type = "AWS"
      identifiers = [
        "arn:${var.aws_partition}:iam::${var.aws_account_id}:role/user/mdr_terraformer",
      ]
    }

    actions = [
      "kms:Create*",
      "kms:Describe*",
      "kms:Enable*",
      "kms:List*",
      "kms:Put*",
      "kms:Update*",
      "kms:Revoke*",
      "kms:Disable*",
      "kms:Get*",
      "kms:Delete*",
      "kms:TagResource",
      "kms:UntagResource",
      "kms:ScheduleKeyDeletion",
      "kms:CancelKeyDeletion"
    ]
    resources = [ "*" ]
  }

  statement {
    sid =  "Allow use of the key"
    effect = "Allow"
    principals {
      type = "AWS"
      identifiers = [
        aws_iam_role.auth.arn
      ]
    }
    actions = [
      "kms:Encrypt",
      "kms:Decrypt",
      "kms:ReEncrypt*",
      "kms:GenerateDataKey*",
      "kms:DescribeKey"
    ]
    resources = [ "*" ]
  }

  statement  {
    sid = "Allow access through Amazon S3 for all principals in the account that are authorized to use Amazon S3"
    effect = "Allow"
    principals {
      type = "AWS"
      identifiers = [ "*" ]
    }
    actions = [
        "kms:Encrypt",
        "kms:Decrypt",
        "kms:ReEncrypt*",
        "kms:GenerateDataKey*",
        "kms:DescribeKey"
    ]
    resources = [ "*" ]

    condition {
      test = "StringEquals"
      variable = "kms.ViaService"
      values = [ "s3.${var.aws_region}.amazonaws.com", "dynamodb.${var.aws_region}.amazonaws.com" ]
    }

    condition {
      test = "StringEquals"
      variable = "kms.CallerAccount"
      values = [ var.aws_account_id ]
    }
  }

  statement {
    sid =  "Allow DynamoDB to get information about the CMK"
    effect = "Allow"
    principals {
      type =  "Service"
      identifiers = ["dynamodb.amazonaws.com"]
    }
    actions = [
        "kms:Describe*",
        "kms:Get*",
        "kms:List*"
    ]
    resources = [ "*" ]
  }
}
