# audit-log-immutable / aws / t0 "Paste"
#
# CloudTrail writing to an S3 bucket with Object Lock in GOVERNANCE mode.
# A locked log file cannot be deleted until its retention period ends.
#
# Run:
#   terraform init && terraform apply
#
# Verify, once the first logs arrive (about fifteen minutes):
#   terraform output verify
#   Run the two commands it prints. The second must fail with AccessDenied.
#
# Why two commands: the bucket is versioned, so a plain delete-object only adds
# a "delete marker" and reports success while the log file is still there. The
# lock protects each stored version, so the real test deletes a version by ID.
#
# Retention here is one day, so you can try this in a scratch account and tear
# it down tomorrow. The Standard version defaults to 400 days.

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

provider "aws" {}

data "aws_caller_identity" "current" {}
data "aws_partition" "current" {}

resource "random_id" "suffix" {
  byte_length = 4
}

locals {
  bucket_name    = "audit-log-immutable-${data.aws_caller_identity.current.account_id}-${random_id.suffix.hex}"
  trail_name     = "audit-log-immutable"
  retention_days = 1
}

# ---------------------------------------------------------------------------
# Bucket. object_lock_enabled can only be set at creation time.
# ---------------------------------------------------------------------------
resource "aws_s3_bucket" "audit" {
  bucket              = local.bucket_name
  object_lock_enabled = true

  # True here so terraform destroy can empty the bucket once the one-day lock
  # has passed. The Standard version sets this false.
  force_destroy = true

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

# Object Lock requires versioning. Terraform will not enable it implicitly.
resource "aws_s3_bucket_versioning" "audit" {
  bucket = aws_s3_bucket.audit.id
  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_object_lock_configuration" "audit" {
  bucket     = aws_s3_bucket.audit.id
  depends_on = [aws_s3_bucket_versioning.audit]

  rule {
    default_retention {
      mode = "GOVERNANCE"
      days = local.retention_days
    }
  }
}

resource "aws_s3_bucket_public_access_block" "audit" {
  bucket                  = aws_s3_bucket.audit.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

resource "aws_s3_bucket_server_side_encryption_configuration" "audit" {
  bucket = aws_s3_bucket.audit.id
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }
    bucket_key_enabled = true
  }
}

resource "aws_s3_bucket_lifecycle_configuration" "audit" {
  bucket     = aws_s3_bucket.audit.id
  depends_on = [aws_s3_bucket_versioning.audit]

  rule {
    id     = "abort-incomplete-uploads"
    status = "Enabled"
    filter {}
    abort_incomplete_multipart_upload {
      days_after_initiation = 7
    }
  }
}

# ---------------------------------------------------------------------------
# Bucket policy. Both statements are required or CreateTrail fails validation.
# aws:SourceArn scopes delivery to this trail only.
# ---------------------------------------------------------------------------
data "aws_iam_policy_document" "audit" {
  statement {
    sid     = "AWSCloudTrailAclCheck"
    effect  = "Allow"
    actions = ["s3:GetBucketAcl"]
    principals {
      type        = "Service"
      identifiers = ["cloudtrail.amazonaws.com"]
    }
    resources = [aws_s3_bucket.audit.arn]
    condition {
      test     = "StringEquals"
      variable = "aws:SourceArn"
      values   = [local.trail_arn]
    }
  }

  statement {
    sid     = "AWSCloudTrailWrite"
    effect  = "Allow"
    actions = ["s3:PutObject"]
    principals {
      type        = "Service"
      identifiers = ["cloudtrail.amazonaws.com"]
    }
    resources = ["${aws_s3_bucket.audit.arn}/AWSLogs/${data.aws_caller_identity.current.account_id}/*"]
    condition {
      test     = "StringEquals"
      variable = "s3:x-amz-acl"
      values   = ["bucket-owner-full-control"]
    }
    condition {
      test     = "StringEquals"
      variable = "aws:SourceArn"
      values   = [local.trail_arn]
    }
  }

  statement {
    sid     = "DenyUnencryptedTransport"
    effect  = "Deny"
    actions = ["s3:*"]
    principals {
      type        = "AWS"
      identifiers = ["*"]
    }
    resources = [
      aws_s3_bucket.audit.arn,
      "${aws_s3_bucket.audit.arn}/*",
    ]
    condition {
      test     = "Bool"
      variable = "aws:SecureTransport"
      values   = ["false"]
    }
  }
}

resource "aws_s3_bucket_policy" "audit" {
  bucket = aws_s3_bucket.audit.id
  policy = data.aws_iam_policy_document.audit.json

  # Applying a policy while the public access block is still being created can
  # fail intermittently. Ordering them removes the race.
  depends_on = [aws_s3_bucket_public_access_block.audit]
}

# ---------------------------------------------------------------------------
# Trail. The ARN is built from parts to avoid a cycle:
# the bucket policy needs the trail ARN, the trail needs the bucket policy.
# ---------------------------------------------------------------------------
locals {
  trail_arn = "arn:${data.aws_partition.current.partition}:cloudtrail:${data.aws_region.current.region}:${data.aws_caller_identity.current.account_id}:trail/${local.trail_name}"
}

data "aws_region" "current" {}

resource "aws_cloudtrail" "audit" {
  name                          = local.trail_name
  s3_bucket_name                = aws_s3_bucket.audit.id
  include_global_service_events = true
  is_multi_region_trail         = true
  enable_log_file_validation    = true

  depends_on = [aws_s3_bucket_policy.audit]

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

output "bucket" {
  description = "Bucket containing the trail. Objects are WORM protected for the retention period."
  value       = aws_s3_bucket.audit.id
}

output "trail_arn" {
  description = "Trail ARN."
  value       = aws_cloudtrail.audit.arn
}

output "verify" {
  description = "Two commands. The second must fail with AccessDenied."
  value       = <<-EOT
    aws s3api list-object-versions --bucket ${aws_s3_bucket.audit.id} --prefix AWSLogs/ --max-items 1 --query 'Versions[0].[Key,VersionId]' --output text
    aws s3api delete-object --bucket ${aws_s3_bucket.audit.id} --key <Key from above> --version-id <VersionId from above>
  EOT
}
