data "aws_caller_identity" "current" {}

# ---------------------------------------------------------------------------
# Buckets: data (the demo object), code (the agent .zip), trail (CloudTrail)
# ---------------------------------------------------------------------------

resource "aws_s3_bucket" "this" {
  for_each = toset(["data", "code", "trail"])

  bucket_prefix = "${local.name}-${each.key}-"
  force_destroy = true
}

resource "aws_s3_bucket_public_access_block" "this" {
  for_each = aws_s3_bucket.this

  bucket                  = each.value.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

resource "aws_s3_bucket_versioning" "this" {
  for_each = aws_s3_bucket.this

  bucket = each.value.id

  versioning_configuration {
    status = "Enabled"
  }
}

# SSE-S3 rather than a KMS key, so that an AccessDenied in the demo can only
# come from the bucket policy and never from a key policy.
resource "aws_s3_bucket_server_side_encryption_configuration" "this" {
  for_each = aws_s3_bucket.this

  bucket = each.value.id

  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }
  }
}

resource "aws_s3_bucket_lifecycle_configuration" "this" {
  for_each = aws_s3_bucket.this

  bucket = each.value.id

  rule {
    id     = "housekeeping"
    status = "Enabled"

    filter {}

    abort_incomplete_multipart_upload {
      days_after_initiation = 1
    }

    noncurrent_version_expiration {
      noncurrent_days = 7
    }
  }

  depends_on = [aws_s3_bucket_versioning.this]
}

locals {
  bucket_statements = {
    # The three statements from the AgentCore Runtime guide: allow the execution
    # role when the call carries allowed_agent's identity from this provider,
    # and deny the role otherwise. The Deny statements are what stop the other
    # agent and the role's plain credentials, because the role's own policy
    # already grants s3:GetObject.
    data = [
      {
        Sid       = "AllowAgentA"
        Effect    = "Allow"
        Principal = { AWS = aws_iam_role.runtime.arn }
        Action    = "s3:GetObject"
        Resource  = "${aws_s3_bucket.this["data"].arn}/*"
        Condition = {
          StringLike   = { "aws:OriginIdentity/Subject" = local.allowed_subject }
          StringEquals = { "aws:OriginIdentity/Issuer" = local.wi_provider_arn }
        }
      },
      {
        Sid       = "DenyRoleWithoutAgentA"
        Effect    = "Deny"
        Principal = { AWS = aws_iam_role.runtime.arn }
        Action    = "s3:GetObject"
        Resource  = "${aws_s3_bucket.this["data"].arn}/*"
        Condition = {
          StringNotLike = { "aws:OriginIdentity/Subject" = local.allowed_subject }
        }
      },
      {
        Sid       = "DenyRoleWithOtherProvider"
        Effect    = "Deny"
        Principal = { AWS = aws_iam_role.runtime.arn }
        Action    = "s3:GetObject"
        Resource  = "${aws_s3_bucket.this["data"].arn}/*"
        Condition = {
          StringNotEquals = { "aws:OriginIdentity/Issuer" = local.wi_provider_arn }
        }
      },
    ]

    code = []

    trail = [
      {
        Sid       = "CloudTrailAclCheck"
        Effect    = "Allow"
        Principal = { Service = "cloudtrail.amazonaws.com" }
        Action    = "s3:GetBucketAcl"
        Resource  = aws_s3_bucket.this["trail"].arn
        Condition = {
          StringEquals = { "aws:SourceArn" = local.trail_arn }
        }
      },
      {
        Sid       = "CloudTrailWrite"
        Effect    = "Allow"
        Principal = { Service = "cloudtrail.amazonaws.com" }
        Action    = "s3:PutObject"
        Resource  = "${aws_s3_bucket.this["trail"].arn}/AWSLogs/${local.account_id}/*"
        Condition = {
          StringEquals = {
            "aws:SourceArn" = local.trail_arn
            "s3:x-amz-acl"  = "bucket-owner-full-control"
          }
        }
      },
    ]
  }
}

resource "aws_s3_bucket_policy" "this" {
  for_each = aws_s3_bucket.this

  bucket = each.value.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = concat(local.bucket_statements[each.key], [
      {
        Sid       = "DenyInsecureTransport"
        Effect    = "Deny"
        Principal = "*"
        Action    = "s3:*"
        Resource  = [each.value.arn, "${each.value.arn}/*"]
        Condition = {
          Bool = { "aws:SecureTransport" = "false" }
        }
      },
    ])
  })

  depends_on = [aws_s3_bucket_public_access_block.this]
}

resource "aws_s3_object" "report" {
  bucket       = aws_s3_bucket.this["data"].id
  key          = local.demo_key
  content      = "Q4 forecast, confidential: only ${local.allowed_agent} may read this.\n"
  content_type = "text/plain"
}

# ---------------------------------------------------------------------------
# Execution role shared by both runtimes
# ---------------------------------------------------------------------------

resource "aws_iam_role" "runtime" {
  name = "${local.name}-runtime"

  # The trust policy from the AgentCore Runtime guide. Agent and workload
  # identity needs no change to it.
  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Sid       = "AssumeRolePolicy"
      Effect    = "Allow"
      Principal = { Service = "bedrock-agentcore.amazonaws.com" }
      Action    = "sts:AssumeRole"
      Condition = {
        StringEquals = { "aws:SourceAccount" = local.account_id }
        ArnLike      = { "aws:SourceArn" = "arn:aws:bedrock-agentcore:${var.region}:${local.account_id}:*" }
      }
    }]
  })
}

resource "aws_iam_role_policy" "runtime" {
  name = "runtime"
  role = aws_iam_role.runtime.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        # Both agents get the same grant. Only the bucket policy tells them apart.
        Sid      = "ReadDemoObject"
        Effect   = "Allow"
        Action   = "s3:GetObject"
        Resource = "${aws_s3_bucket.this["data"].arn}/*"
      },
      {
        Sid      = "ReadDeploymentPackage"
        Effect   = "Allow"
        Action   = "s3:GetObject"
        Resource = "${aws_s3_bucket.this["code"].arn}/*"
      },
      {
        Sid      = "RuntimeLogGroups"
        Effect   = "Allow"
        Action   = ["logs:DescribeLogStreams", "logs:CreateLogGroup"]
        Resource = "arn:aws:logs:${var.region}:${local.account_id}:log-group:/aws/bedrock-agentcore/runtimes/*"
      },
      {
        Sid      = "RuntimeLogResourcePolicy"
        Effect   = "Allow"
        Action   = "logs:PutResourcePolicy"
        Resource = [for a in local.agent_names : "arn:aws:logs:${var.region}:${local.account_id}:log-group:/aws/bedrock-agentcore/runtimes/${a}-*"]
      },
      {
        Sid      = "DescribeLogGroups"
        Effect   = "Allow"
        Action   = "logs:DescribeLogGroups"
        Resource = "arn:aws:logs:${var.region}:${local.account_id}:log-group:*"
      },
      {
        Sid      = "RuntimeLogStreams"
        Effect   = "Allow"
        Action   = ["logs:CreateLogStream", "logs:PutLogEvents"]
        Resource = "arn:aws:logs:${var.region}:${local.account_id}:log-group:/aws/bedrock-agentcore/runtimes/*:log-stream:*"
      },
    ]
  })
}
