# Assume role policy used by Jenkins pipeline 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",
      ]
    }
  }
}

# Jenkins pipeline agents will assume this role in order to run deploys.
resource "aws_iam_role" "jenkins_deploy_role" {
  name               = "${var.environment}-jenkins-pipeline-deploy-role"
  assume_role_policy = data.aws_iam_policy_document.assume_role_policy.json
}

data "aws_iam_policy_document" "jenkins_deploy_role_policy_document" {
  # checkov:skip=CKV_AWS_109:Allow "*" resources in this policy for Jenkins. Critical grant statements are protected by IAM conditions.
  # checkov:skip=CKV_AWS_110:Allow "*" resources in this policy for Jenkins. Critical grant statements are protected by IAM conditions.
  # checkov:skip=CKV_AWS_111:Allow "*" resources in this policy for Jenkins. Critical grant statements are protected by IAM conditions.

  statement {
    sid    = "AllowECRImageOperations"
    effect = "Allow"
    actions = [
      "ecr:BatchCheckLayerAvailability",
      "ecr:BatchGetImage",
      "ecr:CompleteLayerUpload",
      "ecr:DescribeImages",
      "ecr:DescribeImageScanFindings",
      "ecr:DescribeRepositories",
      "ecr:GetAuthorizationToken",
      "ecr:GetDownloadUrlForLayer",
      "ecr:GetLifecyclePolicy",
      "ecr:GetLifecyclePolicyPreview",
      "ecr:GetRepositoryPolicy",
      "ecr:InitiateLayerUpload",
      "ecr:ListImages",
      "ecr:ListTagsForResource",
      "ecr:PutImage",
      "ecr:UploadLayerPart",
    ]
    resources = ["*"]
  }

  statement {
    sid    = "AllowPythonDeploymentUtilsFargateDeployScript"
    effect = "Allow"
    actions = [
      "application-autoscaling:DescribeScalableTargets",
      "application-autoscaling:RegisterScalableTarget",
      "cloudwatch:DescribeAlarms",
      "cloudwatch:DisableAlarmActions",
      "cloudwatch:EnableAlarmActions",
      "ecs:DescribeServices",
      "ecs:DescribeTaskDefinition",
      "ecs:DescribeTasks",
      "ecs:ListTasks",
      "ecs:RegisterTaskDefinition",
      "ecs:TagResource",
      "ecs:UpdateService",
      "events:ListTargetsByRule",
      "events:PutTargets",
    ]
    resources = ["*"]
  }

  statement {
    sid     = "AllowPassRole"
    effect  = "Allow"
    actions = ["iam:PassRole"]
    condition {
      test     = "StringEquals"
      variable = "iam:PassedToService"
      values   = ["events.amazonaws.com"]
    }
    resources = [
      "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/${var.environment}-*-event-role",
    ]
  }

  statement {
    sid    = "AllowLambdaDeployment"
    effect = "Allow"
    actions = [
      "lambda:CreateAlias",
      "lambda:Get*",
      "lambda:List*",
      "lambda:PublishVersion",
      "lambda:UpdateAlias",
      "lambda:UpdateFunctionCode",
    ]
    resources = ["*"]
  }

  statement {
    sid     = "AllowPassRoleToECS"
    effect  = "Allow"
    actions = ["iam:PassRole"]
    condition {
      test     = "StringLike"
      variable = "iam:PassedToService"
      values   = ["ecs-tasks.amazonaws.com"]
    }
    resources = [
      "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/${var.environment}-*-task-role",
      "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/${var.environment}-*-execution-role",
    ]
  }

  statement {
    sid    = "AllowUsingKMSKeysViaLambdaService"
    effect = "Allow"
    actions = [
      "kms:CreateGrant",
      "kms:Decrypt",
      "kms:DescribeKey",
      "kms:Encrypt",
      "kms:GenerateDataKey*",
    ]
    condition {
      test     = "StringLike"
      variable = "kms:ViaService"
      values   = ["lambda.${var.aws_region}.amazonaws.com"]
    }
    resources = ["*"]
  }
}

resource "aws_iam_policy" "jenkins_deploy_role_policy" {
  name        = "${var.environment}-Jenkins-pipeline-deploy-policy"
  description = "${var.environment}-Jenkins pipeline deploy policy"
  policy      = data.aws_iam_policy_document.jenkins_deploy_role_policy_document.json
}

# Attach iam policies to Jenkins deploy role.
resource "aws_iam_role_policy_attachment" "jenkins_deploy_role_policy_attachment" {
  role       = aws_iam_role.jenkins_deploy_role.id
  policy_arn = aws_iam_policy.jenkins_deploy_role_policy.arn
}
