#------------------------------------------------------------------------------------------
# A variant on PowerUserAccess that isn't so damn generous with sts:assumeRole
#------------------------------------------------------------------------------------------
data "aws_iam_policy_document" "mdr_engineer" {
  statement {
    effect = "Allow"
    not_actions = [
      "sts:*",
      "iam:*",
      "organizations:*",
    ]
    resources = [
      "*",
    ]
  }
  statement {
    effect = "Allow"
    actions = [
      "iam:CreateServiceLinkedRole",
      "iam:DeleteServiceLinkedRole",
      "iam:ListRoles",
      "iam:ListRolePolicies",
      "iam:ListInstanceProfiles",
      "iam:ListPolicies",
      "iam:GetRole",
      "iam:GetRolePolicy",
      "iam:GetInstanceProfile",
      "iam:GetPolicy",
      "iam:GetPolicyVersion",
      "iam:ListAttachedRolePolicies",
      "organizations:DescribeOrganization",
    ]

    resources = [
      "*",
    ]
  }
  statement {
    effect = "Allow"
    actions = [
      "iam:PassRole",
    ]

    resources = [
      "arn:${local.aws_partition}:iam::${local.aws_account}:role/instance/*",
      "arn:${local.aws_partition}:iam::${local.aws_account}:role/lambda/*",
      "arn:${local.aws_partition}:iam::${local.aws_account}:role/aws_services/*",
      "arn:${local.aws_partition}:iam::${local.aws_account}:role/fargate/*",
    ]
  }

  statement {
    sid    = "AssumeThisRoleInOtherAccounts"
    effect = "Allow"
    actions = [
      "sts:AssumeRole"
    ]

    resources = [
      "arn:${local.aws_partition}:iam::*:role/user/mdr_engineer",
      "arn:${local.aws_partition}:iam::*:role/mdr_engineer",
    ]
  }
}

resource "aws_iam_policy" "mdr_engineer" {
  name   = "mdr_engineer"
  path   = "/user/"
  policy = data.aws_iam_policy_document.mdr_engineer.json
}

