# secrets-backend / aws / t1 "Standard" # # One secret under its own key, readable only by named roles, rotating on a # schedule, with alerts on refused reads, changes to the secret, and failed # rotations. Use this folder once per secret, or call it as a module. data "aws_caller_identity" "current" {} data "aws_region" "current" {} data "aws_partition" "current" {} locals { tags = merge({ owner = var.owner environment = var.environment data_classification = "restricted" managed_by = "terraform" }, var.extra_tags) account = data.aws_caller_identity.current.account_id region = data.aws_region.current.region partition = data.aws_partition.current.partition slug = replace(var.name, "/", "-") readers = concat(var.reader_role_arns, [aws_iam_role.rotate.arn]) } data "aws_iam_policy_document" "key" { statement { sid = "AccountManagesKeyThroughIAM" actions = ["kms:*"] resources = ["*"] principals { type = "AWS" identifiers = ["arn:${local.partition}:iam::${local.account}:root"] } } # Readers decrypt only through Secrets Manager, so the key cannot be used # to decrypt anything taken out of it some other way. statement { sid = "ReadersDecryptThroughSecretsManager" actions = ["kms:Decrypt", "kms:GenerateDataKey"] resources = ["*"] principals { type = "AWS" identifiers = local.readers } condition { test = "StringEquals" variable = "kms:ViaService" values = ["secretsmanager.${local.region}.amazonaws.com"] } } } resource "aws_kms_key" "secret" { description = "Secret ${var.name}" enable_key_rotation = true deletion_window_in_days = 30 policy = data.aws_iam_policy_document.key.json } resource "aws_secretsmanager_secret" "this" { name = var.name description = "Rotates every ${var.rotation_days} days. Readable only by named roles." kms_key_id = aws_kms_key.secret.arn recovery_window_in_days = 30 } # A deny in the secret's own policy wins over any allow elsewhere, so no role # outside the list can read it, whatever its permissions say. data "aws_iam_policy_document" "secret" { statement { sid = "OnlyNamedReaders" effect = "Deny" actions = ["secretsmanager:GetSecretValue"] resources = ["*"] principals { type = "*" identifiers = ["*"] } condition { test = "ArnNotEquals" variable = "aws:PrincipalArn" values = local.readers } } } resource "aws_secretsmanager_secret_policy" "this" { secret_arn = aws_secretsmanager_secret.this.arn policy = data.aws_iam_policy_document.secret.json block_public_policy = true } data "archive_file" "rotate" { type = "zip" source_file = "${path.module}/rotate.py" output_path = "${path.module}/.build/rotate.zip" } data "aws_iam_policy_document" "lambda_trust" { statement { actions = ["sts:AssumeRole"] principals { type = "Service" identifiers = ["lambda.amazonaws.com"] } } } resource "aws_iam_role" "rotate" { name = "rotate-${local.slug}" 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:${local.partition}: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 = "*" }, { Effect = "Allow", Action = ["kms:Decrypt", "kms:GenerateDataKey"], Resource = aws_kms_key.secret.arn }, ] }) } resource "aws_cloudwatch_log_group" "rotate" { name = "/aws/lambda/rotate-${local.slug}" retention_in_days = 400 } resource "aws_lambda_function" "rotate" { function_name = "rotate-${local.slug}" 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 depends_on = [aws_cloudwatch_log_group.rotate] } 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 } 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 = var.rotation_days } depends_on = [aws_lambda_permission.secrets_manager, aws_iam_role_policy.rotate, aws_secretsmanager_secret_policy.this] } locals { # Callers may name the secret or give its ARN, so match both. this_secret = "(($.requestParameters.secretId = \"${var.name}\") || ($.requestParameters.secretId = \"${aws_secretsmanager_secret.this.arn}\"))" sm = "($.eventSource = \"secretsmanager.amazonaws.com\")" detections = { read-refused = { pattern = "{ ${local.sm} && ${local.this_secret} && (($.errorCode = \"AccessDenied\") || ($.errorCode = \"AccessDeniedException\")) }" description = "Someone outside the reader list tried to read ${var.name}." } changed = { pattern = "{ ${local.sm} && ${local.this_secret} && (($.eventName = \"DeleteSecret\") || ($.eventName = \"PutResourcePolicy\") || ($.eventName = \"DeleteResourcePolicy\") || ($.eventName = \"CancelRotateSecret\") || ($.eventName = \"UpdateSecret\")) }" description = "Someone deleted ${var.name}, changed its policy, or stopped its rotation." } # Rotation results name the secret in a different field, so this one # covers every secret in the account. rotation-failed = { pattern = "{ ${local.sm} && ($.eventName = \"RotationFailed\") }" description = "A secret rotation failed in this account. The rotation function's log says why." } } } resource "aws_cloudwatch_log_metric_filter" "detection" { for_each = local.detections name = "secret-${local.slug}-${each.key}" log_group_name = var.trail_log_group pattern = each.value.pattern metric_transformation { name = "${local.slug}-${each.key}" namespace = "Security/Secrets" value = "1" default_value = "0" } } resource "aws_cloudwatch_metric_alarm" "detection" { for_each = local.detections alarm_name = "secret-${local.slug}-${each.key}" alarm_description = each.value.description namespace = "Security/Secrets" metric_name = "${local.slug}-${each.key}" statistic = "Sum" period = 300 evaluation_periods = 1 threshold = 1 comparison_operator = "GreaterThanOrEqualToThreshold" treat_missing_data = "notBreaching" alarm_actions = [var.alert_topic_arn] depends_on = [aws_cloudwatch_log_metric_filter.detection] }