# An alert whenever anyone, anywhere in this region, switches a key off, # schedules a deletion, or rewrites a key policy. A key is only a control if # someone notices when the lever is pulled. # # These events reach EventBridge through CloudTrail, so the account needs a trail # that records management events. The audit log template creates one. resource "aws_cloudwatch_event_rule" "key_changes" { name = "${var.name}-kms-key-changes" description = "KMS keys switched off, scheduled for deletion, or given a new policy." event_pattern = jsonencode({ source = ["aws.kms"] "detail-type" = ["AWS API Call via CloudTrail"] detail = { eventSource = ["kms.amazonaws.com"] eventName = ["DisableKey", "ScheduleKeyDeletion", "PutKeyPolicy"] } }) } # Deliberately not encrypted with the key it watches. If it were, switching the # key off would also silence the alert about switching it off. resource "aws_sns_topic" "key_changes" { name = "${var.name}-kms-key-changes" } data "aws_iam_policy_document" "topic" { statement { sid = "EventBridgePublishes" effect = "Allow" actions = ["sns:Publish"] principals { type = "Service" identifiers = ["events.amazonaws.com"] } resources = [aws_sns_topic.key_changes.arn] condition { test = "ArnEquals" variable = "aws:SourceArn" values = [aws_cloudwatch_event_rule.key_changes.arn] } } } resource "aws_sns_topic_policy" "key_changes" { arn = aws_sns_topic.key_changes.arn policy = data.aws_iam_policy_document.topic.json } resource "aws_cloudwatch_event_target" "key_changes" { rule = aws_cloudwatch_event_rule.key_changes.name arn = aws_sns_topic.key_changes.arn } resource "aws_sns_topic_subscription" "email" { count = var.alert_email == "" ? 0 : 1 topic_arn = aws_sns_topic.key_changes.arn protocol = "email" endpoint = var.alert_email }