module "default_tags" {
  source             = "git@github.com:theorchard/terraform-default-tags.git//?ref=2.0.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
  alias   = "networking"
  profile = "networking"

  default_tags {
    tags = module.default_tags.tags
  }
}

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

data "aws_caller_identity" "current" {}

data "aws_s3_bucket" "logging_bucket_waf" {
  bucket = "aws-waf-logs-prod-tf-orcd-bucket"
}

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

  environment = var.environment
}

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

data "aws_route53_zone" "route53_zone" {
  name = "theorchard.io"
}

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

  name = "theorchard.io"
}

module "ows_service_owsrequest" {
  source = "git@github.com:theorchard/terraform-owsrequest.git//?ref=1.1.0"

  environment_name = var.environment
  service_name     = var.service_name
}

module "ows_grass_fargate_environment" {
  source = "git@github.com:theorchard/terraform-fargate.git//?ref=5.7.0"

  providers = {
    aws.dns = aws.networking
  }

  environment                              = var.environment
  service_name                             = var.service_name
  application_family                       = var.application_family
  aws_region                               = var.aws_region
  commit_sha                               = "latest"
  container_port                           = "8080"
  task_type                                = "web_service"
  desired_task_count                       = 2
  task_cpu                                 = 1024
  task_memory                              = 2048
  maximum_capacity                         = 4
  minimum_capacity                         = 2
  route53_zone_id                          = data.aws_route53_zone.route53_zone.zone_id
  load_balancer_access_logs_s3_bucket_name = "orch-elb-logs"
  https_listener_ssl_policy                = "ELBSecurityPolicy-TLS13-1-2-2021-06"
  vpc_id                                   = module.vpc_info.vpc_id
  https_listener_certificate_id            = split("/", data.aws_acm_certificate.theorchard_io.arn)[1]
  custom_waf_arn                           = module.ows_grass_waf.waf_blocking_arn_output
  qa_https_listener_allow_cidr_blocks = [
    "192.168.31.0/24",
    "192.168.32.0/24",
    "192.168.33.0/24",
    "192.168.40.0/22",
    "10.30.0.0/22",
    "10.40.0.0/22",
    "10.110.1.0/24", # qa switchboard
    "10.110.0.0/24", # qa switchboard
    "10.180.0.0/24", # qa songwhip
    "10.180.1.0/24", # qa songwhip
    "10.180.2.0/24", # qa songwhip
  ]

  https_listener_allow_prefix_list_names = [
    "vpn-sme-internal-primary",
    "sme-infosec-vm-network",
  ]

  iam_managed_policy_attachments = [
    "arn:aws:iam::aws:policy/AmazonElastiCacheFullAccess",
    "arn:aws:iam::aws:policy/CloudWatchFullAccess",
    "arn:aws:iam::437795906767:policy/grassapi-dev",
    module.ows_service_owsrequest.policy_arn_output,
  ]

  fargate_service_subnets = module.vpc_info.default_private_subnet_ids

  load_balancer_subnets = module.vpc_info.default_private_subnet_ids

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      LOGGER_HANDLER_ASYNC = var.LOGGER_HANDLER_ASYNC
    },
    {
      REDIS_HOST = module.ows_grass_elasticache.redis_primary_endpoint_address
    },
    {
      REDIS_PORT = var.REDIS_PORT
    },
    {
      SEND_METRICS_TO_DD_ENABLED = var.SEND_METRICS_TO_DD_ENABLED
    },
    {
      SESSION_DURATION = var.SESSION_DURATION
    },
    {
      JWT_SERVICE_NAME = var.JWT_SERVICE_NAME
    },
    {
      JWT_SECRET_NAME = var.JWT_SECRET_NAME
    },
    {
      JWT_REFRESH_INTERVAL = var.JWT_REFRESH_INTERVAL
    },
    {
      SENTRY_DSN = module.sentry_ows_grass_qa.sentry_key_dsn_public_output
    },
  ]

  secrets = [
    {
      AUTH0_API_AUDIENCE = "${var.environment}/ows-grass/AUTH0_API_AUDIENCE"
    },
    {
      AUTH0_DOMAIN = "${var.environment}/ows-grass/AUTH0_DOMAIN"
    },
    {
      DB_URL = "${var.environment}/ows-grass/DB_URL"
    },
  ]
}

module "secrets" {
  source   = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.5.1"
  for_each = toset(var.secrets_manager_secret_names)

  environment                    = var.environment
  service_name                   = var.service_name
  secret_name                    = each.value
  application_family             = var.application_family
  secret_recovery_window_in_days = 7
}

module "fargate_service_dashboard" {
  source                            = "git@github.com:theorchard/terraform-datadog.git//modules/service?ref=6.13.6"
  environment                       = var.environment
  environment_type                  = "fargate"
  service_name                      = var.service_name
  service_cpu_monitor_silenced      = true
  service_4xx_monitor_enabled       = false
  service_5xx_monitor_silenced      = true
  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.notification_endpoints
  escalation_notification_endpoints = var.escalation_notification_endpoints
  teams                             = [var.application_family]
}

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 = 131072

        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
  }
}

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 = false
  block_waf_enabled = true
  excluded_rules = [
    "NoUserAgent_HEADER",
    "SizeRestrictions_BODY",
  ]

  logging_config_default_destination = data.aws_s3_bucket.logging_bucket_waf.arn

  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                = "${var.environment}-${var.service_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" "private_networks" {
  name  = "private_networks"
  scope = "REGIONAL"
}

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

data "aws_wafv2_ip_set" "graphql_networks" {
  name  = "${var.environment}_graphql_switchboard_private"
  scope = "REGIONAL"
}

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                 = 2000
        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                 = 2000
        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 "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 = 9

    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.nat.arn
          }
        }

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

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

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

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

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

    action {
      block {}
    }

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

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

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

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
}

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 "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} 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 = [
    "environment        = ${var.environment}",
    "service_name       = ${var.service_name}",
    "application_family = ${var.application_family}"
  ]
}

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 @slack-devops-internal-alerts{{/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 @slack-devops-internal-alerts"
  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 @slack-devops-internal-alerts{{/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 @slack-devops-internal-alerts"
  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 "sentry_ows_grass_qa" {
  source = "git@github.com:theorchard/terraform-sentry.git//?ref=4.1.2"

  environment        = var.environment
  service_name       = var.service_name
  application_family = var.application_family
}

module "ows_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=3.1.1"

  providers = {
    aws.dns = aws.networking
  }

  environment                      = var.environment
  service_name                     = var.service_name
  application_family               = var.application_family
  cache_engine                     = "redis"
  redis_engine_version             = "5.0.8"
  cache_subnet_group_name          = "${var.environment}-elasticache-subnet-group"
  cache_transit_encryption_enabled = false
  redis_snapshot_window            = "08:30-09:30"
  cache_maintenance_window         = "wed:06:00-wed:07:00"
  cache_node_type                  = "cache.t4g.micro"
  cache_parameter_group_name       = "default.redis5.0"
  route53_zone_id                  = data.aws_route53_zone.route53_zone.zone_id
  vpc_id                           = module.vpc_info.vpc_id
}

