# This module should used for each AWS Account / Environment pair.
# It is used to ensure PP's auth0-m2m-config-task-role can make changes
# to this AWS Account's <env>/*/M2M_AUTH0_CLIENT_CREDENTIALS Secrets Manager Secret

data "aws_caller_identity" "current" {}

# Allow roles from PP account's task role to assume the role in this AWS Account/Environment
data "aws_iam_policy_document" "assume_auth0_m2m_config_role_policy" {
  statement {
    effect  = "Allow"
    actions = ["sts:AssumeRole"]
    principals {
      type = "AWS"
      identifiers = [
        "arn:aws:iam::${local.permissions_platform_aws_account_id}:role/${var.environment}-auth0-m2m-config-task-role",
      ]
    }
  }
}
# Create the role that can be assumed
resource "aws_iam_role" "auth0_m2m_config_invoke_role" {
  name               = "${var.environment}-assume-auth0-m2m-config"
  assume_role_policy = data.aws_iam_policy_document.assume_auth0_m2m_config_role_policy.json

  tags = local.tags
}

# RW Policy Document for any <env>/*/M2M_AUTH0_CLIENT_CREDENTIALS in this AWS Account
data "aws_iam_policy_document" "auth0_m2m_config_secrets_manager_policy_document" {
  statement {
    effect = "Allow"
    actions = [
      "secretsmanager:GetResourcePolicy",
      "secretsmanager:GetSecretValue",
      "secretsmanager:DescribeSecret",
      "secretsmanager:ListSecretVersionIds",
      "secretsmanager:PutSecretValue",
    ]
    resources = [
      "arn:aws:secretsmanager:${var.aws_region}:${data.aws_caller_identity.current.account_id}:secret:${var.environment}/*/M2M_AUTH0_CLIENT_CREDENTIALS",
      "arn:aws:secretsmanager:${var.aws_region}:${data.aws_caller_identity.current.account_id}:secret:${var.environment}/*/M2M_AUTH0_CLIENT_CREDENTIALS*",
    ]
  }
}

# Create an IAM Policy with the RW Policy Document
resource "aws_iam_policy" "auth0_m2m_config_secrets_manager_policy" {
  name   = "${var.environment}-SecretsManager-auth0-m2m-config-access-policy"
  policy = data.aws_iam_policy_document.auth0_m2m_config_secrets_manager_policy_document.json

  tags = local.tags
}

# Associate to the IAM Policy for RW Secrets to the role that can be assumed
resource "aws_iam_role_policy_attachment" "auth0_m2m_config_secret_manager_policy_attachment" {
  role       = aws_iam_role.auth0_m2m_config_invoke_role.id
  policy_arn = aws_iam_policy.auth0_m2m_config_secrets_manager_policy.arn
}
