resource "aws_kms_key" "recovery_key" {
  description         = "KMS key used for intermediate or shareable RDS snapshots"
  enable_key_rotation = true
  policy              = data.aws_iam_policy_document.kms_policy.json

  tags = local.tags
}

resource "aws_kms_alias" "kms_alias" {
  name          = "alias/${var.environment}-${var.service_name}-shareable-snapshot-key"
  target_key_id = aws_kms_key.recovery_key.key_id
}

data "aws_iam_policy_document" "kms_policy" {
  # checkov:skip=CKV_AWS_109:It is a KMS key policy, so it applies only to a specific key.
  # checkov:skip=CKV_AWS_111:Same as above.

  # Statement from default KMS key policy
  statement {
    sid    = "Enable IAM policies"
    effect = "Allow"

    principals {
      type        = "AWS"
      identifiers = ["arn:aws:iam::${data.aws_caller_identity.current.account_id}:root"]
    }

    actions   = ["kms:*"]
    resources = ["*"]
  }

  dynamic "statement" {
    for_each = toset(var.recovery_account_ids)
    content {
      sid    = "Allow ${statement.value} disaster recovery account(s) to use key"
      effect = "Allow"
      principals {
        type        = "AWS"
        identifiers = ["arn:aws:iam::${statement.value}:root"]
      }
      actions = [
        "kms:CreateGrant",
      ]
      resources = ["*"]

      condition {
        test     = "Bool"
        variable = "kms:GrantIsForAWSResource"
        values   = ["true"]
      }
    }
  }

  dynamic "statement" {
    for_each = toset(var.recovery_account_ids)
    content {
      sid    = "Allow disaster recovery account ${statement.value} to describe key"
      effect = "Allow"
      principals {
        type        = "AWS"
        identifiers = ["arn:aws:iam::${statement.value}:root"]
      }
      actions = [
        "kms:DescribeKey",
      ]
      resources = ["*"]
    }
  }
}
