# key-baseline / gcp / t0 "Quick start"
#
# A Cloud KMS key ring and a key that rotates every 90 days. The verify
# commands encrypt a word, switch the key version off, show that decrypting
# now fails, and switch it back on.
#
# Change the project ID below, then:
#   gcloud auth application-default login
#   terraform init && terraform apply
#   terraform output verify
#
# One thing to know before you run this anywhere: key rings and keys can never
# be deleted in Google Cloud. terraform destroy removes them from state and
# destroys the key versions, and the names stay used in that project for good.

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

  location = "us-east1"
}

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

provider "google" {
  project = local.project_id
}

# Off in a new project.
resource "google_project_service" "kms" {
  service            = "cloudkms.googleapis.com"
  disable_on_destroy = false
}

# Key rings are permanent, so a random suffix keeps a second apply after a
# destroy from colliding with the first ring's name.
resource "random_id" "ring" {
  byte_length = 3
}

resource "google_kms_key_ring" "this" {
  name       = "key-baseline-${random_id.ring.hex}"
  location   = local.location
  depends_on = [google_project_service.kms]
}

resource "google_kms_crypto_key" "this" {
  name            = "app-data"
  key_ring        = google_kms_key_ring.this.id
  rotation_period = "7776000s" # 90 days

  labels = {
    owner               = "security-engineering"
    environment         = "prod"
    data_classification = "restricted"
    managed_by          = "terraform"
  }
}

output "key_id" {
  description = "The key."
  value       = google_kms_crypto_key.this.id
}

output "verify" {
  description = "Encrypt, switch the key version off, watch decrypt fail, switch it back on."
  value       = <<-EOT
    printf hello > plain.txt
    gcloud kms encrypt --location ${local.location} --keyring ${google_kms_key_ring.this.name} --key ${google_kms_crypto_key.this.name} --plaintext-file plain.txt --ciphertext-file secret.enc
    gcloud kms keys versions disable 1 --location ${local.location} --keyring ${google_kms_key_ring.this.name} --key ${google_kms_crypto_key.this.name}
    gcloud kms decrypt --location ${local.location} --keyring ${google_kms_key_ring.this.name} --key ${google_kms_crypto_key.this.name} --ciphertext-file secret.enc --plaintext-file -      # must fail, the version is disabled
    gcloud kms keys versions enable 1 --location ${local.location} --keyring ${google_kms_key_ring.this.name} --key ${google_kms_crypto_key.this.name}
  EOT
}
