# Secret Manager policy document.
data "aws_iam_policy_document" "prod_sforce_int_test_secrets_manager_policy_document" {
  statement {
    actions = [
      "secretsmanager:GetSecretValue"
    ]

    resources = [
      "arn:aws:secretsmanager:*:*:secret:${var.environment}/${var.lambda_name}/INTEGRATION_TEST_CONSUMER_KEY*",
      "arn:aws:secretsmanager:*:*:secret:${var.environment}/${var.lambda_name}/INTEGRATION_TEST_CONSUMER_SECRET*",
      "arn:aws:secretsmanager:*:*:secret:${var.environment}/${var.lambda_name}/INTEGRATION_TEST_REFRESH_TOKEN*",
    ]
  }
}

# Secret Manager Policy
resource "aws_iam_policy" "prod_sforce_int_test_secrets_manager_policy" {
  name              = "${var.environment}_sforce_int_test_secrets_manager_policy"
  policy            = data.aws_iam_policy_document.prod_sforce_int_test_secrets_manager_policy_document.json
}

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

    principals {
      type = "AWS"

      identifiers = [
        "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/prod-jenkins-aws-pipeline-agent",
      ]
    }
  }
}

# Jenkins pipeline agents will assume this role in order to access salesforce secrets
resource "aws_iam_role" "prod_jenkins_salesforce_integration_tests_role" {
  name               = "${var.environment}-${var.lambda_name}-integration-tests-role"
  assume_role_policy = data.aws_iam_policy_document.salesforce_integration_test_assume_role_policy.json
}

# Attach secrets manager policy to Jenkins role.
resource "aws_iam_role_policy_attachment" "prod_sforce_int_test_secrets_manager_policy_attachment" {
  role               = aws_iam_role.prod_jenkins_salesforce_integration_tests_role.id
  policy_arn         = aws_iam_policy.prod_sforce_int_test_secrets_manager_policy.arn
}
