module "default_tags" {
  source             = "git@github.com:theorchard/terraform-default-tags.git//?ref=2.0.0"
  environment        = var.environment
  application_family = var.application_family
  team_name          = var.team_name
}

provider "aws" {
  region = var.aws_region

  default_tags {
    tags = module.default_tags.tags
  }
}

data "aws_caller_identity" "current" {}

# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "qa-permissions-platform-terraform-state"
    key     = "qa/terraform-aws-waf-logging/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

data "aws_iam_policy_document" "bucket_policy" {
  statement {
    sid = "AWSLogDeliveryWrite"

    principals {
      type        = "Service"
      identifiers = ["delivery.logs.amazonaws.com"]
    }

    actions = [
      "s3:PutObject",
    ]

    resources = [
      "${module.waf_log_bucket.s3_bucket_arn_output}/*"
    ]

    condition {
      test     = "StringEquals"
      variable = "s3:x-amz-acl"

      values = ["bucket-owner-full-control"]
    }

    condition {
      test     = "StringEquals"
      variable = "aws:SourceAccount"

      values = [data.aws_caller_identity.current.account_id]
    }

    condition {
      test     = "ArnLike"
      variable = "aws:SourceArn"

      values = ["arn:aws:logs:${var.aws_region}:${data.aws_caller_identity.current.account_id}:*"]
    }
  }

  statement {
    sid = "AWSLogDeliveryAclCheck"

    principals {
      type        = "Service"
      identifiers = ["delivery.logs.amazonaws.com"]
    }

    actions = [
      "s3:GetBucketAcl",
    ]

    resources = [
      module.waf_log_bucket.s3_bucket_arn_output,
    ]

    condition {
      test     = "StringEquals"
      variable = "aws:SourceAccount"

      values = [data.aws_caller_identity.current.account_id]
    }

    condition {
      test     = "ArnLike"
      variable = "aws:SourceArn"

      values = ["arn:aws:logs:${var.aws_region}:${data.aws_caller_identity.current.account_id}:*"]
    }
  }
}

module "waf_log_bucket" {
  source              = "git@github.com:theorchard/terraform-s3.git//modules/s3_bucket?ref=3.10.2"
  custom_bucket_name  = "aws-waf-logs-${var.environment}-${var.account_group}"
  env                 = var.environment
  bucket_name         = var.account_group
  application_family  = var.application_family
  s3_read_only_policy = false

  apply_server_side_encryption_by_default = {
    sse_algorithm = "AES256"
  }

  bucket_policy_overrides = [
    data.aws_iam_policy_document.bucket_policy.json,
  ]

  lifecycle_rules_options_noncurrent_version_expiration = [
    {
      prefix  = "" # Using "" will lifecyle the whole bucket.
      enabled = true
      days    = 30
    },
  ]

  lifecycle_rules_options_current_version_expiration = [
    {
      prefix  = "" # Using "" will lifecyle the whole bucket.
      enabled = true
      days    = 60
    },

  ]

  lifecycle_rules_abort_incomplete_multipart_upload_days = [
    {
      prefix  = "" # Using "" will lifecyle the whole bucket.
      enabled = true
      days    = 3
    },
  ]
}

data "aws_iam_policy_document" "kms_data_policy" {
  # checkov:skip=CKV_AWS_109:It is a KMS key policy, so it applies only to a specific key. This policy allows GSIRT to access the key using IAM policies for decrypting AWS WAF logs. GSIRT uses `<env>-gsirt-waf-logs-access-policy` while any other access is forbidden by `<env>-orchard-shared-iam-deny-policy`.
  # checkov:skip=CKV_AWS_111:The same as above.

  version = "2012-10-17"
  statement {
    sid    = "Enable IAM User Permissions"
    effect = "Allow"
    principals {
      type        = "AWS"
      identifiers = ["arn:aws:iam::${data.aws_caller_identity.current.account_id}:root"]
    }
    actions   = ["kms:*"]
    resources = ["*"]
  }

  statement {
    sid    = "Allow sns and s3 to use kms key"
    effect = "Allow"
    principals {
      type        = "Service"
      identifiers = ["s3.amazonaws.com", "sns.amazonaws.com"]
    }
    actions   = ["kms:GenerateDataKey", "kms:Decrypt"]
    resources = ["arn:aws:kms:${var.aws_region}:${data.aws_caller_identity.current.account_id}:key/*"]
  }
}

resource "aws_kms_key" "aws_waf_logging_kms_key" {
  description = "${var.environment}-${var.account_group}-kms-key"
  policy      = data.aws_iam_policy_document.kms_data_policy.json

  enable_key_rotation = true

  tags = {
    environment        = var.environment
    service_name       = var.account_group
    application_family = var.application_family
    terraformed        = "true"
  }
}

resource "aws_kms_alias" "aws_waf_logging_kms_key_alias" {
  name          = "alias/${var.environment}-${var.account_group}-data-key"
  target_key_id = aws_kms_key.aws_waf_logging_kms_key.key_id
}

