# ai-model-logging / aws / t0 "Quick start"
#
# Records every Bedrock model call in this Region, with its prompt and
# response, in a CloudWatch log group. Images, documents, and bodies over
# 100 KB go to an S3 bucket. Five alarms watch the trail: logging changed,
# logging checked, model access turned on, guardrails changed, and a Bedrock
# API key created. Two more fire when Bedrock fails to deliver a record.
#
# Needs a multi-region CloudTrail trail that delivers management events, read
# and write, to CloudWatch Logs, such as the Standard audit log template
# builds. logging-checked watches a read event. Apply in that log group's
# Region. Invocation logging covers this Region only.
#
# Change the two values below, then:
#   terraform init && terraform apply
#   Confirm the subscription in the email SNS sends.
#
# Terraform reads the logging configuration on every plan, which is the call
# logging-checked watches, so expect that alarm after a plan. terraform
# destroy calls DeleteModelInvocationLoggingConfiguration, the call
# logging-changed watches.
#
# Verify: aws bedrock get-model-invocation-logging-configuration
# The logging-checked alarm emails within about ten minutes.

locals {
  trail_log_group = "your-cloudtrail-log-group"   # change me
  alert_email     = "security-alerts@example.com" # change me

  account   = data.aws_caller_identity.current.account_id
  partition = data.aws_partition.current.partition
  region    = data.aws_region.current.region

  # Bedrock's own calls from this account and Region, the two conditions AWS
  # gives for the delivery role and the bucket policy.
  bedrock_source_arn = "arn:${local.partition}:bedrock:${local.region}:${local.account}:*"

  # CloudWatch filter patterns, one per detection, each under the 1,024
  # character limit. They read the trail's log group, which contains every
  # Region's events.
  detections = {
    # Logging redirected, narrowed, or switched off. A Put can point the
    # records somewhere else or drop a data type, so it alarms with Delete.
    logging-changed = {
      pattern = join("", [
        "{ ($.eventSource = \"bedrock.amazonaws.com\") && (($.eventName = \"PutModelInvocationLoggingConfiguration\") ",
        "|| ($.eventName = \"DeleteModelInvocationLoggingConfiguration\")) }",
      ])
      description = "Bedrock model invocation logging was changed or deleted."
    }
    # Stolen keys check whether model calls are logged before using them.
    # Three published intrusions show it: Sysdig 2024-05, Permiso 2024-10, and
    # Sysdig 2026-02. The console's logging settings page reads it too.
    logging-checked = {
      pattern     = "{ ($.eventSource = \"bedrock.amazonaws.com\") && ($.eventName = \"GetModelInvocationLoggingConfiguration\") }"
      description = "Someone read the Bedrock logging configuration, as stolen keys do before using models."
    }
    # Model access turned on: the Anthropic use case form, a model agreement,
    # and the console-only entitlement call, each seen in LLMjacking cases.
    # AcceptAgreementRequest is the Marketplace step Sysdig saw in 2026-02;
    # it accepts any Marketplace offer. No published sample shows the event
    # source of the last two, so this filter matches on name alone.
    model-access = {
      pattern = join("", [
        "{ ($.eventName = \"PutUseCaseForModelAccess\") || ($.eventName = \"CreateFoundationModelAgreement\") ",
        "|| ($.eventName = \"PutFoundationModelEntitlement\") || ($.eventName = \"AcceptAgreementRequest\") }",
      ])
      description = "Someone turned on access to a Bedrock model or accepted a Marketplace offer."
    }
    # A guardrail changed or deleted, or account-wide enforcement set or
    # removed. The names are the API's operations. No published CloudTrail
    # sample shows them, so test this once on a scratch guardrail.
    guardrails-weakened = {
      pattern = join("", [
        "{ ($.eventSource = \"bedrock.amazonaws.com\") && (($.eventName = \"UpdateGuardrail\") ",
        "|| ($.eventName = \"DeleteGuardrail\") || ($.eventName = \"PutEnforcedGuardrailConfiguration\") ",
        "|| ($.eventName = \"DeleteEnforcedGuardrailConfiguration\")) }",
      ])
      description = "A Bedrock guardrail or its account-wide enforcement was changed or removed."
    }
    # A long-term Bedrock API key. Short-term keys are made on the client and
    # never reach CloudTrail; only their use does.
    api-key-created = {
      pattern = join("", [
        "{ ($.eventSource = \"iam.amazonaws.com\") && ($.eventName = \"CreateServiceSpecificCredential\") ",
        "&& ($.requestParameters.serviceName = \"bedrock.amazonaws.com\") }",
      ])
      description = "Someone created a long-term Bedrock API key."
    }
  }

  # Bedrock emits these for each failed delivery. AWS lists them under
  # "Across all model IDs", the console's name for the metric with no
  # dimension, so the alarms name none.
  delivery = {
    cloudwatch = "ModelInvocationLogsCloudWatchDeliveryFailure"
    large-data = "ModelInvocationLargeDataS3DeliveryFailure"
  }
}

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

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

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

