# audit-log-immutable / azure / t0 "Paste"
#
# Subscription Activity Log written to a blob container under a time-based
# immutability policy. Blobs cannot be deleted or overwritten for the period,
# including by a subscription Owner.
#
# Retention here is one day and the policy is unlocked, so you can try this in a
# scratch subscription and remove it. The Standard version defaults to 400 days.
#
# Run:
#   az login
#   export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv)
#   terraform init && terraform apply
#
# Since version 4, the Azure provider no longer guesses which subscription to use.
# The export line tells it, and keeps this file free of anything to edit.
#
# Verify:
#   az storage blob delete --account-name <account> --container-name insights-activity-logs --name <blob>
#   Expect: this operation is not permitted on an immutable blob.
#
# Gotcha this template exists to handle: the diagnostic setting writes to a
# container Azure creates on first delivery, named insights-activity-logs.
# Creating that container up front is what lets the policy attach to it.

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-based access is switched off on the storage account below, so the
  # provider has to use Entra ID for any data-plane call it makes.
  storage_use_azuread = true
}

data "azurerm_subscription" "current" {}

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

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

resource "azurerm_resource_group" "audit" {
  name     = "rg-audit-log-immutable"
  location = "eastus"
  tags     = local.tags
}

resource "azurerm_storage_account" "audit" {
  name                            = "auditlog${random_string.suffix.result}"
  resource_group_name             = azurerm_resource_group.audit.name
  location                        = azurerm_resource_group.audit.location
  account_tier                    = "Standard"
  account_replication_type        = "GRS"
  account_kind                    = "StorageV2"
  min_tls_version                 = "TLS1_2"
  https_traffic_only_enabled      = true
  allow_nested_items_to_be_public = false
  shared_access_key_enabled       = false
  tags                            = local.tags

  blob_properties {
    versioning_enabled = true
  }
}

resource "azurerm_storage_container" "activity" {
  name                  = "insights-activity-logs"
  storage_account_id    = azurerm_storage_account.audit.id
  container_access_type = "private"
}

# Unlocked, so it can be shortened or removed while you are testing.
#
# protected_append_writes_all_enabled matters more than it looks. Azure Monitor
# appends to one blob per hour. Without this flag the policy blocks those appends
# and delivery fails quietly.
resource "azurerm_storage_container_immutability_policy" "activity" {
  # With storage_account_id set on the container, its id is the Resource
  # Manager id this resource expects.
  storage_container_resource_manager_id = azurerm_storage_container.activity.id
  immutability_period_in_days           = 1
  protected_append_writes_all_enabled   = true
  locked                                = false
}

resource "azurerm_monitor_diagnostic_setting" "activity" {
  name               = "activity-to-immutable-blob"
  target_resource_id = data.azurerm_subscription.current.id
  storage_account_id = azurerm_storage_account.audit.id

  enabled_log { category = "Administrative" }
  enabled_log { category = "Security" }
  enabled_log { category = "ServiceHealth" }
  enabled_log { category = "Alert" }
  enabled_log { category = "Policy" }
  enabled_log { category = "Autoscale" }
  enabled_log { category = "ResourceHealth" }
  enabled_log { category = "Recommendation" }
}

output "storage_account" {
  description = "Account containing the activity log."
  value       = azurerm_storage_account.audit.name
}

output "container" {
  description = "Container under the immutability policy."
  value       = azurerm_storage_container.activity.name
}

output "verify" {
  description = "Command that must fail."
  value       = "az storage blob delete --account-name ${azurerm_storage_account.audit.name} --container-name ${azurerm_storage_container.activity.name} --name <blob> --auth-mode login"
}
