{
  "Description": "Qovery role for day-to-day operations on an existing EKS cluster: deploying your applications and the databases managed by Qovery, and updating the cluster. The cluster must first be created with the extended permissions role, which is also needed to delete it and for any change to its IAM roles and policies. The Metadata of the Role resource explains why each permission is needed.",
  "Parameters": {
    "RoleName": {
      "Description": "The name of the role that is going to be created to allow restricted access to Qovery, for day-to-day operations on an existing cluster",
      "Type": "String",
      "Default": "qovery-restricted-user-role",
      "MaxLength": 64
    },
    "OrganizationId": {
      "Description": "The id of your Qovery organization. Only Qovery acting on behalf of this organization will be able to assume the role",
      "Type": "String",
      "AllowedPattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
      "ConstraintDescription": "must be a Qovery organization id, a lowercase UUID like 3f2b7c1e-8d4a-4b6e-9f0a-1c2d3e4f5a6b"
    },
    "AwsEksEncryptSecretsKmsKeyArn": {
      "Description": "ARN of your own KMS key, if you set one in the cluster's aws_eks_encrypt_secrets_kms_key_arn advanced setting. Leave empty if you don't: the role then gets no permission on KMS keys that Qovery doesn't create",
      "Type": "String",
      "Default": "",
      "AllowedPattern": "^(arn:aws[a-z-]*:kms:[a-z0-9-]+:[0-9]{12}:key/[0-9a-f-]+)?$",
      "ConstraintDescription": "must be empty or a KMS key ARN (arn:aws:kms:<region>:<account id>:key/<key id>), not an alias"
    },
    "AwsEksEnableEfsAddon": {
      "Description": "Whether the cluster's aws_eks_enable_efs_addon advanced setting is on. When false (default), the role gets no permission on Amazon EFS. Set it to true to let Qovery manage the EFS file system of the cluster and its mount targets",
      "Type": "String",
      "Default": "false",
      "AllowedValues": [
        "true",
        "false"
      ]
    }
  },
  "Conditions": {
    "HasEksEncryptSecretsKmsKey": {
      "Fn::Not": [
        {
          "Fn::Equals": [
            {
              "Ref": "AwsEksEncryptSecretsKmsKeyArn"
            },
            ""
          ]
        }
      ]
    },
    "EksEfsAddonEnabled": {
      "Fn::Equals": [
        {
          "Ref": "AwsEksEnableEfsAddon"
        },
        "true"
      ]
    }
  },
  "Resources": {
    "Role": {
      "Type": "AWS::IAM::Role",
      "Metadata": {
        "Comments": {
          "AwsServicesUnscoped": {
            "Why": [
              "The AWS services Qovery uses to update the cluster's infrastructure and to deploy the databases it manages, plus read-only lookups on the account (Organizations, Service Quotas, CloudTrail events, resource tags)."
            ]
          },
          "EfsUnscoped": {
            "Why": [
              "elasticfilesystem:*: the EFS file system of the cluster and its mount targets, created by Qovery when the aws_eks_enable_efs_addon advanced setting is on.",
              "Only written when the AwsEksEnableEfsAddon parameter is true.",
              "Unscoped: a file system is identified by a generated id, not by a name Qovery can rely on."
            ]
          },
          "S3SqsQoveryScoped": {
            "Why": "Full access to the S3 buckets and SQS queues created by Qovery. Scoped to the names starting with qovery: the other buckets and queues of the account are out of reach."
          },
          "SimulatePolicyFromQovery": {
            "Why": [
              "Pre-flight check: lets Qovery dry-run the permissions of this role before a deployment, so a missing permission is reported up front instead of making the deployment fail halfway through.",
              "Scoped to this role: it can't be used to inspect the permissions of the other users and roles of the account."
            ],
            "Actions": {
              "iam:SimulatePrincipalPolicy": "simulate this role's policies against the actions Qovery needs"
            }
          },
          "IamManageQoveryIdentities": {
            "Why": [
              "The IAM roles, policies and instance profiles of the cluster, created by Qovery with the extended permissions role:",
              "  - EKS control plane and nodes: qovery-eks-<cluster id>, qovery-eks-workers-<cluster id>, KarpenterNodeRole-<cluster>",
              "  - Karpenter controller: KarpenterControllerRole-<cluster>",
              "  - EBS and EFS CSI drivers: eks-ebs-csi-plugin-<cluster id>, eks-efs-csi-plugin-<cluster id>, AmazonEKS_EBS_CSI_Policy-<cluster id>, AmazonEKS_EFS_CSI_Policy-<cluster id>",
              "  - Qovery's cluster components, each with its own role and policy named qovery-*: Loki, Thanos, cluster-autoscaler, Grafana, CloudWatch exporter, AWS Load Balancer controller, KEDA, External Secrets, IAM user mapper, RDS enhanced monitoring",
              "  - Instance profiles: KarpenterNodeInstanceProfile-<cluster>, qovery-eks-alb-controller-<cluster id>",
              "This role can read them, tag them and hand them to AWS, but can't create, change or delete them.",
              "Scoped to these names: Qovery can't read or change the other IAM identities of the account."
            ],
            "Actions": {
              "iam:GetRole": "read a role on every deployment to detect changes",
              "iam:ListRoleTags": "re-read a role's tags after an update, when their values were only known at apply time",
              "iam:TagRole": "add or update the cluster tags on a role (QoveryProduct, ClusterId, your custom tags)",
              "iam:UntagRole": "remove a tag that is no longer set on the cluster",
              "iam:ListRolePolicies": "list a role's inline policies, to read them",
              "iam:GetRolePolicy": "read the content of an inline policy",
              "iam:ListAttachedRolePolicies": "list the policies attached to a role, to read them",
              "iam:ListInstanceProfilesForRole": "list the instance profiles of a role",
              "iam:GetPolicy": "read a policy on every deployment to detect changes",
              "iam:GetPolicyVersion": "read the current content of a policy",
              "iam:ListPolicyVersions": "list the versions of a policy",
              "iam:GetInstanceProfile": "read an instance profile on every deployment to detect changes",
              "iam:TagInstanceProfile": "add or update the cluster tags on an instance profile",
              "iam:UntagInstanceProfile": "remove a tag that is no longer set on the cluster",
              "iam:PassRole": "hand an existing role to AWS: a node role to EKS when it recreates a node group (e.g. when a paused cluster is resumed), a CSI driver role to EKS when an add-on is updated, and the RDS enhanced monitoring role to the RDS databases managed by Qovery"
            }
          },
          "IamPassRdsMonitoringRole": {
            "Why": [
              "The RDS databases deployed with a Qovery Blueprint: the blueprint's enhanced monitoring role isn't named qovery-*, so IamManageQoveryIdentities doesn't cover it.",
              "Condition: any role of the account, but it can only be handed to RDS enhanced monitoring (monitoring.rds.amazonaws.com), not to any other AWS service."
            ],
            "Actions": {
              "iam:PassRole": "hand the enhanced monitoring role to RDS when a Blueprint database is created or updated"
            }
          },
          "IamServiceLinkedRoleLookup": {
            "Why": [
              "AWS service-linked roles live under the aws-service-role/ path. IamManageQoveryIdentities only covers two of them (AWSServiceRoleForEC2Spot and AWSServiceRoleForAmazonEKSNodegroup): this statement lets Qovery read any of them.",
              "Read-only: lets AWS and Qovery check whether one already exists before creating it (see IamServiceLinkedRolesScoped).",
              "While a role doesn't exist yet, IAM can't know its path: it checks the permission against role/<name>, without the aws-service-role/ path, hence the second ARN."
            ],
            "Actions": {
              "iam:GetRole": "check that a service-linked role exists: EKS does it for AWSServiceRoleForAmazonEKSNodegroup before creating a managed node group, Qovery for AWSServiceRoleForEC2Spot before running spot instances"
            }
          },
          "IamOidcProviderScoped": {
            "Why": [
              "The cluster's OpenID Connect provider, created by Qovery with the extended permissions role: it lets Kubernetes service accounts assume IAM roles (IRSA), which is how Karpenter, the CSI drivers, Loki, Thanos, ... get their AWS permissions.",
              "Scoped to the EKS providers (oidc.eks.<region>.amazonaws.com/id/<id>): AWS names a provider after its cluster's issuer URL, so it can't be narrowed down to Qovery's clusters, but the account's other identity providers (GitHub Actions, GitLab, ...) are out of reach."
            ],
            "Actions": {
              "iam:GetOpenIDConnectProvider": "read the provider on every deployment to detect changes",
              "iam:TagOpenIDConnectProvider": "add or update the cluster tags on the provider",
              "iam:UntagOpenIDConnectProvider": "remove a tag that is no longer set on the cluster",
              "iam:UpdateOpenIDConnectProviderThumbprint": "update the fingerprint of the issuer's certificate when AWS changes it"
            }
          },
          "IamServiceLinkedRolesScoped": {
            "Why": "Some AWS services need a service-linked role in the account, created by AWS on behalf of the caller the first time the service is used. Limited to the services Qovery can start using after the cluster's creation.",
            "Actions": {
              "iam:CreateServiceLinkedRole": "let AWS create the service-linked role of one of the services below"
            },
            "AWSServiceNames": {
              "elasticfilesystem.amazonaws.com": "AWSServiceRoleForAmazonElasticFileSystem, created by EFS with the first file system of the account, needed when the aws_eks_enable_efs_addon advanced setting is on",
              "rds.amazonaws.com": "AWSServiceRoleForRDS, created with the first PostgreSQL, MySQL or DocumentDB database managed by Qovery in the account",
              "spot.amazonaws.com": "AWSServiceRoleForEC2Spot, needed by Karpenter to run spot instances: Qovery creates it when spot instances are enabled on the cluster and the account doesn't have it yet",
              "elasticache.amazonaws.com": "AWSServiceRoleForElastiCache, created with the first ElastiCache cluster of the account (Redis database managed by Qovery, or deployed with a Qovery Blueprint)",
              "mq.amazonaws.com": "AWSServiceRoleForAmazonMQ, created with the first Amazon MQ broker of the account, deployed with a Qovery Blueprint",
              "kafka.amazonaws.com": "AWSServiceRoleForKafka, created with the first Amazon MSK cluster of the account, deployed with a Qovery Blueprint"
            }
          },
          "KmsManageKeysScoped": {
            "Why": [
              "The 2 KMS keys of the cluster, created by Qovery with the extended permissions role to encrypt its S3 buckets: Loki logs and Thanos metrics.",
              "Condition: only keys tagged QoveryProduct=EKS, so the other keys of the account are out of reach."
            ],
            "Actions": {
              "kms:DescribeKey": "read a key on every deployment to detect changes",
              "kms:GetKeyPolicy": "read a key's policy",
              "kms:GetKeyRotationStatus": "check that automatic key rotation is on",
              "kms:ListResourceTags": "read a key's tags",
              "kms:TagResource": "add or update the cluster tags on a key",
              "kms:UntagResource": "remove a tag that is no longer set on the cluster"
            }
          },
          "KmsCreateGrantOwnKey": {
            "Why": [
              "Your own KMS key, if you set one in the cluster's aws_eks_encrypt_secrets_kms_key_arn advanced setting to encrypt its Kubernetes secrets.",
              "Only written when the AwsEksEncryptSecretsKmsKeyArn parameter is set, and scoped to that key: your key isn't created by Qovery, so it has no name or tag Qovery can rely on, hence its ARN."
            ],
            "Actions": {
              "kms:DescribeKey": "read your key to check it before EKS uses it",
              "kms:CreateGrant": "let EKS use your key to encrypt the cluster's Kubernetes secrets"
            }
          }
        }
      },
      "Properties": {
        "RoleName": {
          "Ref": "RoleName"
        },
        "MaxSessionDuration": 28800,
        "Policies": [
          {
            "PolicyName": "qovery-permissions",
            "PolicyDocument": {
              "Version": "2012-10-17",
              "Statement": [
                {
                  "Sid": "AwsServicesUnscoped",
                  "Effect": "Allow",
                  "Action": [
                    "application-autoscaling:*",
                    "autoscaling:*",
                    "cloudtrail:LookupEvents",
                    "cloudwatch:*",
                    "ec2:*",
                    "ecr:*",
                    "eks:*",
                    "elasticache:*",
                    "elasticloadbalancing:*",
                    "es:AddTags",
                    "es:CreateElasticsearchDomain",
                    "es:DeleteElasticsearchDomain",
                    "es:DescribeElasticsearchDomain",
                    "es:ListTags",
                    "es:RemoveTags",
                    "events:DeleteRule",
                    "events:DescribeRule",
                    "events:ListRuleNamesByTarget",
                    "events:ListTagsForResource",
                    "events:ListTargetsByRule",
                    "events:PutRule",
                    "events:PutTargets",
                    "events:RemoveTargets",
                    "events:TagResource",
                    "events:UntagResource",
                    "logs:*",
                    "organizations:DescribeAccount",
                    "organizations:DescribeOrganization",
                    "organizations:DescribeOrganizationalUnit",
                    "organizations:DescribePolicy",
                    "organizations:ListChildren",
                    "organizations:ListParents",
                    "organizations:ListPolicies",
                    "organizations:ListPoliciesForTarget",
                    "organizations:ListRoots",
                    "organizations:ListTargetsForPolicy",
                    "rds:*",
                    "s3:ListAllMyBuckets",
                    "servicequotas:GetServiceQuota",
                    "tag:GetResources"
                  ],
                  "Resource": "*"
                },
                {
                  "Fn::If": [
                    "EksEfsAddonEnabled",
                    {
                      "Sid": "EfsUnscoped",
                      "Effect": "Allow",
                      "Action": "elasticfilesystem:*",
                      "Resource": "*"
                    },
                    {
                      "Ref": "AWS::NoValue"
                    }
                  ]
                },
                {
                  "Sid": "S3SqsQoveryScoped",
                  "Effect": "Allow",
                  "Action": [
                    "s3:*",
                    "sqs:*"
                  ],
                  "Resource": [
                    "arn:aws:s3:::qovery*",
                    "arn:aws:s3:::qovery*/*",
                    "arn:aws:sqs:*:*:qovery*",
                    "arn:aws:sqs:*:*:qovery*/*"
                  ]
                },
                {
                  "Sid": "SimulatePolicyFromQovery",
                  "Effect": "Allow",
                  "Action": [
                    "iam:SimulatePrincipalPolicy"
                  ],
                  "Resource": {
                    "Fn::Sub": "arn:aws:iam::${AWS::AccountId}:role/${RoleName}"
                  }
                },
                {
                  "Sid": "IamManageQoveryIdentities",
                  "Effect": "Allow",
                  "Action": [
                    "iam:GetRole",
                    "iam:ListRoleTags",
                    "iam:TagRole",
                    "iam:UntagRole",
                    "iam:ListRolePolicies",
                    "iam:GetRolePolicy",
                    "iam:ListAttachedRolePolicies",
                    "iam:ListInstanceProfilesForRole",
                    "iam:GetPolicy",
                    "iam:GetPolicyVersion",
                    "iam:ListPolicyVersions",
                    "iam:GetInstanceProfile",
                    "iam:TagInstanceProfile",
                    "iam:UntagInstanceProfile",
                    "iam:PassRole"
                  ],
                  "Resource": [
                    "arn:aws:iam::*:role/qovery-*",
                    "arn:aws:iam::*:policy/qovery-*",
                    "arn:aws:iam::*:instance-profile/qovery-*",
                    "arn:aws:iam::*:role/Karpenter*",
                    "arn:aws:iam::*:instance-profile/KarpenterNodeInstanceProfile-*",
                    "arn:aws:iam::*:role/eks-ebs-csi-plugin-*",
                    "arn:aws:iam::*:role/eks-efs-csi-plugin-*",
                    "arn:aws:iam::*:policy/AmazonEKS_EBS_CSI_Policy-*",
                    "arn:aws:iam::*:policy/AmazonEKS_EFS_CSI_Policy-*",
                    "arn:aws:iam::*:role/aws-service-role/spot.amazonaws.com/AWSServiceRoleForEC2Spot",
                    "arn:aws:iam::*:role/aws-service-role/eks-nodegroup.amazonaws.com/AWSServiceRoleForAmazonEKSNodegroup"
                  ]
                },
                {
                  "Sid": "IamPassRdsMonitoringRole",
                  "Effect": "Allow",
                  "Action": "iam:PassRole",
                  "Resource": "arn:aws:iam::*:role/*",
                  "Condition": {
                    "StringEquals": {
                      "iam:PassedToService": "monitoring.rds.amazonaws.com"
                    }
                  }
                },
                {
                  "Sid": "IamServiceLinkedRoleLookup",
                  "Effect": "Allow",
                  "Action": "iam:GetRole",
                  "Resource": [
                    "arn:aws:iam::*:role/aws-service-role/*",
                    "arn:aws:iam::*:role/AWSServiceRoleFor*"
                  ]
                },
                {
                  "Sid": "IamOidcProviderScoped",
                  "Effect": "Allow",
                  "Action": [
                    "iam:GetOpenIDConnectProvider",
                    "iam:TagOpenIDConnectProvider",
                    "iam:UntagOpenIDConnectProvider",
                    "iam:UpdateOpenIDConnectProviderThumbprint"
                  ],
                  "Resource": "arn:aws:iam::*:oidc-provider/oidc.eks.*"
                },
                {
                  "Sid": "IamServiceLinkedRolesScoped",
                  "Effect": "Allow",
                  "Action": "iam:CreateServiceLinkedRole",
                  "Resource": "*",
                  "Condition": {
                    "StringEquals": {
                      "iam:AWSServiceName": [
                        "elasticfilesystem.amazonaws.com",
                        "rds.amazonaws.com",
                        "spot.amazonaws.com",
                        "elasticache.amazonaws.com",
                        "mq.amazonaws.com",
                        "kafka.amazonaws.com"
                      ]
                    }
                  }
                },
                {
                  "Sid": "KmsManageKeysScoped",
                  "Effect": "Allow",
                  "Action": [
                    "kms:DescribeKey",
                    "kms:GetKeyPolicy",
                    "kms:GetKeyRotationStatus",
                    "kms:ListResourceTags",
                    "kms:TagResource",
                    "kms:UntagResource"
                  ],
                  "Resource": "*",
                  "Condition": {
                    "StringEquals": {
                      "aws:ResourceTag/QoveryProduct": "EKS"
                    }
                  }
                },
                {
                  "Fn::If": [
                    "HasEksEncryptSecretsKmsKey",
                    {
                      "Sid": "KmsCreateGrantOwnKey",
                      "Effect": "Allow",
                      "Action": [
                        "kms:DescribeKey",
                        "kms:CreateGrant"
                      ],
                      "Resource": {
                        "Ref": "AwsEksEncryptSecretsKmsKeyArn"
                      }
                    },
                    {
                      "Ref": "AWS::NoValue"
                    }
                  ]
                }
              ]
            }
          }
        ],
        "AssumeRolePolicyDocument": {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Effect": "Allow",
              "Principal": {
                "AWS": [
                  "arn:aws:iam::283389881690:role/qovery-deployer",
                  "arn:aws:iam::283389881690:user/qovery-deployer"
                ]
              },
              "Action": "sts:AssumeRole",
              "Condition": {
                "StringLike": {
                  "sts:ExternalId": {
                    "Fn::Sub": "${OrganizationId}:*"
                  }
                }
              }
            }
          ]
        }
      }
    }
  },
  "Outputs": {
    "RoleARN": {
      "Description": "Arn of the created role. This is the information to give in Qovery console",
      "Value": {
        "Fn::GetAtt": [
          "Role",
          "Arn"
        ]
      },
      "Export": {
        "Name": {
          "Fn::Sub": "${AWS::StackName}-RoleARN"
        }
      }
    }
  }
}
