# key-baseline / oci / t0 "Quick start"
#
# A vault and one AES-256 key. The verify commands encrypt a word, switch the
# key off, show that decrypting now fails, and switch it back on.
#
# Change the compartment OCID and region below, then:
#   terraform init && terraform apply
#   terraform output verify
#
# Deleting a vault or key only schedules it, with a wait of at least seven days
# that can be cancelled. terraform destroy starts that clock.

locals {
  compartment_ocid = "ocid1.compartment.oc1..change-me" # change me
  region           = "us-ashburn-1"                     # change me

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

terraform {
  required_version = ">= 1.6"
  required_providers {
    oci = {
      source  = "oracle/oci"
      version = "~> 9.0"
    }
  }
}

provider "oci" {
  region = local.region
}

resource "oci_kms_vault" "this" {
  compartment_id = local.compartment_ocid
  display_name   = "key-baseline"
  vault_type     = "DEFAULT"
  freeform_tags  = local.tags
}

# Software-protected here. The Standard version uses the vault's hardware.
resource "oci_kms_key" "this" {
  compartment_id      = local.compartment_ocid
  display_name        = "app-data"
  management_endpoint = oci_kms_vault.this.management_endpoint
  protection_mode     = "SOFTWARE"
  freeform_tags       = local.tags

  key_shape {
    algorithm = "AES"
    length    = 32
  }
}

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

output "verify" {
  description = "Encrypt, switch the key off, watch decrypt fail, switch it back on."
  value       = <<-EOT
    oci kms crypto encrypt --key-id ${oci_kms_key.this.id} --endpoint ${oci_kms_vault.this.crypto_endpoint} --plaintext "$(printf hello | base64)" --query 'data.ciphertext' --raw-output > secret.txt
    oci kms management key disable --key-id ${oci_kms_key.this.id} --endpoint ${oci_kms_vault.this.management_endpoint}
    oci kms crypto decrypt --key-id ${oci_kms_key.this.id} --endpoint ${oci_kms_vault.this.crypto_endpoint} --ciphertext "$(cat secret.txt)"      # must fail, the key is disabled
    oci kms management key enable --key-id ${oci_kms_key.this.id} --endpoint ${oci_kms_vault.this.management_endpoint}
  EOT
}