# Create sqs with dlq for WAF logging
module "aws_waf_sqs" {
  source = "git@github.com:theorchard/terraform-sqs.git?ref=2.5.0"

  environment                          = var.environment
  queue_name                           = "${var.account_group}-waf-logs"
  sqs_kms_master_key_id                = aws_kms_alias.aws_waf_logging_kms_key_alias.name
  sqs_delay_seconds                    = 10
  sqs_max_message_size                 = 2048
  sqs_message_retention_seconds        = 86400
  sqs_receive_wait_time_seconds        = 10
  sqs_deadletter_enabled               = "true"
  deadletter_max_receive_count         = 200
  deadletter_delay_seconds             = 10
  deadletter_max_message_size          = 2048
  deadletter_message_retention_seconds = 86400
  deadletter_receive_wait_time_seconds = 10
  application_family                   = var.application_family
}

data "aws_iam_policy_document" "sqs_queue_policy" {
  statement {
    principals {
      type        = "AWS"
      identifiers = ["*"]
    }

    actions = [
      "sqs:SendMessage",
    ]

    resources = [
      module.aws_waf_sqs.queue_arn,
    ]

    condition {
      test     = "ArnLike"
      variable = "aws:SourceArn"

      values = [aws_sns_topic.topic.arn]
    }
  }
}

resource "aws_sqs_queue_policy" "aws_waf_logging_access_policy" {
  queue_url = module.aws_waf_sqs.queue_url
  policy    = data.aws_iam_policy_document.sqs_queue_policy.json
}

data "aws_iam_policy_document" "sns_topic_policy" {
  statement {
    principals {
      type        = "Service"
      identifiers = ["s3.amazonaws.com"]
    }

    actions = [
      "sns:Publish",
    ]

    resources = [
      "arn:aws:sns:*:*:${var.environment}-${var.account_group}-waf-logs",
    ]

    condition {
      test     = "ArnLike"
      variable = "aws:SourceArn"

      values = [module.waf_log_bucket.s3_bucket_arn_output]
    }
  }
}

resource "aws_sns_topic" "topic" {
  name                          = "${var.environment}-${var.account_group}-waf-logs"
  kms_master_key_id             = aws_kms_key.aws_waf_logging_kms_key.key_id
  sqs_failure_feedback_role_arn = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/SNSFailureFeedback"
  sqs_success_feedback_role_arn = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/SNSSuccessFeedback"
  delivery_policy               = ""
  policy                        = data.aws_iam_policy_document.sns_topic_policy.json

  tags = {
    environment        = var.environment
    service_name       = var.account_group
    application_family = var.application_family
    terraformed        = "true"
  }
}

# Subscribe sns topic to sqs endpoint
resource "aws_sns_topic_subscription" "aws_waf_sqs_target" {
  topic_arn              = aws_sns_topic.topic.arn
  protocol               = "sqs"
  endpoint               = module.aws_waf_sqs.queue_arn
  endpoint_auto_confirms = true
}

resource "aws_s3_bucket_notification" "bucket_notification" {
  bucket = module.waf_log_bucket.s3_bucket_name_output

  topic {
    topic_arn = aws_sns_topic.topic.arn
    events    = ["s3:ObjectCreated:*"]
  }
}

data "aws_iam_policy_document" "aws_waf_logs_networking_policy_document" {
  statement {
    effect = "Allow"

    resources = [
      "${module.waf_log_bucket.s3_bucket_arn_output}/*",
    ]

    actions = [
      "s3:GetObject",
      "s3:GetObjectVersion",
    ]
  }

  statement {
    effect = "Allow"

    resources = [
      module.waf_log_bucket.s3_bucket_arn_output,
    ]

    actions = [
      "s3:ListBucket",
    ]
  }

  statement {
    effect    = "Allow"
    resources = [module.aws_waf_sqs.queue_arn]

    actions = [
      "sqs:ChangeMessageVisibility",
      "sqs:DeleteMessage",
      "sqs:GetQueueAttributes",
      "sqs:GetQueueUrl",
      "sqs:ListDeadLetterSourceQueues",
      "sqs:ListQueueTags",
      "sqs:ReceiveMessage",
    ]
  }

  statement {
    effect    = "Allow"
    resources = ["*"]
    actions   = ["sqs:ListQueues", ]
  }

  statement {
    effect    = "Allow"
    resources = [aws_kms_key.aws_waf_logging_kms_key.arn]

    actions = [
      "kms:GenerateDataKey",
      "kms:Decrypt",
    ]
  }
}

# Create policy for GSIRT AWS WAF LOGS
# Should be attached to GSIRT_AWS_Monitoring_Role
resource "aws_iam_policy" "aws_waf_logs_networking_policy" {
  name   = "${var.environment}-gsirt-waf-logs-access-policy"
  policy = data.aws_iam_policy_document.aws_waf_logs_networking_policy_document.json

  tags = {
    environment        = var.environment
    service_name       = var.account_group
    application_family = var.application_family
    terraformed        = "true"
  }
}

# Datadog lambda SNS subscription has been moved to terraform-infra in the datadog-forwarder directory
