# Read-only IAM role allowing the Jenkins pipeline to fetch the jodconverter
# GH_TOKEN secret. The Jenkins agent (in the Orchard prod account) assumes this
# role cross-account, so the trusted principal is referenced by ARN.
resource "aws_iam_role" "build_role" {
  name               = "${var.environment}-${var.service_name}-build-role"
  assume_role_policy = data.aws_iam_policy_document.jenkins_assume_role_policy.json
}

# Trust policy: allow the Jenkins pipeline agent role to assume this role.
data "aws_iam_policy_document" "jenkins_assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type        = "AWS"
      identifiers = [var.jenkins_pipeline_agent_role_arn]
    }
  }
}

# Least-privilege read-only access, scoped to the GH_TOKEN secret ARN.
data "aws_iam_policy_document" "secrets_read" {
  statement {
    effect = "Allow"

    actions = [
      "secretsmanager:GetSecretValue",
      "secretsmanager:DescribeSecret",
    ]

    resources = [module.gh_token_secret.secret_arn]
  }
}

resource "aws_iam_policy" "secrets_read" {
  name   = "SECRETSMANAGER-${var.environment}-${var.service_name}-readonly"
  policy = data.aws_iam_policy_document.secrets_read.json
}

resource "aws_iam_role_policy_attachment" "secrets_read" {
  role       = aws_iam_role.build_role.name
  policy_arn = aws_iam_policy.secrets_read.arn
}
