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

provider "aws" {
  region = var.aws_region

  default_tags {
    tags = module.default_tags.tags
  }
}

provider "aws" {
  region  = var.aws_region
  profile = "networking"
  alias   = "networking"

  default_tags {
    tags = module.default_tags.tags
  }
}

# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "prod/ows-grass-public/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

data "aws_caller_identity" "current" {}

data "aws_secretsmanager_secret_version" "loggly_handler_async" {
  secret_id = "${var.environment}/ows-grass/LOGGER_HANDLER_ASYNC"
}

data "aws_secretsmanager_secret_version" "session_duration" {
  secret_id = "${var.environment}/ows-grass/SESSION_DURATION"
}

module "vpc_info" {
  source = "git@github.com:theorchard/terraform-vpc-info.git//?ref=3.3.0"

  environment = var.environment
}

data "aws_acm_certificate" "theorchard_io" {
  domain   = "*.theorchard.io"
  statuses = ["ISSUED"]
}

data "aws_route53_zone" "route53_zone_networking" {
  provider = aws.networking

  name = "theorchard.io"
}

data "aws_subnet" "private_subnets" {
  for_each = toset(["prod_ows_grass01", "prod_ows_grass02", "prod_ows_grass03"])
  filter {
    name   = "tag:Name"
    values = [each.key]
  }
}

data "aws_subnet" "public_subnets" {
  for_each = toset(["public01", "public02", "prod_public_subnet_3"])
  filter {
    name   = "tag:Name"
    values = [each.key]
  }
}

resource "aws_wafv2_rule_group" "grass_post_body_size" {
  name        = "${var.environment}-${var.service_name}-custom-rule-group"
  description = "${var.environment}-${var.service_name} custom rule group"
  scope       = "REGIONAL"
  capacity    = 500

  rule {
    name     = "post-body-size-rule"
    priority = 1

    action {
      block {}
    }

    statement {

      size_constraint_statement {

        comparison_operator = "GT"

        field_to_match {
          body {}
        }

        size = 1024000

        text_transformation {
          priority = 1
          type     = "COMPRESS_WHITE_SPACE"
        }
      }
    }

    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name                = "post-body-size-rule"
      sampled_requests_enabled   = true
    }
  }

  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name                = "post-body-size-rule-group"
    sampled_requests_enabled   = true
  }

  tags = {
    Name         = "${var.environment}-${var.service_name}-custom-rule-group"
    terraformed  = "true"
    environment  = var.environment
    service_name = var.service_name
  }
}

resource "aws_wafv2_ip_set" "blocked_ips" {
  name               = "${var.environment}-${var.service_name}-blocked-ips"
  description        = "${var.environment}-${var.service_name}-blocked-ips"
  scope              = "REGIONAL"
  ip_address_version = "IPV4"
  addresses          = var.blocked_ip_addresses
}

# Create both blocking and count-only WAFs for grass temporarily, to get request baseline before cutting over to blocking.
# It lives here instead of in the ows-grass directory because this grass is the long-term service, whereas the private ows-grass
# service and directory are only required and utilized by workstation as a private proxy.
module "ows_grass_waf" {
  source            = "git@github.com:theorchard/terraform-aws-waf.git//?ref=2.0.2"
  environment       = var.environment
  service_name      = var.service_name
  aws_region        = var.aws_region
  count_waf_enabled = true
  block_waf_enabled = true
  excluded_rules = [
    "CrossSiteScripting_BODY",
    "EC2MetaDataSSRF_BODY",
    "NoUserAgent_HEADER",
    "SizeRestrictions_BODY",
  ]