# ---------------------------------------------------------------------------
# The record. It carries full prompts and responses, so treat both stores as
# sensitive data and keep read access tight.
# ---------------------------------------------------------------------------
resource "aws_cloudwatch_log_group" "invocations" {
  name              = "/aws/bedrock/model-invocations"
  retention_in_days = 365
}

resource "aws_s3_bucket" "large_data" {
  bucket_prefix = "ai-model-logging-"
  force_destroy = false
}

# Bedrock's bucket policy only takes effect with ACLs disabled.
resource "aws_s3_bucket_ownership_controls" "large_data" {
  bucket = aws_s3_bucket.large_data.id
  rule {
    object_ownership = "BucketOwnerEnforced"
  }
}

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

resource "aws_s3_bucket_versioning" "large_data" {
  bucket = aws_s3_bucket.large_data.id
  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_server_side_encryption_configuration" "large_data" {
  bucket = aws_s3_bucket.large_data.id
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }
  }
}

# Large data lasts as long as the log records that point to it.
resource "aws_s3_bucket_lifecycle_configuration" "large_data" {
  bucket     = aws_s3_bucket.large_data.id
  depends_on = [aws_s3_bucket_versioning.large_data]

  rule {
    id     = "expire-large-data"
    status = "Enabled"
    filter {}
    expiration {
      days = 365
    }
    noncurrent_version_expiration {
      noncurrent_days = 7
    }
    abort_incomplete_multipart_upload {
      days_after_initiation = 7
    }
  }
}

# AWS documents the key path for invocation records and gives none for large
# data objects, so this statement covers every object in the bucket. Only
# Bedrock calls from this account and Region meet the two conditions.
resource "aws_s3_bucket_policy" "large_data" {
  bucket = aws_s3_bucket.large_data.id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Sid       = "AmazonBedrockLogsWrite"
      Effect    = "Allow"
      Principal = { Service = "bedrock.amazonaws.com" }
      Action    = "s3:PutObject"
      Resource  = "${aws_s3_bucket.large_data.arn}/*"
      Condition = {
        StringEquals = { "aws:SourceAccount" = local.account }
        ArnLike      = { "aws:SourceArn" = local.bedrock_source_arn }
      }
    }]
  })
  depends_on = [aws_s3_bucket_public_access_block.large_data, aws_s3_bucket_ownership_controls.large_data]
}

# The role Bedrock assumes to write to the log group, scoped as AWS documents
# it: one log stream, and only Bedrock acting for this account and Region.
resource "aws_iam_role" "delivery" {
  name = "ai-model-logging-delivery"
  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { Service = "bedrock.amazonaws.com" }
      Action    = "sts:AssumeRole"
      Condition = {
        StringEquals = { "aws:SourceAccount" = local.account }
        ArnLike      = { "aws:SourceArn" = local.bedrock_source_arn }
      }
    }]
  })
}

resource "aws_iam_role_policy" "delivery" {
  name = "delivery"
  role = aws_iam_role.delivery.id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect   = "Allow"
      Action   = ["logs:CreateLogStream", "logs:PutLogEvents"]
      Resource = "${aws_cloudwatch_log_group.invocations.arn}:log-stream:aws/bedrock/modelinvocations"
    }]
  })
}

