module "revoke_keys_lambda_role" {
  source = "../../../../modules/iam/roles/lambda_role"

  name_prefix   = local.name_prefix
  name          = "aws_users_key_watchdog_notifications_role"
  common_tags   = var.common_tags
  policies_list = concat(var.iam_policies_arns, [aws_iam_policy.revoke_keys_lambda_role_policy.arn])

  depends_on = [aws_iam_policy.revoke_keys_lambda_role_policy]
}

data "aws_iam_policy_document" "revoke_keys_lambda_role_policy" {
  statement {
    actions = [
      "iam:DeleteAccessKey",
      "iam:DeleteLoginProfile",
      "iam:GetAccessKeyLastUsed",
      "iam:UpdateAccessKey",
      "iam:ListUsers",
      "iam:ListGroups",
      "iam:GetGroup",
      "iam:ListAccessKeys",
      "iam:ListUserTags",
      "iam:ListAccountAliases",
    ]
    effect    = "Allow"
    resources = ["*"]
  }
  statement {
    actions   = ["ses:SendEmail"]
    effect    = "Allow"
    resources = ["*"]
  }
  statement {
    actions   = ["logs:CreateLogGroup"]
    effect    = "Allow"
    resources = ["arn:aws:logs:${local.aws_region_id}:${local.account_id}:*"]
  }
  statement {
    actions = [
      "logs:CreateLogStream",
      "logs:PutLogEvents",
    ]
    effect    = "Allow"
    resources = ["arn:aws:logs:${local.aws_region_id}:${local.account_id}:log-group:/aws/lambda/${local.name_prefix}-aws_users_key_watchdog:*"]
  }
}

resource "aws_iam_policy" "revoke_keys_lambda_role_policy" {
  name        = "${local.name_prefix}-aws_users_key_watchdog_notifications_policy"
  description = "Added ability to list users, groups and access keys, and also ability to revoke and delete access keys."
  policy      = data.aws_iam_policy_document.revoke_keys_lambda_role_policy.json
}