  custom_rules = [
    {
      name                       = "${var.environment}-${var.service_name}-ip-block-rule-group"
      rule_group_arn             = aws_wafv2_rule_group.ip_block_rule_group.arn
      priority                   = 3
      cloudwatch_metrics_enabled = true
      metric_name                = "${var.environment}-${var.service_name}-ip-block-rule-group"
      sampled_requests_enabled   = true
    },
    {
      name                       = "${var.environment}-${var.service_name}-auth-headers-rate-limit-group"
      rule_group_arn             = aws_wafv2_rule_group.auth_headers_rate_limit_rule_group.arn
      priority                   = 11
      cloudwatch_metrics_enabled = true
      metric_name                = "${var.environment}-${var.service_name}-auth-headers-rate-limit-group"
      sampled_requests_enabled   = true
    },
    {
      name                       = "${var.environment}-${var.service_name}-waf-custom-rules-group"
      rule_group_arn             = aws_wafv2_rule_group.rate_limit_rule_group.arn
      priority                   = 20
      cloudwatch_metrics_enabled = true
      metric_name                = "waf-block-acl"
      sampled_requests_enabled   = true
    },
  ]
}

data "aws_wafv2_ip_set" "nat" {
  name  = "nat"
  scope = "REGIONAL"
}

data "aws_wafv2_ip_set" "ny_office" {
  name  = "ny_office"
  scope = "REGIONAL"
}

data "aws_wafv2_ip_set" "uk_office" {
  name  = "uk_office"
  scope = "REGIONAL"
}

resource "aws_wafv2_rule_group" "rate_limit_rule_group" {
  name        = "${var.environment}-${var.service_name}-rate-limiting-rules-group"
  description = "An rule group for rate limiting"
  scope       = "REGIONAL"
  capacity    = 500

  rule {
    name     = "rate-limit-whitelist"
    priority = 1

    action {
      allow {}
    }

    statement {
      or_statement {
        statement {
          ip_set_reference_statement {
            arn = data.aws_wafv2_ip_set.ny_office.arn
          }
        }

        statement {
          ip_set_reference_statement {
            arn = data.aws_wafv2_ip_set.uk_office.arn
          }
        }

        statement {
          ip_set_reference_statement {
            arn = data.aws_wafv2_ip_set.nat.arn
          }
        }
      }
    }

    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name                = "rate-limiting-whitelist"
      sampled_requests_enabled   = true
    }
  }

  rule {
    name     = "rate-limit-count"
    priority = 10

    action {
      count {}
    }

    statement {
      rate_based_statement {
        limit                 = 200
        aggregate_key_type    = "IP"
        evaluation_window_sec = "60"
      }
    }

    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name                = "rate-limiting-count"
      sampled_requests_enabled   = true
    }
  }

  rule {
    name     = "rate-limit-block"
    priority = 20

    action {
      count {}
    }

    statement {
      rate_based_statement {
        limit                 = 400
        aggregate_key_type    = "IP"
        evaluation_window_sec = "60"
      }
    }

    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name                = "rate-limiting-block"
      sampled_requests_enabled   = true
    }
  }

  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name                = "rate-limiting-rule"
    sampled_requests_enabled   = true
  }
}

resource "aws_wafv2_rule_group" "ip_block_rule_group" {
  name        = "${var.environment}-${var.service_name}-ip-block-rules-group"
  description = "An rule group for IP block rules"
  scope       = "REGIONAL"
  capacity    = 50

  rule {
    name     = "ip-block-rule"
    priority = 1

    action {
      block {}
    }

    statement {
      ip_set_reference_statement {
        arn = aws_wafv2_ip_set.blocked_ips.arn
      }
    }

    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name                = "${var.environment}-${var.service_name}-ip-block-rule"
      sampled_requests_enabled   = true
    }
  }

  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name                = "${var.environment}-${var.service_name}-ip-block-rule-group"
    sampled_requests_enabled   = true
  }
}

