# SecretsManager policy to grant Jenkins access to the dbt-accounting secrets

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

    actions = [
      "secretsmanager:GetSecretValue",
    ]

    resources = [
      "arn:aws:secretsmanager:*:*:secret:${var.environment}/${var.service_name}/",
      "arn:aws:secretsmanager:*:*:secret:${var.environment}/${var.service_name}/*",
    ]
  }
}

# Assume role policy used by Jenkins scheduler agent role
data "aws_iam_policy_document" "assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type = "AWS"

      identifiers = [
        "arn:aws:iam::437795906767:role/prod-jenkins-aws-pipeline-agent",
        "arn:aws:iam::437795906767:role/prod-jenkins-aws-task-agent",
      ]
    }
  }
}

resource "aws_iam_policy" "secrets_manager_policy" {
  name   = "SecretsManager-${var.environment}-${var.service_name}-access-policy"
  policy = data.aws_iam_policy_document.secrets_manager_policy_document.json
}

# Jenkins agent will assume this role in order to access SecretsManager
resource "aws_iam_role" "dbt_accounting_deploy_role" {
  name               = "${var.environment}-${var.service_name}-deploy-role"
  assume_role_policy = data.aws_iam_policy_document.assume_role_policy.json
}

resource "aws_iam_role_policy_attachment" "pdp_integration_secret_manager_policy_attachment" {
  role       = aws_iam_role.dbt_accounting_deploy_role.id
  policy_arn = aws_iam_policy.secrets_manager_policy.arn
}

resource "aws_iam_role_policy_attachment" "m2m_policy_attachment" {
  role       = aws_iam_role.dbt_accounting_deploy_role.id
  policy_arn = data.aws_iam_policy.ows_machine_to_machine_policy.arn
}

data "aws_iam_policy_document" "run_task_policy_document" {
  # checkov:skip=CKV_AWS_111:Wildcards are required here to allow Step Functions to run tasks
  statement {
    effect = "Allow"
    actions = [
      "ec2:DescribeSecurityGroups",
      "ec2:DescribeSubnets",
      "ec2:DescribeVpcs",
      "ecs:DescribeTasks",
      "ecs:DescribeTaskDefinition",
      "ecs:StopTask",
    ]
    resources = ["*"]
  }

  statement {
    effect = "Allow"
    actions = [
      "ecs:RunTask",
    ]
    resources = [
      "${module.dbt_accounting_fargate_environment.fargate_task_definition_arn_without_revision}:*",
      module.dbt_accounting_fargate_environment.fargate_cluster_arn,
      "${data.aws_ecs_task_definition.dbt_accounting_qa_task_definition.arn_without_revision}:*",
      data.aws_ecs_cluster.dbt_accounting_qa_cluster.arn,
    ]
  }

  statement {
    effect = "Allow"
    actions = [
      "ecs:TagResource",
    ]
    resources = ["*"]
    condition {
      test     = "StringEquals"
      variable = "ecs:CreateAction"
      values = [
        "RunTask",
      ]
    }
  }

  statement {
    effect  = "Allow"
    actions = ["iam:PassRole"]
    condition {
      test     = "StringLike"
      variable = "iam:PassedToService"
      values   = ["ecs-tasks.amazonaws.com"]
    }
    resources = [
      module.dbt_accounting_fargate_environment.fargate_task_iam_role_arn,
      module.dbt_accounting_fargate_environment.fargate_task_iam_execution_role_arn,
      data.aws_iam_role.dbt_accounting_qa_task_role.arn,
      data.aws_iam_role.dbt_accounting_qa_task_execution_role.arn,
    ]
  }

  statement {
    effect = "Allow"
    actions = [
      "events:PutTargets",
      "events:PutRule",
      "events:DescribeRule",
    ]

    resources = [
      "arn:aws:events:${var.aws_region}:${data.aws_caller_identity.current.account_id}:rule/StepFunctionsGetEventsForECSTaskRule"
    ]
  }
}

resource "aws_iam_policy" "ecs_service_start_sf_policy" {
  name   = "${var.environment}-${var.service_name}-ecs-service-start-sf-policy"
  policy = jsonencode({
    Version : "2012-10-17",
    Statement : [
      {
        Effect   : "Allow",
        Action   : ["states:StartExecution"],
        Resource : aws_sfn_state_machine.dbt_accounting_run_state_machine.arn
      }
    ]
  })
}

resource "aws_iam_role" "step_func_ecs_runner_role" {
  name = "StepFunctions-${var.environment}-${var.service_name}-ecs-runner"

  assume_role_policy = jsonencode({
    Version : "2012-10-17",
    Statement : [{
      Effect  : "Allow",
      Principal : { Service : "states.amazonaws.com" },
      Action   : "sts:AssumeRole"
    }]
  })
}

resource "aws_iam_role_policy" "step_func_ecs_runner_policy_attachment" {
  name   = "${var.environment}-${var.service_name}-step-func-ecs-runner-policy"
  role   = aws_iam_role.step_func_ecs_runner_role.id
  policy = data.aws_iam_policy_document.run_task_policy_document.json
}

resource "aws_iam_role_policy" "step_func_logging" {
  name = "${var.environment}-${var.service_name}-sfn-logging"
  role = aws_iam_role.step_func_ecs_runner_role.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        Action = [
          "logs:CreateLogDelivery",
          "logs:GetLogDelivery",
          "logs:UpdateLogDelivery",
          "logs:DeleteLogDelivery",
          "logs:ListLogDeliveries",
          "logs:PutResourcePolicy",
          "logs:DescribeResourcePolicies",
          "logs:DescribeLogGroups",
        ]
        Resource = "*"
      }
    ]
  })
}
