# secrets-backend / aws / t0 "Quick start"
#
# A Secrets Manager secret that rotates itself every 30 days. The rotation
# function generates every value, including the first, so no secret value
# ever passes through Terraform or lands in its state.
#
# Applications read the secret when they use it, or cache it for a short time,
# so a rotation reaches them with no redeploy.
#
#   terraform init && terraform apply
#
# Verify:
#   terraform output verify    # run the three commands it prints

locals {
  name = "app/api-token" # change me: the secret's name
}

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

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

resource "aws_secretsmanager_secret" "this" {
  name                    = local.name
  description             = "Rotates every 30 days. Read it at use time, never copy it."
  recovery_window_in_days = 7
}

locals {
  # The four steps Secrets Manager calls in order. setSecret is where a real
  # rotation tells the system the secret unlocks, such as a database or a
  # vendor's API, about the new value. This one generates a self-contained
  # token, so there is nothing to tell.
  code = <<-PY
    import boto3

    sm = boto3.client("secretsmanager")


    def handler(event, _context):
        arn, token, step = event["SecretId"], event["ClientRequestToken"], event["Step"]
        meta = sm.describe_secret(SecretId=arn)
        if not meta.get("RotationEnabled"):
            raise ValueError("rotation is not enabled for this secret")
        stages = meta.get("VersionIdsToStages", {})
        if token not in stages:
            raise ValueError("unknown version")
        if "AWSCURRENT" in stages[token]:
            return  # already finished

        if step == "createSecret":
            try:
                sm.get_secret_value(SecretId=arn, VersionId=token, VersionStage="AWSPENDING")
            except sm.exceptions.ResourceNotFoundException:
                value = sm.get_random_password(PasswordLength=48, ExcludePunctuation=True)["RandomPassword"]
                sm.put_secret_value(SecretId=arn, ClientRequestToken=token, SecretString=value,
                                    VersionStages=["AWSPENDING"])
        elif step == "setSecret":
            pass  # tell the target system about the new value here
        elif step == "testSecret":
            pass  # sign in to the target system with the new value here
        elif step == "finishSecret":
            current = next((v for v, s in stages.items() if "AWSCURRENT" in s), None)
            args = {"SecretId": arn, "VersionStage": "AWSCURRENT", "MoveToVersionId": token}
            if current:
                args["RemoveFromVersionId"] = current
            sm.update_secret_version_stage(**args)
        else:
            raise ValueError(f"unknown step {step}")
  PY
}

data "archive_file" "rotate" {
  type        = "zip"
  output_path = "${path.module}/.build/rotate.zip"
  source {
    content  = local.code
    filename = "rotate.py"
  }
}

data "aws_iam_policy_document" "lambda_trust" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["lambda.amazonaws.com"]
    }
  }
}

resource "aws_iam_role" "rotate" {
  name_prefix        = "secret-rotation-"
  assume_role_policy = data.aws_iam_policy_document.lambda_trust.json
}

resource "aws_iam_role_policy_attachment" "logs" {
  role       = aws_iam_role.rotate.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}

resource "aws_iam_role_policy" "rotate" {
  name = "rotate-this-secret"
  role = aws_iam_role.rotate.id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect   = "Allow"
        Action   = ["secretsmanager:DescribeSecret", "secretsmanager:GetSecretValue", "secretsmanager:PutSecretValue", "secretsmanager:UpdateSecretVersionStage"]
        Resource = aws_secretsmanager_secret.this.arn
      },
      { Effect = "Allow", Action = ["secretsmanager:GetRandomPassword"], Resource = "*" },
    ]
  })
}

resource "aws_lambda_function" "rotate" {
  function_name    = "rotate-${replace(local.name, "/", "-")}"
  role             = aws_iam_role.rotate.arn
  runtime          = "python3.12"
  handler          = "rotate.handler"
  filename         = data.archive_file.rotate.output_path
  source_code_hash = data.archive_file.rotate.output_base64sha256
  timeout          = 30
}

resource "aws_lambda_permission" "secrets_manager" {
  statement_id  = "SecretsManagerRotates"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.rotate.function_name
  principal     = "secretsmanager.amazonaws.com"
  source_arn    = aws_secretsmanager_secret.this.arn
}

# Turning rotation on runs it once straight away, which creates the first value.
resource "aws_secretsmanager_secret_rotation" "this" {
  secret_id           = aws_secretsmanager_secret.this.id
  rotation_lambda_arn = aws_lambda_function.rotate.arn
  rotation_rules {
    automatically_after_days = 30
  }
  depends_on = [aws_lambda_permission.secrets_manager, aws_iam_role_policy.rotate]
}

output "verify" {
  description = "Read the version, rotate, and read it again. The version ID changes."
  value       = <<-EOT
    aws secretsmanager describe-secret --secret-id ${local.name} --query 'VersionIdsToStages'
    aws secretsmanager rotate-secret --secret-id ${local.name}
    aws secretsmanager describe-secret --secret-id ${local.name} --query 'VersionIdsToStages'   # a new ID has AWSCURRENT, the old one AWSPREVIOUS
  EOT
}
