# compliance-evaluation / gcp / t0 "Quick start"
#
# Streams every active Security Command Center finding in one project to a
# Pub/Sub subscription, the moment it is raised: an open firewall, a public
# bucket, a service account key, and the rest of what Security Health
# Analytics checks.
#
# Security Command Center must already be on for the organisation; the
# Standard tier is free. Terraform cannot switch it on.
#
# Change the project below, then:
#   gcloud auth application-default login
#   terraform init && terraform apply
#
# Verify, in a scratch project:
#   Create a firewall rule allowing tcp:22 from 0.0.0.0/0.
#   terraform output verify    # pull the finding once it is raised
#   Delete the rule afterwards; the finding becomes inactive.

locals {
  project_id = "your-project-id" # change me
}

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

provider "google" {
  project = local.project_id
}

resource "google_project_service" "needed" {
  for_each           = toset(["securitycenter.googleapis.com", "pubsub.googleapis.com"])
  service            = each.value
  disable_on_destroy = false
}

resource "google_pubsub_topic" "findings" {
  name                       = "scc-findings"
  message_retention_duration = "604800s"
  depends_on                 = [google_project_service.needed]
}

# Security Command Center grants its own service account the right to publish
# here when the configuration is created, so the identity running Terraform
# needs permission to change this topic's IAM policy.
resource "google_scc_v2_project_notification_config" "findings" {
  project      = local.project_id
  location     = "global"
  config_id    = "active-findings"
  description  = "Every active, unmuted finding in this project."
  pubsub_topic = google_pubsub_topic.findings.id
  streaming_config {
    filter = "state = \"ACTIVE\" AND NOT mute = \"MUTED\""
  }
}

resource "google_pubsub_subscription" "findings" {
  name                       = "scc-findings"
  topic                      = google_pubsub_topic.findings.id
  message_retention_duration = "604800s"
  expiration_policy {
    ttl = ""
  }
}

output "verify" {
  description = "Shows waiting findings without removing them."
  value       = "gcloud pubsub subscriptions pull ${google_pubsub_subscription.findings.name} --project ${local.project_id} --limit=5"
}
