# secrets-backend / oci / t0 "Quick start"
#
# An OCI Vault with a hardware-protected key for secrets, a policy letting one
# group read the secrets in this vault and another manage them, and an email
# when someone is refused a secret. Every read and change is recorded in Audit
# with no extra setup.
#
# Change the four values below. The provider reads everything else, region
# included, from the DEFAULT profile in ~/.oci/config. Then:
#   terraform init && terraform apply
#
# Add a secret, as a member of the officers group:
#   oci vault secret create-base64 --compartment-id <compartment> --vault-id <vault> \
#     --key-id <key> --secret-name test --secret-content-content $(printf hello | base64)
#
# Verify: confirm the subscription email. Then, as a user in neither group:
#   oci secrets secret-bundle get-secret-bundle-by-name --vault-id <vault> --secret-name test
#   The call is refused with 404, and the email follows within a few minutes.

locals {
  tenancy_ocid     = "ocid1.tenancy.oc1..change-me"     # change me
  compartment_ocid = "ocid1.compartment.oc1..change-me" # change me
  alert_email      = "security-alerts@example.com"      # change me
  readers_group    = "secrets-readers"                  # change me: may read secrets
  officers_group   = "secrets-officers"                 # change me: may create and change them

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

  # Oracle documents "and" and "or" for a connector's filter, with no
  # parentheses and no order for mixing the two. So each filter is one "and"
  # of two equalities: either read operation, answered 401 or 404. Connector
  # Hub allows 20 connectors per region by default and five on a trial
  # account; this uses four.
  refused = {
    refused-get-401     = "data.eventName='GetSecretBundle' and data.response.status='401'"
    refused-get-404     = "data.eventName='GetSecretBundle' and data.response.status='404'"
    refused-by-name-401 = "data.eventName='GetSecretBundleByName' and data.response.status='401'"
    refused-by-name-404 = "data.eventName='GetSecretBundleByName' and data.response.status='404'"
  }
}

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

provider "oci" {}

resource "oci_kms_vault" "secrets" {
  compartment_id = local.compartment_ocid
  display_name   = "secrets"
  vault_type     = "DEFAULT"
  freeform_tags  = local.tags
}

resource "oci_kms_key" "secrets" {
  compartment_id      = local.compartment_ocid
  display_name        = "secrets"
  management_endpoint = oci_kms_vault.secrets.management_endpoint
  protection_mode     = "HSM"
  freeform_tags       = local.tags

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

# Readers read secret contents in this vault only. Officers manage secrets in
# it and encrypt them with its key, but cannot delete the vault or the key.
resource "oci_identity_policy" "secrets" {
  compartment_id = local.tenancy_ocid
  name           = "secrets-backend"
  description    = "Who may read and manage secrets in the secrets vault."
  freeform_tags  = local.tags
  statements = [
    "Allow group ${local.readers_group} to read secret-bundles in compartment id ${local.compartment_ocid} where target.vault.id = '${oci_kms_vault.secrets.id}'",
    "Allow group ${local.officers_group} to manage secret-family in compartment id ${local.compartment_ocid} where target.vault.id = '${oci_kms_vault.secrets.id}'",
    "Allow group ${local.officers_group} to use keys in compartment id ${local.compartment_ocid} where target.key.id = '${oci_kms_key.secrets.id}'",
    "Allow group ${local.officers_group} to use vaults in compartment id ${local.compartment_ocid} where target.vault.id = '${oci_kms_vault.secrets.id}'",
    "Allow any-user to use ons-topics in compartment id ${local.compartment_ocid} where all {request.principal.type='serviceconnector', target.topic.id='${oci_ons_notification_topic.refused.id}', request.principal.compartment.id='${local.compartment_ocid}'}",
  ]
}

resource "oci_ons_notification_topic" "refused" {
  compartment_id = local.compartment_ocid
  name           = "secrets-refused"
  description    = "Refused attempts to read a secret."
  freeform_tags  = local.tags
}

resource "oci_ons_subscription" "email" {
  compartment_id = local.compartment_ocid
  topic_id       = oci_ons_notification_topic.refused.id
  protocol       = "EMAIL"
  endpoint       = local.alert_email
  freeform_tags  = local.tags
}

# OCI answers a caller without permission with 404 NotAuthorizedOrNotFound, so
# a refusal and a wrong name look the same. Both are worth a look.
resource "oci_sch_service_connector" "refused" {
  for_each       = local.refused
  compartment_id = local.compartment_ocid
  display_name   = "secrets-${each.key}"
  description    = "Secret reads that were refused."
  freeform_tags  = local.tags

  source {
    kind = "logging"
    log_sources {
      compartment_id = local.compartment_ocid
      log_group_id   = "_Audit"
    }
  }

  tasks {
    kind      = "logRule"
    condition = each.value
  }

  target {
    kind                       = "notifications"
    topic_id                   = oci_ons_notification_topic.refused.id
    enable_formatted_messaging = true
  }

  depends_on = [oci_identity_policy.secrets]
}

# The alert was one connector before v0.42.0. It becomes the first of the
# four, changed in place.
moved {
  from = oci_sch_service_connector.refused
  to   = oci_sch_service_connector.refused["refused-get-401"]
}

output "vault_id" {
  description = "The vault."
  value       = oci_kms_vault.secrets.id
}

output "key_id" {
  description = "Encrypt secrets with this key."
  value       = oci_kms_key.secrets.id
}
