rpmansion
rpmansion

Reputation: 2014

Defining proper IAM role for Cognito SMS using Terraform

I created a role with policy for Cognito to publish SNS. The problem with this when scanning via terraform security, is it complains of having an overly permissive (AVD-AWS-0057) since I'm using a wildcard in Resource: ["*"].

So, I made a change to this to only add the Cognito user pool ARN and SNS topic ARN, but still complain of the role not having an SNS publish permission. Where in fact, the action below indicates permission.

data "aws_iam_policy_document" "assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type = "Service"
      identifiers = ["cognito-idp.amazonaws.com"]
    }

    condition {
      test = "StringEquals"
      variable = "sts:ExternalId"

      values = [aws_cognito_user_pool.uam_user_pool.arn]
    }
  }
}

resource "aws_iam_role" "iam_role" {
  name               = var.role_name
  path               = var.role_path
  assume_role_policy = data.aws_iam_policy_document.assume_role_policy.json

  tags = var.default_tags
}

data "aws_iam_policy_document" "role_policy" {
  statement {
    sid = "AllowSNSPublish"
    effect  = "Allow"
    actions = ["sns:publish"]
    resources = [
      aws_sns_topic.topic.arn,
      aws_cognito_user_pool.uam_user_pool.arn
    ]
  }
}

resource "aws_iam_policy" "managed_policy" {
  name = var.role_policy_name
  policy = data.aws_iam_policy_document.role_policy.json

  tags = var.default_tags
}

resource "aws_iam_role_policy_attachment" "managed_policy_attach" {
  role = aws_iam_role.role.name
  policy_arn = aws_iam_policy.managed_policy.arn
}

How do you properly set this up?

Upvotes: 1

Views: 1426

Answers (1)

Fermin
Fermin

Reputation: 36081

In your "assume_role_policy" you are referencing the ARN of the user_pool and checking this against the sts:ExternalId - you need to add the external-id here rather than the ARN.

data "aws_iam_policy_document" "assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type = "Service"
      identifiers = ["cognito-idp.amazonaws.com"]
    }

    condition {
      test = "StringEquals"
      variable = "sts:ExternalId"

      values = ["<your-external-id>"]
    }
  }
}

You also don't need the ARN of the userpool in the "role_policy". This document is stating "whoever has this assigned to them can sns:publish to aws_sns_topic.topic.arn" - there is no need to specifc the userpool here. This is done at the point of attaching the policy to role/user/group (e.g. aws_iam_role.role.name).

Upvotes: 2

Related Questions