# k8s-audit-logging / gcp / t0 "Quick start"
#
# GKE records every change to a cluster in its admin activity audit log by
# default, and keeps it for 400 days. This turns three entries in that log
# into alerts: exec or attach into a pod, a new cluster role binding, and a
# request from someone who never signed in.
#
# Change the two values below, then:
#   gcloud auth application-default login
#   terraform init && terraform apply
#
# Verify:
#   kubectl exec -it <any pod> -- true
#   The pod-exec alert opens an incident and emails you within a few minutes.

locals {
  project_id  = "your-project-id" # change me
  alert_email = "you@example.com" # change me
}

terraform {
  required_version = ">= 1.6"
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~> 8.0"
    }
  }
}

provider "google" {
  project = local.project_id
}

locals {
  # Exec is matched as create and as get, because newer clients open it as a
  # get over a WebSocket.
  detections = {
    pod-exec             = "resource.type=\"k8s_cluster\" AND protoPayload.methodName=(\"io.k8s.core.v1.pods.exec.create\" OR \"io.k8s.core.v1.pods.exec.get\" OR \"io.k8s.core.v1.pods.attach.create\" OR \"io.k8s.core.v1.pods.attach.get\")"
    cluster-role-binding = "resource.type=\"k8s_cluster\" AND protoPayload.methodName=\"io.k8s.authorization.rbac.v1.clusterrolebindings.create\""
    anonymous-request    = "resource.type=\"k8s_cluster\" AND protoPayload.authenticationInfo.principalEmail=\"system:anonymous\""
  }
}

resource "google_logging_metric" "detection" {
  for_each = local.detections
  name     = "gke-${each.key}"
  filter   = each.value
  metric_descriptor {
    metric_kind = "DELTA"
    value_type  = "INT64"
  }
}

resource "google_monitoring_notification_channel" "email" {
  display_name = "GKE audit alerts"
  type         = "email"
  labels = {
    email_address = local.alert_email
  }
}

resource "google_monitoring_alert_policy" "detection" {
  for_each              = local.detections
  display_name          = "GKE: ${each.key}"
  combiner              = "OR"
  notification_channels = [google_monitoring_notification_channel.email.id]
  conditions {
    display_name = each.key
    condition_threshold {
      filter          = "metric.type=\"logging.googleapis.com/user/${google_logging_metric.detection[each.key].name}\" AND resource.type=\"k8s_cluster\""
      comparison      = "COMPARISON_GT"
      threshold_value = 0
      duration        = "0s"
      aggregations {
        alignment_period   = "300s"
        per_series_aligner = "ALIGN_SUM"
      }
    }
  }
  documentation {
    content = "Seen in a GKE audit log. In Logs Explorer, search: ${each.value}"
  }
}
