resource "aws_kms_key" "kms_key" {
  policy              = data.aws_iam_policy_document.kms_key_policy.json
  enable_key_rotation = true
  tags                = local.tags
}

resource "aws_kms_alias" "kms_alias" {
  target_key_id = aws_kms_key.kms_key.key_id
  name          = "alias/${var.environment}-${var.service_name}-airflow-kms-key"
}

data "aws_iam_policy_document" "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:The same as above.

  statement {
    sid    = "Enable IAM User Permissions"
    effect = "Allow"
    principals {
      type        = "AWS"
      identifiers = ["arn:aws:iam::${data.aws_caller_identity.current.account_id}:root"]
    }
    actions   = ["kms:*"]
    resources = ["*"]
  }

  statement {
    sid    = "Enable CloudWatch logs service"
    effect = "Allow"
    principals {
      type        = "Service"
      identifiers = ["logs.${var.aws_region}.amazonaws.com"]
    }
    actions = [
      "kms:Encrypt*",
      "kms:Decrypt*",
      "kms:ReEncrypt*",
      "kms:GenerateDataKey*",
      "kms:Describe*",
    ]
    resources = ["*"]
    condition {
      test     = "ArnEquals"
      variable = "kms:EncryptionContext:aws:logs:arn"
      values   = ["arn:aws:logs:${var.aws_region}:${data.aws_caller_identity.current.account_id}:log-group:${local.cloudwatch_log_group_prefix}-*"]
    }
  }
}