# One configuration per account and Region. Bedrock checks the role against
# the log group when it is set, and the provider retries while a new role
# propagates.
resource "aws_bedrock_model_invocation_logging_configuration" "this" {
  logging_config {
    # The provider turns all four on when they are left out. It has no flag
    # for audio, so audio logging is whatever the API applies when the
    # setting is absent; AWS documents no default.
    text_data_delivery_enabled      = true
    image_data_delivery_enabled     = true
    embedding_data_delivery_enabled = false
    video_data_delivery_enabled     = false

    cloudwatch_config {
      log_group_name = aws_cloudwatch_log_group.invocations.name
      role_arn       = aws_iam_role.delivery.arn
      large_data_delivery_s3_config {
        bucket_name = aws_s3_bucket.large_data.id
        key_prefix  = "large-data"
      }
    }
  }

  depends_on = [aws_iam_role_policy.delivery, aws_s3_bucket_policy.large_data]
}

# ---------------------------------------------------------------------------
# Alerts
# ---------------------------------------------------------------------------
resource "aws_sns_topic" "alerts" {
  name = "ai-model-logging"
}

resource "aws_sns_topic_subscription" "email" {
  topic_arn = aws_sns_topic.alerts.arn
  protocol  = "email"
  endpoint  = local.alert_email
}

resource "aws_cloudwatch_log_metric_filter" "detection" {
  for_each       = local.detections
  name           = "ai-model-logging-${each.key}"
  log_group_name = local.trail_log_group
  pattern        = each.value.pattern
  metric_transformation {
    name          = "AIModelLogging-${each.key}"
    namespace     = "Security/AIModelLogging"
    value         = "1"
    default_value = "0"
  }
}

resource "aws_cloudwatch_metric_alarm" "detection" {
  for_each            = local.detections
  alarm_name          = "ai-model-logging-${each.key}"
  alarm_description   = "${each.value.description} In Logs Insights on ${local.trail_log_group}, filter on the event names in the ai-model-logging-${each.key} metric filter to see who and what."
  namespace           = "Security/AIModelLogging"
  metric_name         = "AIModelLogging-${each.key}"
  statistic           = "Sum"
  period              = 300
  evaluation_periods  = 1
  threshold           = 1
  comparison_operator = "GreaterThanOrEqualToThreshold"
  treat_missing_data  = "notBreaching"
  alarm_actions       = [aws_sns_topic.alerts.arn]
  depends_on          = [aws_cloudwatch_log_metric_filter.detection]
}

resource "aws_cloudwatch_metric_alarm" "delivery_failing" {
  for_each            = local.delivery
  alarm_name          = "ai-model-logging-delivery-failing-${each.key}"
  alarm_description   = "Bedrock could not deliver model invocation records (${each.value}). Check the delivery role, the bucket policy, and that the log group and bucket still exist."
  namespace           = "AWS/Bedrock"
  metric_name         = each.value
  statistic           = "Sum"
  period              = 300
  evaluation_periods  = 1
  threshold           = 1
  comparison_operator = "GreaterThanOrEqualToThreshold"
  treat_missing_data  = "notBreaching"
  alarm_actions       = [aws_sns_topic.alerts.arn]
}

output "verify" {
  description = "The drill."
  value       = <<-EOT
    aws bedrock get-model-invocation-logging-configuration --region ${local.region}
    The ai-model-logging-logging-checked alarm goes to ALARM and the email arrives within about ten minutes.
    aws bedrock-runtime converse --region ${local.region} --model-id <a model ID you already use> --messages '[{"role":"user","content":[{"text":"ping"}]}]'
    aws logs tail ${aws_cloudwatch_log_group.invocations.name} --region ${local.region} --since 15m    # the call, with its prompt and response
    aws cloudwatch describe-alarms --alarm-name-prefix ai-model-logging- --query 'MetricAlarms[].[AlarmName,StateValue]'
  EOT
}
