# k8s-audit-logging / aws / t0 "Quick start"
#
# Keeps an EKS cluster's audit log for a year, and raises an alarm when anyone
# execs or attaches into a pod, creates a cluster role binding, or reaches the
# API without signing in.
#
# EKS writes nothing until audit logging is switched on for the cluster. Change
# the two values below, then:
#   terraform init && terraform apply
#   terraform output switch_on          # run the command it prints
#
# Confirm the email subscription, then verify:
#   kubectl exec -it <any pod> -- true
#   Within about ten minutes the pod-exec alarm fires and the email arrives.

locals {
  cluster_name = "your-cluster"    # change me
  alert_email  = "you@example.com" # change me
}

terraform {
  required_version = ">= 1.6"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

provider "aws" {
  default_tags {
    tags = {
      owner               = "platform-engineering"
      environment         = "prod"
      data_classification = "internal"
      managed_by          = "terraform"
    }
  }
}

# EKS writes to this exact name. Creating it first sets the retention; EKS
# would otherwise create it with no expiry. If logging is already on, the group
# exists: import it with terraform import aws_cloudwatch_log_group.audit <name>.
resource "aws_cloudwatch_log_group" "audit" {
  name              = "/aws/eks/${local.cluster_name}/cluster"
  retention_in_days = 365
}

resource "aws_sns_topic" "alerts" {
  name = "eks-audit-${local.cluster_name}"
}

resource "aws_sns_topic_subscription" "email" {
  topic_arn = aws_sns_topic.alerts.arn
  protocol  = "email"
  endpoint  = local.alert_email
}

locals {
  # One pattern per behaviour. Each audit event is written at more than one
  # stage, so matching ResponseComplete counts every call once. Exec is matched
  # on the subresource alone because newer clients send it as a get.
  detections = {
    pod-exec             = "{ ($.stage = \"ResponseComplete\") && (($.objectRef.subresource = \"exec\") || ($.objectRef.subresource = \"attach\")) }"
    cluster-role-binding = "{ ($.stage = \"ResponseComplete\") && ($.objectRef.resource = \"clusterrolebindings\") && ($.verb = \"create\") }"
    anonymous-request    = "{ ($.stage = \"ResponseComplete\") && ($.user.username = \"system:anonymous\") }"
  }
}

resource "aws_cloudwatch_log_metric_filter" "detection" {
  for_each       = local.detections
  name           = each.key
  log_group_name = aws_cloudwatch_log_group.audit.name
  pattern        = each.value
  metric_transformation {
    name          = each.key
    namespace     = "EKS/Audit/${local.cluster_name}"
    value         = "1"
    default_value = "0"
  }
}

resource "aws_cloudwatch_metric_alarm" "detection" {
  for_each            = local.detections
  alarm_name          = "eks-${local.cluster_name}-${each.key}"
  alarm_description   = "Seen in the ${local.cluster_name} audit log. Search the log group for the event to see who and which object."
  namespace           = "EKS/Audit/${local.cluster_name}"
  metric_name         = each.key
  statistic           = "Sum"
  period              = 300
  evaluation_periods  = 1
  threshold           = 1
  comparison_operator = "GreaterThanOrEqualToThreshold"
  treat_missing_data  = "notBreaching"
  alarm_actions       = [aws_sns_topic.alerts.arn]
  depends_on          = [aws_cloudwatch_log_metric_filter.detection]
}

output "switch_on" {
  description = "Switches on audit and authenticator logging for the cluster."
  value       = "aws eks update-cluster-config --name ${local.cluster_name} --logging '{\"clusterLogging\":[{\"types\":[\"audit\",\"authenticator\"],\"enabled\":true}]}'"
}
