# key-baseline / aws / t0 "Quick start"
#
# A KMS key that rotates every year, with an alias, and a policy that keeps the
# account able to manage it.
#
# Run:
#   terraform init && terraform apply
#   terraform output verify
#
# The verify commands encrypt a word, switch the key off, and show that the
# same ciphertext can no longer be decrypted. Then they switch it back on. That
# off switch is the reason to own a key at all.
#
# Deletion waits seven days here, the shortest AWS allows, so you can remove
# this next week. The Standard version waits thirty.

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

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

data "aws_caller_identity" "current" {}
data "aws_partition" "current" {}

resource "aws_kms_key" "this" {
  description             = "key-baseline quick start"
  enable_key_rotation     = true
  rotation_period_in_days = 365
  deletion_window_in_days = 7
  policy                  = data.aws_iam_policy_document.key.json
}

resource "aws_kms_alias" "this" {
  name          = "alias/key-baseline"
  target_key_id = aws_kms_key.this.key_id
}

# A key policy that names nobody can leave a key nobody can manage. This one
# statement lets the account's IAM policies decide who may do what.
data "aws_iam_policy_document" "key" {
  statement {
    sid    = "AccountManagesKeyThroughIAM"
    effect = "Allow"
    principals {
      type        = "AWS"
      identifiers = ["arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:root"]
    }
    actions   = ["kms:*"]
    resources = ["*"]
  }
}

output "key_arn" {
  description = "The key."
  value       = aws_kms_key.this.arn
}

output "verify" {
  description = "Encrypt, switch the key off, watch decrypt fail, switch it back on."
  value       = <<-EOT
    aws kms encrypt --key-id ${aws_kms_alias.this.name} --plaintext fileb://<(printf hello) --query CiphertextBlob --output text > secret.b64
    aws kms disable-key --key-id ${aws_kms_key.this.key_id}
    aws kms decrypt --ciphertext-blob fileb://<(base64 -d secret.b64)      # must fail with DisabledException
    aws kms enable-key --key-id ${aws_kms_key.this.key_id}
  EOT
}