resource "aws_wafv2_rule_group" "auth_headers_rate_limit_rule_group" {
  name        = "${var.environment}-${var.service_name}-auth-headers-rate-limit-group"
  description = "An rule group for auth headers rate limiting"
  scope       = "REGIONAL"
  capacity    = 500

  rule {
    name     = "RateLimit-Orchard-Profile-Id"
    priority = 10

    action {
      count {}
    }

    statement {
      rate_based_statement {
        limit                 = 700
        aggregate_key_type    = "CUSTOM_KEYS"
        evaluation_window_sec = "120"

        custom_key {
          header {
            name = "orchard-profile-id"
            text_transformation {
              priority = 0
              type     = "LOWERCASE"
            }
          }
        }
      }
    }

    rule_label {
      name = "custom:RateLimit-Orchard-Profile-Id"
    }

    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name                = "RateLimitByOrchardProfileId"
      sampled_requests_enabled   = true
    }
  }

  rule {
    name     = "RateLimit-Authorization"
    priority = 20

    action {
      count {}
    }

    statement {
      rate_based_statement {
        limit                 = 700
        aggregate_key_type    = "CUSTOM_KEYS"
        evaluation_window_sec = "120"

        custom_key {
          header {
            name = "Authorization"
            text_transformation {
              priority = 0
              type     = "LOWERCASE"
            }
          }
        }
      }
    }

    rule_label {
      name = "custom:RateLimit-Authorization"
    }

    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name                = "RateLimitByAuthorization"
      sampled_requests_enabled   = true
    }
  }

  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name                = "${var.environment}-${var.service_name}-auth-headers-rate-limit-group"
    sampled_requests_enabled   = true
  }
}

