data "aws_iam_policy_document" "rds_shared_snapshots_kms_key_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 = ["*"]
  }

  statement {
    sid    = "Allow external principals to describe key for copying snapshots"
    effect = "Allow"

    principals {
      type        = "AWS"
      identifiers = local.external_restore_account_arns
    }

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

  statement {
    sid    = "Allow external principals to create grants for copying snapshots"
    effect = "Allow"

    principals {
      type        = "AWS"
      identifiers = local.external_restore_account_arns
    }

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

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

resource "aws_kms_key" "rds_shared_snapshots_kms_key" {
  description         = "KMS key for encrypting RDS snapshots to be shared across accounts"
  policy              = data.aws_iam_policy_document.rds_shared_snapshots_kms_key_policy.json
  enable_key_rotation = true
  tags = {
    environment        = var.environment
    application_family = var.application_family
    project            = var.service_name
    terraformed        = true
  }
}

resource "aws_kms_alias" "rds_shared_snapshots_kms_alias" {
  name          = "alias/${var.environment}-${var.service_name}-shared-snapshots"
  target_key_id = aws_kms_key.rds_shared_snapshots_kms_key.key_id
}
