# ---------------------------------------------------------------------------
# Evidence: a trail that records reads and writes of the demo bucket's objects.
# S3 GetObject is a data event, so it never appears in CloudTrail Event history.
# The AssumeRole events that carry the agent identity are management events
# and are read from Event history, which needs no trail.
# ---------------------------------------------------------------------------

resource "aws_kms_key" "this" {
  description             = "${local.name}: CloudTrail log files and CloudWatch log groups"
  enable_key_rotation     = true
  deletion_window_in_days = 7
}

resource "aws_kms_alias" "this" {
  name          = "alias/${local.name}"
  target_key_id = aws_kms_key.this.key_id
}

resource "aws_kms_key_policy" "this" {
  key_id = aws_kms_key.this.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        # The default key policy statement: it hands access control for the
        # key to IAM policies in this account.
        Sid       = "AccountAdministration"
        Effect    = "Allow"
        Principal = { AWS = "arn:aws:iam::${local.account_id}:root" }
        Action    = "kms:*"
        Resource  = "*"
      },
      {
        Sid       = "CloudTrailEncrypt"
        Effect    = "Allow"
        Principal = { Service = "cloudtrail.amazonaws.com" }
        Action    = "kms:GenerateDataKey*"
        Resource  = "*"
        Condition = {
          StringEquals = { "aws:SourceArn" = local.trail_arn }
          StringLike   = { "kms:EncryptionContext:aws:cloudtrail:arn" = "arn:aws:cloudtrail:*:${local.account_id}:trail/*" }
        }
      },
      {
        Sid       = "CloudTrailDescribe"
        Effect    = "Allow"
        Principal = { Service = "cloudtrail.amazonaws.com" }
        Action    = "kms:DescribeKey"
        Resource  = "*"
        Condition = {
          StringEquals = { "aws:SourceArn" = local.trail_arn }
        }
      },
      {
        Sid       = "CloudWatchLogs"
        Effect    = "Allow"
        Principal = { Service = "logs.${var.region}.amazonaws.com" }
        Action    = ["kms:Encrypt", "kms:Decrypt", "kms:ReEncrypt*", "kms:GenerateDataKey*", "kms:DescribeKey"]
        Resource  = "*"
        Condition = {
          ArnLike = { "kms:EncryptionContext:aws:logs:arn" = "arn:aws:logs:${var.region}:${local.account_id}:log-group:/${local.name}/*" }
        }
      },
    ]
  })
}

resource "aws_cloudwatch_log_group" "trail" {
  name              = "/${local.name}/cloudtrail"
  retention_in_days = 14
  kms_key_id        = aws_kms_key.this.arn

  depends_on = [aws_kms_key_policy.this]
}

resource "aws_iam_role" "trail" {
  name = "${local.name}-cloudtrail"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { Service = "cloudtrail.amazonaws.com" }
      Action    = "sts:AssumeRole"
      Condition = {
        StringEquals = { "aws:SourceArn" = local.trail_arn }
      }
    }]
  })
}

resource "aws_iam_role_policy" "trail" {
  name = "write-trail-log-group"
  role = aws_iam_role.trail.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect   = "Allow"
      Action   = ["logs:CreateLogStream", "logs:PutLogEvents"]
      Resource = ["${aws_cloudwatch_log_group.trail.arn}:log-stream:*"]
    }]
  })
}

resource "aws_cloudtrail" "this" {
  name                          = local.name
  s3_bucket_name                = aws_s3_bucket.this["trail"].id
  kms_key_id                    = aws_kms_key.this.arn
  enable_log_file_validation    = true
  is_multi_region_trail         = false
  include_global_service_events = false
  cloud_watch_logs_group_arn    = "${aws_cloudwatch_log_group.trail.arn}:*"
  cloud_watch_logs_role_arn     = aws_iam_role.trail.arn

  # Data events for the demo bucket only. Management events stay with the
  # account's own trail, so nothing is recorded (or billed) twice.
  advanced_event_selector {
    name = "Demo bucket objects"

    field_selector {
      field  = "eventCategory"
      equals = ["Data"]
    }

    field_selector {
      field  = "resources.type"
      equals = ["AWS::S3::Object"]
    }

    field_selector {
      field       = "resources.ARN"
      starts_with = ["${aws_s3_bucket.this["data"].arn}/"]
    }
  }

  depends_on = [
    aws_s3_bucket_policy.this,
    aws_iam_role_policy.trail,
    aws_kms_key_policy.this,
  ]
}
