# secrets-backend / azure / t0 "Quick start"
#
# A Key Vault that grants access through Azure roles only, cannot be purged
# before its retention ends, records every read and change, and emails when
# someone is refused. Three more alerts read the subscription's activity log
# without the workspace: a diagnostic setting deleted or written, and a rule
# disabled.
#
# Change the alert address below, then:
#   az login
#   export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv)
#   terraform init && terraform apply
#
# You get Key Vault Secrets Officer on the vault, to add secrets. Give an
# application Key Vault Secrets User, on the vault or on one secret, to read.
#
# Verify: a diagnostic setting can take up to 90 minutes to start sending,
# so wait that long after the first apply. Then:
#   az keyvault secret set --vault-name <vault> --name test --value hello
#   Then, as an identity without a role on the vault:
#   az keyvault secret show --vault-name <vault> --name test    # Forbidden
#   The refused-access email follows the first five-minute run after the
#   entry reaches the workspace.

locals {
  alert_email = "security-alerts@example.com" # change me
  location    = "eastus"
  tags = {
    owner               = "security-engineering"
    environment         = "prod"
    data_classification = "restricted"
    managed_by          = "terraform"
  }
}

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

provider "azurerm" {
  features {
    key_vault {
      purge_soft_delete_on_destroy = false
    }
  }
}

data "azurerm_client_config" "current" {}

resource "random_string" "suffix" {
  length  = 6
  special = false
  upper   = false
}

resource "azurerm_resource_group" "secrets" {
  name     = "rg-secrets"
  location = local.location
  tags     = local.tags
}

resource "azurerm_key_vault" "secrets" {
  name                       = "kv-secrets-${random_string.suffix.result}"
  location                   = azurerm_resource_group.secrets.location
  resource_group_name        = azurerm_resource_group.secrets.name
  tenant_id                  = data.azurerm_client_config.current.tenant_id
  sku_name                   = "standard"
  rbac_authorization_enabled = true
  purge_protection_enabled   = true
  soft_delete_retention_days = 90
  tags                       = local.tags
}

resource "azurerm_role_assignment" "officer" {
  scope                = azurerm_key_vault.secrets.id
  role_definition_name = "Key Vault Secrets Officer"
  principal_id         = data.azurerm_client_config.current.object_id
}

resource "azurerm_log_analytics_workspace" "secrets" {
  name                = "law-secrets-${random_string.suffix.result}"
  location            = azurerm_resource_group.secrets.location
  resource_group_name = azurerm_resource_group.secrets.name
  sku                 = "PerGB2018"
  retention_in_days   = 365
  tags                = local.tags
}

resource "azurerm_monitor_diagnostic_setting" "vault" {
  name                           = "audit"
  target_resource_id             = azurerm_key_vault.secrets.id
  log_analytics_workspace_id     = azurerm_log_analytics_workspace.secrets.id
  log_analytics_destination_type = "AzureDiagnostics"
  enabled_log {
    category = "AuditEvent"
  }
}

resource "azurerm_monitor_action_group" "security" {
  name                = "secrets-alerts"
  resource_group_name = azurerm_resource_group.secrets.name
  short_name          = "secrets"
  tags                = local.tags
  email_receiver {
    name          = "security"
    email_address = local.alert_email
  }
}

# Changes the workspace might never hear of. A deleted or rewritten setting
# stops the record of its own change, and a disabled rule does not run.
locals {
  native = {
    diagnostic-setting-deleted = {
      operation = "Microsoft.Insights/diagnosticSettings/delete"
      doc       = "A diagnostic setting was deleted in the subscription, possibly the one that records the vault's reads and changes."
    }
    # Policy remediation and other teams' monitoring write diagnostic
    # settings too, so expect some of these.
    diagnostic-setting-written = {
      operation = "Microsoft.Insights/diagnosticSettings/write"
      doc       = "A diagnostic setting was created or changed in the subscription. A rewrite can drop AuditEvent or send the record somewhere else."
    }
    # Azure writes this when a log search rule's query has failed for a week.
    rule-disabled = {
      operation = "Microsoft.Insights/ScheduledQueryRules/disable/action"
      doc       = "Azure disabled a log search alert rule in the subscription because its query kept failing."
    }
  }
}

# Azure evaluates these alerts on the activity log itself, with no workspace
# in between, and they cost nothing. They still notify through the one action
# group, so deleting or disabling it, or deleting the resource group,
# silences every alert here. Standard locks the alert path against deletes.
resource "azurerm_monitor_activity_log_alert" "native" {
  for_each            = local.native
  name                = "secrets-${each.key}"
  resource_group_name = azurerm_resource_group.secrets.name
  location            = "global"
  scopes              = ["/subscriptions/${data.azurerm_client_config.current.subscription_id}"]
  description         = each.value.doc
  tags                = local.tags

  criteria {
    category       = "Administrative"
    operation_name = each.value.operation
  }

  action {
    action_group_id = azurerm_monitor_action_group.security.id
  }
}

# The rule is made after the setting, though a setting can still take up to
# 90 minutes to start sending.
resource "azurerm_monitor_scheduled_query_rules_alert_v2" "refused" {
  name                = "secrets-refused"
  resource_group_name = azurerm_resource_group.secrets.name
  location            = azurerm_resource_group.secrets.location
  scopes              = [azurerm_log_analytics_workspace.secrets.id]
  description         = "Someone was refused access to the vault. A burst is someone testing what a stolen identity can read."
  severity            = 2
  # Look back an hour, keep rows that arrived in the last five minutes: a
  # late row is neither missed nor alerted twice.
  evaluation_frequency  = "PT5M"
  window_duration       = "PT1H"
  skip_query_validation = true
  tags                  = local.tags

  criteria {
    query                   = <<-KQL
      AzureDiagnostics
      | where ingestion_time() > ago(5m)
      | where ResourceProvider == "MICROSOFT.KEYVAULT" and ResultSignature == "Forbidden"
    KQL
    time_aggregation_method = "Count"
    operator                = "GreaterThan"
    threshold               = 0
  }

  action {
    action_groups = [azurerm_monitor_action_group.security.id]
  }

  depends_on = [azurerm_monitor_diagnostic_setting.vault]
}

output "vault_name" {
  description = "Put secrets here."
  value       = azurerm_key_vault.secrets.name
}