resource "datadog_monitor" "waf-blocking-monitor" {
  message             = <<-EOT
{{#is_alert}}The ${var.environment}-${var.service_name} WAF blocked request count is higher than ${var.datadog_waf_monitor_threshold}. Notification to ${var.waf_blocking_alert_channel}"{{/is_alert}}
{{#is_alert_recovery}}The ${var.environment}-${var.service_name} WAF blocked request count is less than ${var.datadog_waf_monitor_threshold}. Notification to ${var.waf_blocking_alert_channel}"{{/is_alert_recovery}}
EOT
  name                = "${var.environment}-${var.service_name}-public WAF blocking monitor"
  type                = "query alert"
  escalation_message  = "Escalation to ${var.waf_blocking_alert_channel}"
  query               = "sum(last_5m):sum:aws.wafv2.blocked_requests{webacl:${var.environment}-${var.service_name}-waf-block, rule:${var.environment}-${var.service_name}-waf-block-acl} by {rule}.as_count() > ${var.datadog_waf_monitor_threshold}"
  notify_no_data      = false
  renotify_interval   = 60
  renotify_statuses   = ["alert"]
  evaluation_delay    = "300"
  timeout_h           = "1"
  include_tags        = true
  require_full_window = true
  notify_audit        = false
  monitor_thresholds {
    critical          = var.datadog_waf_monitor_threshold
    critical_recovery = 50
    warning           = 50
    warning_recovery  = 10
  }

  tags = concat(
    [
      "environment        = ${var.environment}",
      "service_name       = ${var.service_name}",
      "application_family = ${var.application_family}"
    ],
    [for dependent_application in var.dependent_applications : "dependent_application = ${dependent_application}"]
  )
}

resource "datadog_monitor" "waf_auth_rate_limit_monitor" {
  name                = "${var.environment}-${var.service_name} WAF Authorization header rate-limit threshold observed"
  type                = "query alert"
  message             = <<-EOT
{{#is_alert}} ${var.environment}-${var.service_name} WAF is detecting high request volume by unique Authorization headers — more than ${var.datadog_waf_monitor_threshold} counted in last 5m. Notify ${var.waf_blocking_alert_channel}{{/is_alert}}
{{#is_alert_recovery}} Authorization header request rate is back to normal. Notify ${var.waf_blocking_alert_channel}{{/is_alert_recovery}}
EOT
  escalation_message  = "Escalate to ${var.waf_blocking_alert_channel}"
  query               = "sum(last_5m):sum:aws.wafv2.counted_requests{rulegroup:${var.environment}-${var.service_name}-auth-headers-rate-limit-group,rule:ratelimitbyauthorization}.as_count() > ${var.datadog_waf_monitor_threshold}"
  notify_no_data      = false
  require_full_window = true
  evaluation_delay    = 300
  timeout_h           = 1
  renotify_interval   = 60
  renotify_statuses   = ["alert"]

  monitor_thresholds {
    critical          = var.datadog_waf_monitor_threshold
    critical_recovery = 10
    warning           = 50
    warning_recovery  = 10
  }

  tags = [
    "environment        = ${var.environment}",
    "service_name       = ${var.service_name}",
    "application_family = ${var.application_family}"
  ]
}

resource "datadog_monitor" "waf_profileid_rate_limit_monitor" {
  name                = "${var.environment}-${var.service_name} WAF orchard-profile-id rate-limit threshold observed"
  type                = "query alert"
  message             = <<-EOT
{{#is_alert}} ${var.environment}-${var.service_name} WAF is detecting high request volume by unique orchard-profile-id header — more than ${var.datadog_waf_monitor_threshold} counted in last 5m. Notify ${var.waf_blocking_alert_channel}{{/is_alert}}
{{#is_alert_recovery}} orchard-profile-id header request rate is back to normal. Notify ${var.waf_blocking_alert_channel}{{/is_alert_recovery}}
EOT
  escalation_message  = "Escalate to ${var.waf_blocking_alert_channel}"
  query               = "sum(last_5m):sum:aws.wafv2.counted_requests{rulegroup:${var.environment}-${var.service_name}-auth-headers-rate-limit-group,rule:ratelimitbyorchardprofileid}.as_count() > ${var.datadog_waf_monitor_threshold}"
  notify_no_data      = false
  require_full_window = true
  evaluation_delay    = 300
  timeout_h           = 1
  renotify_interval   = 60
  renotify_statuses   = ["alert"]

  monitor_thresholds {
    critical          = var.datadog_waf_monitor_threshold
    critical_recovery = 10
    warning           = 50
    warning_recovery  = 10
  }

  tags = [
    "environment        = ${var.environment}",
    "service_name       = ${var.service_name}",
    "application_family = ${var.application_family}"
  ]
}

module "ows_grass_public_fargate_environment" {
  source = "git@github.com:theorchard/terraform-fargate.git//?ref=6.6.0"
  # checkov:skip=ORCD_AWS_1:Grass subnets are purpose specific for ows-grass and ows-grass-public. IP space is sufficient.

  providers = {
    aws.dns = aws.networking
  }

  environment                              = var.environment
  service_name                             = "${var.service_name}-public"
  application_family                       = var.application_family
  aws_region                               = var.aws_region
  non_ecr_image                            = "${data.aws_caller_identity.current.account_id}.dkr.ecr.us-east-1.amazonaws.com/ows-grass:latest"
  commit_sha                               = "latest"
  container_port                           = "8080"
  task_type                                = "web_service"
  desired_task_count                       = 3
  minimum_capacity                         = 3
  maximum_capacity                         = 10
  task_cpu                                 = 4096
  task_memory                              = 8192
  override_route53_zone_id                 = data.aws_route53_zone.route53_zone_networking.zone_id
  load_balancer_access_logs_s3_bucket_name = "orch-elb-logs"
  vpc_id                                   = module.vpc_info.vpc_id
  load_balancer_is_internal                = false
  http_listener_enabled                    = false
  https_listener_certificate_id            = split("/", data.aws_acm_certificate.theorchard_io.arn)[1]
  custom_waf_arn                           = module.ows_grass_waf.waf_blocking_arn_output
  prod_https_listener_allow_cidr_blocks = [
    "0.0.0.0/0",
  ]

  fargate_service_subnets = [for subnet in data.aws_subnet.private_subnets : subnet.id]

  load_balancer_subnets = [for subnet in data.aws_subnet.public_subnets : subnet.id]

  iam_managed_policy_attachments = [
    "arn:aws:iam::aws:policy/CloudWatchFullAccess",
    "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/grassapi-prod",
    "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/Dynamo-prod-ows-grass-owsrequest",
    "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/S3-aws-logs-437795906767-us-east-1-prod-ows-grass-RW",
    "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/SecretsManager-prod-ows-grass-policy"
  ]

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      LOGGER_HANDLER_ASYNC = data.aws_secretsmanager_secret_version.loggly_handler_async.secret_string
    },
    {
      REDIS_HOST = module.grass_elasticache.redis_primary_endpoint_address
    },
    {
      REDIS_PORT = "6379"
    },
    {
      SEND_METRICS_TO_DD_ENABLED = "true"
    },
    {
      SESSION_DURATION = data.aws_secretsmanager_secret_version.session_duration.secret_string
    },
    {
      JWT_SERVICE_NAME = var.JWT_SERVICE_NAME
    },
    {
      JWT_SECRET_NAME = var.JWT_SECRET_NAME
    },
    {
      JWT_REFRESH_INTERVAL = var.JWT_REFRESH_INTERVAL
    },
  ]
  secrets = [
    {
      AUTH0_API_AUDIENCE = "${var.environment}/ows-grass-public/AUTH0_API_AUDIENCE"
    },
    {
      AUTH0_DOMAIN = "${var.environment}/ows-grass-public/AUTH0_DOMAIN"
    },
    {
      DB_URL = "${var.environment}/ows-grass-public/DB_URL"
    },
    {
      SENTRY_DSN = "${var.environment}/ows-grass-public/SENTRY_DSN"
    },
  ]
}

resource "aws_route53_record" "ows_grass_cname_route53_record_networking" {
  provider = aws.networking

  name    = var.service_name
  zone_id = data.aws_route53_zone.route53_zone_networking.zone_id
  type    = "CNAME"
  ttl     = 60
  records = [module.ows_grass_public_fargate_environment.fargate_service_route53_record_fqdn_output]
}

resource "aws_route53_record" "prod_ows_grass_cname_route53_record_networking" {
  provider = aws.networking

  name    = "${var.environment}-${var.service_name}"
  zone_id = data.aws_route53_zone.route53_zone_networking.zone_id
  type    = "CNAME"
  ttl     = 60
  records = [aws_route53_record.ows_grass_cname_route53_record_networking.fqdn]
}

module "grass_elasticache" {
  # checkov:skip=CKV_AWS_30:ElastiCache encryption in transit requires client library update.
  # checkov:skip=CKV_AWS_31:ElastiCache encryption in transit requires client library update.
  source = "git@github.com:theorchard/terraform-elasticache.git//?ref=4.0.2"

  providers = {
    aws.dns = aws.networking
  }

  environment                      = var.environment
  service_name                     = "${var.service_name}-public"
  application_family               = var.application_family
  cache_engine                     = "redis"
  cache_node_type                  = "cache.m6g.large"
  cache_node_count                 = "2"
  redis_engine_version             = "5.0.6"
  cache_subnet_group_name          = "prod-vpc-orchard-subnet"
  cache_parameter_group_name       = "default.redis5.0"
  vpc_id                           = module.vpc_info.vpc_id
  override_route53_zone_id         = data.aws_route53_zone.route53_zone_networking.zone_id
  cache_transit_encryption_enabled = false
  additional_cidr_blocks_enabled   = true
  additional_cidr_blocks = [
    "10.100.80.32/28",
    "10.100.80.16/28",
    "10.100.80.0/28",
  ]
}

module "fargate_service_dashboard" {
  source                            = "git@github.com:theorchard/terraform-datadog.git//modules/service?ref=6.19.0"
  environment                       = var.environment
  environment_type                  = "fargate"
  service_name                      = "${var.service_name}-public"
  critical_number_4xx               = 400
  critical_recovery_number_4xx      = 380
  warning_number_4xx                = 375
  warning_recovery_number_4xx       = 350
  ok_number_4xx                     = 100
  critical_number_5xx               = 400
  critical_recovery_number_5xx      = 380
  warning_number_5xx                = 375
  warning_recovery_number_5xx       = 350
  ok_number_5xx                     = 100
  application_family                = var.application_family
  notification_endpoints            = var.application_alert_channel
  escalation_notification_endpoints = var.application_alert_channel
  teams                             = [var.application_family]
  dependent_applications            = var.dependent_applications
}
