AWSTemplateFormatVersion: '2010-09-09'
Description: ZopNight OIDC Federation - allows ZopNight (running on GCP) to discover and manage AWS resources.

Parameters:
  PermissionLevel:
    Type: String
    AllowedValues:
      - read_only
      - read_write
    Default: read_write
    Description: Permission level - read_only for discovery only, read_write for discovery + start/stop

Conditions:
  IsReadWrite: !Equals [!Ref PermissionLevel, 'read_write']

Resources:
  OIDCProviderLookupRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: OIDCProviderAccess
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - iam:ListOpenIDConnectProviders
                  - iam:CreateOpenIDConnectProvider
                  - iam:DeleteOpenIDConnectProvider
                  - iam:GetOpenIDConnectProvider
                  - iam:AddClientIDToOpenIDConnectProvider
                Resource: '*'

  OIDCProviderLookupFunction:
    Type: AWS::Lambda::Function
    Properties:
      Runtime: python3.12
      Handler: index.handler
      Timeout: 60
      Role: !GetAtt OIDCProviderLookupRole.Arn
      Code:
        ZipFile: |
          import boto3
          import cfnresponse
          import traceback


          GOOGLE_ISSUER = 'https://accounts.google.com'
          AUDIENCE = '108571531846883966629'
          THUMBPRINT = '6938fd4d98bab03faadb97b34396831e3780aea1'

          def handler(event, context):
              try:
                  iam = boto3.client('iam')

                  if event['RequestType'] == 'Delete':
                      created_by_us = event.get('ResourceProperties', {}).get('_createdByUs', 'false')
                      if created_by_us == 'true':
                          provider_arn = event.get('PhysicalResourceId', '')
                          if provider_arn.startswith('arn:'):
                              try:
                                  iam.delete_open_id_connect_provider(OpenIDConnectProviderArn=provider_arn)
                              except Exception:
                                  pass
                      cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
                      return

                  existing_arn = None
                  providers = iam.list_open_id_connect_providers()['OpenIDConnectProviderList']
                  for p in providers:
                      details = iam.get_open_id_connect_provider(OpenIDConnectProviderArn=p['Arn'])
                      if details.get('Url', '').rstrip('/') in ['accounts.google.com', 'https://accounts.google.com']:
                          existing_arn = p['Arn']
                          if AUDIENCE not in details.get('ClientIDList', []):
                              iam.add_client_id_to_open_id_connect_provider(
                                  OpenIDConnectProviderArn=existing_arn,
                                  ClientID=AUDIENCE
                              )
                          break

                  if existing_arn:
                      cfnresponse.send(event, context, cfnresponse.SUCCESS,
                          {'Arn': existing_arn, 'CreatedByUs': 'false'},
                          physicalResourceId=existing_arn)
                  else:
                      resp = iam.create_open_id_connect_provider(
                          Url=GOOGLE_ISSUER,
                          ClientIDList=[AUDIENCE],
                          ThumbprintList=[THUMBPRINT]
                      )
                      new_arn = resp['OpenIDConnectProviderArn']
                      cfnresponse.send(event, context, cfnresponse.SUCCESS,
                          {'Arn': new_arn, 'CreatedByUs': 'true'},
                          physicalResourceId=new_arn)
              except Exception as e:
                  traceback.print_exc()
                  cfnresponse.send(event, context, cfnresponse.FAILED, {'Error': str(e)})

  OIDCProviderLookup:
    Type: Custom::OIDCProviderLookup
    Properties:
      ServiceToken: !GetAtt OIDCProviderLookupFunction.Arn

  ZopNightWritePolicy:
    Type: AWS::IAM::ManagedPolicy
    Condition: IsReadWrite
    Properties:
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          # GENERATED-BEGIN: zopnight-aws-write-policy
          # Regenerated from docs/permissions/zopnight/aws.json by the
          # WIF CloudFormation workflow. Do not edit by hand.
          - Sid: ApplicationAutoscalingPermissions
            Effect: Allow
            Action:
              - application-autoscaling:DeleteScalingPolicy
              - application-autoscaling:DeleteScheduledAction
              - application-autoscaling:DeregisterScalableTarget
              - application-autoscaling:PutScalingPolicy
              - application-autoscaling:PutScheduledAction
              - application-autoscaling:RegisterScalableTarget
            Resource: '*'
          - Sid: ApprunnerPermissions
            Effect: Allow
            Action:
              - apprunner:PauseService
              - apprunner:ResumeService
            Resource: '*'
          - Sid: AutoscalingPermissions
            Effect: Allow
            Action:
              - autoscaling:CreateAutoScalingGroup
              - autoscaling:DeletePolicy
              - autoscaling:DeleteScheduledAction
              - autoscaling:PutScalingPolicy
              - autoscaling:PutScheduledUpdateGroupAction
              - autoscaling:UpdateAutoScalingGroup
            Resource: '*'
          - Sid: AwsMarketplacePermissions
            Effect: Allow
            Action:
              - aws-marketplace:Subscribe
              - aws-marketplace:Unsubscribe
              - aws-marketplace:ViewSubscriptions
            Resource: '*'
          - Sid: BedrockPermissions
            Effect: Allow
            Action:
              - bedrock:InvokeModel
              - bedrock:InvokeModelWithResponseStream
            Resource: '*'
          - Sid: Ec2Permissions
            Effect: Allow
            Action:
              - ec2:CreateLaunchTemplate
              - ec2:DeleteLaunchTemplate
              - ec2:StartInstances
              - ec2:StopInstances
            Resource: '*'
          - Sid: EcsPermissions
            Effect: Allow
            Action:
              - ecs:UpdateService
            Resource: '*'
          - Sid: EksPermissions
            Effect: Allow
            Action:
              - eks:TagResource
              - eks:UpdateNodegroupConfig
            Resource: '*'
          - Sid: ElasticbeanstalkPermissions
            Effect: Allow
            Action:
              - elasticbeanstalk:UpdateEnvironment
            Resource: '*'
          - Sid: EmrServerlessPermissions
            Effect: Allow
            Action:
              - emr-serverless:StartApplication
              - emr-serverless:StopApplication
            Resource: '*'
          - Sid: LambdaPermissions
            Effect: Allow
            Action:
              - lambda:DeleteFunctionConcurrency
              - lambda:PutFunctionConcurrency
              - lambda:TagResource
            Resource: '*'
          - Sid: LightsailPermissions
            Effect: Allow
            Action:
              - lightsail:StartInstance
              - lightsail:StopInstance
            Resource: '*'
          - Sid: RdsPermissions
            Effect: Allow
            Action:
              - rds:StartDBCluster
              - rds:StartDBInstance
              - rds:StopDBCluster
              - rds:StopDBInstance
            Resource: '*'
          - Sid: RedshiftPermissions
            Effect: Allow
            Action:
              - redshift:PauseCluster
              - redshift:ResumeCluster
            Resource: '*'
          - Sid: SagemakerPermissions
            Effect: Allow
            Action:
              - sagemaker:CreateEndpoint
              - sagemaker:DeleteEndpoint
              - sagemaker:StartNotebookInstance
              - sagemaker:StopNotebookInstance
              - sagemaker:UpdateCluster
            Resource: '*'
          - Sid: StatesPermissions
            Effect: Allow
            Action:
              - states:StopExecution
            Resource: '*'
          - Sid: WorkspacesPermissions
            Effect: Allow
            Action:
              - workspaces:StartWorkspaces
              - workspaces:StopWorkspaces
            Resource: '*'
          # GENERATED-END

  # Second managed policy. ZopNight's write permissions do not fit in one
  # managed policy (AWS caps a policy document at 6,144 chars), so they are
  # split by the catalog's own `role` field: scheduling writes stay in
  # ZopNightWritePolicy, remediation writes live here. The generator enforces
  # the ceiling per policy — see maxManagedPolicyChars in wif-cfn-build.
  ZopNightRemediationPolicy:
    Type: AWS::IAM::ManagedPolicy
    Condition: IsReadWrite
    Properties:
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          # GENERATED-BEGIN: zopnight-aws-remediation-policy
          # Regenerated from docs/permissions/zopnight/aws.json by the
          # WIF CloudFormation workflow. Do not edit by hand.
          - Sid: AcmPermissions
            Effect: Allow
            Action:
              - acm:AddTagsToCertificate
            Resource: '*'
          - Sid: ApigatewayPermissions
            Effect: Allow
            Action:
              - apigateway:DELETE
              - apigateway:POST
              - apigateway:PUT
            Resource: '*'
          - Sid: BedrockPermissions
            Effect: Allow
            Action:
              - bedrock:DeleteAgent
              - bedrock:DeleteCustomModel
              - bedrock:DeleteGuardrail
              - bedrock:DeleteImportedModel
              - bedrock:DeleteKnowledgeBase
              - bedrock:DeleteProvisionedModelThroughput
            Resource: '*'
          - Sid: CloudfrontPermissions
            Effect: Allow
            Action:
              - cloudfront:DeleteDistribution
              - cloudfront:GetDistributionConfig
              - cloudfront:UpdateDistribution
            Resource: '*'
          - Sid: CloudwatchPermissions
            Effect: Allow
            Action:
              - cloudwatch:DeleteAlarms
              - cloudwatch:DeleteDashboards
              - cloudwatch:TagResource
            Resource: '*'
          - Sid: CodebuildPermissions
            Effect: Allow
            Action:
              - codebuild:DeleteProject
            Resource: '*'
          - Sid: CodecommitPermissions
            Effect: Allow
            Action:
              - codecommit:DeleteRepository
            Resource: '*'
          - Sid: DynamodbPermissions
            Effect: Allow
            Action:
              - dynamodb:TagResource
            Resource: '*'
          - Sid: Ec2Permissions
            Effect: Allow
            Action:
              - ec2:CreateTags
              - ec2:DeleteInternetGateway
              - ec2:DeleteSnapshot
              - ec2:DeleteTransitGateway
              - ec2:DeleteVolume
              - ec2:DeleteVpcEndpoints
              - ec2:DeleteVpcPeeringConnection
              - ec2:DisassociateAddress
              - ec2:ModifyInstanceAttribute
              - ec2:ModifySnapshotTier
              - ec2:ModifyVolume
              - ec2:ReleaseAddress
              - ec2:RestoreSnapshotTier
            Resource: '*'
          - Sid: EcrPermissions
            Effect: Allow
            Action:
              - ecr:TagResource
            Resource: '*'
          - Sid: EcsPermissions
            Effect: Allow
            Action:
              - ecs:DeleteCluster
              - ecs:DeleteService
              - ecs:DeregisterTaskDefinition
              - ecs:RegisterTaskDefinition
              - ecs:TagResource
            Resource: '*'
          - Sid: EksPermissions
            Effect: Allow
            Action:
              - eks:DeleteNodegroup
            Resource: '*'
          - Sid: ElasticachePermissions
            Effect: Allow
            Action:
              - elasticache:AddTagsToResource
            Resource: '*'
          - Sid: ElasticfilesystemPermissions
            Effect: Allow
            Action:
              - elasticfilesystem:CreateTags
              - elasticfilesystem:DeleteFileSystem
              - elasticfilesystem:DeleteMountTarget
              - elasticfilesystem:TagResource
            Resource: '*'
          - Sid: ElasticloadbalancingPermissions
            Effect: Allow
            Action:
              - elasticloadbalancing:AddTags
              - elasticloadbalancing:DescribeLoadBalancerAttributes
              - elasticloadbalancing:ModifyLoadBalancerAttributes
            Resource: '*'
          - Sid: EsPermissions
            Effect: Allow
            Action:
              - es:AddTags
              - es:DeleteDomain
            Resource: '*'
          - Sid: GluePermissions
            Effect: Allow
            Action:
              - glue:TagResource
              - glue:UpdateJob
            Resource: '*'
          - Sid: KafkaPermissions
            Effect: Allow
            Action:
              - kafka:TagResource
            Resource: '*'
          - Sid: KinesisPermissions
            Effect: Allow
            Action:
              - kinesis:DeleteStream
            Resource: '*'
          - Sid: KmsPermissions
            Effect: Allow
            Action:
              - kms:ScheduleKeyDeletion
              - kms:TagResource
            Resource: '*'
          - Sid: LambdaPermissions
            Effect: Allow
            Action:
              - lambda:DeleteFunction
              - lambda:UpdateFunctionConfiguration
            Resource: '*'
          - Sid: LogsPermissions
            Effect: Allow
            Action:
              - logs:DeleteRetentionPolicy
              - logs:PutRetentionPolicy
              - logs:TagResource
            Resource: '*'
          - Sid: RdsPermissions
            Effect: Allow
            Action:
              - rds:AddTagsToResource
              - rds:DeleteDBProxy
              - rds:ModifyDBInstance
            Resource: '*'
          - Sid: RedshiftPermissions
            Effect: Allow
            Action:
              - redshift:CreateTags
            Resource: '*'
          - Sid: Route53Permissions
            Effect: Allow
            Action:
              - route53:ChangeTagsForResource
              - route53:DeleteHealthCheck
            Resource: '*'
          - Sid: S3Permissions
            Effect: Allow
            Action:
              - s3:GetAccelerateConfiguration
              - s3:GetIntelligentTieringConfiguration
              - s3:PutAccelerateConfiguration
              - s3:PutBucketTagging
              - s3:PutIntelligentTieringConfiguration
              - s3:PutLifecycleConfiguration
            Resource: '*'
          - Sid: SagemakerPermissions
            Effect: Allow
            Action:
              - sagemaker:CreateEndpointConfig
              - sagemaker:DeleteNotebookInstance
              - sagemaker:UpdateEndpoint
            Resource: '*'
          - Sid: SecretsmanagerPermissions
            Effect: Allow
            Action:
              - secretsmanager:DeleteSecret
            Resource: '*'
          - Sid: SesPermissions
            Effect: Allow
            Action:
              - ses:DeleteEmailIdentity
            Resource: '*'
          - Sid: SnsPermissions
            Effect: Allow
            Action:
              - sns:DeleteTopic
            Resource: '*'
          - Sid: SqsPermissions
            Effect: Allow
            Action:
              - sqs:DeleteQueue
            Resource: '*'
          - Sid: StatesPermissions
            Effect: Allow
            Action:
              - states:DeleteStateMachine
            Resource: '*'
          - Sid: TagPermissions
            Effect: Allow
            Action:
              - tag:TagResources
            Resource: '*'
          - Sid: Wafv2Permissions
            Effect: Allow
            Action:
              - wafv2:DeleteWebACL
              - wafv2:TagResource
            Resource: '*'
          # GENERATED-END

  # Discovery READ permissions, enumerated from the catalog rather than left to
  # AWS-managed ReadOnlyAccess — AWS does not keep that policy current with newer
  # actions, so a declared+probed read could otherwise be granted by nothing
  # (#3004). Split across three policies because the read set exceeds one managed
  # policy's char limit; the generator balances them and enforces the ceiling.
  ZopNightReadPolicyA:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          # GENERATED-BEGIN: zopnight-aws-read-policy-a
          # Regenerated from docs/permissions/zopnight/aws.json by the
          # WIF CloudFormation workflow. Do not edit by hand.
          - Sid: AcmPcaPermissions
            Effect: Allow
            Action:
              - acm-pca:ListCertificateAuthorities
            Resource: '*'
          - Sid: ApplicationAutoscalingPermissions
            Effect: Allow
            Action:
              - application-autoscaling:DescribeScalableTargets
              - application-autoscaling:DescribeScalingPolicies
              - application-autoscaling:DescribeScheduledActions
            Resource: '*'
          - Sid: AutoscalingPermissions
            Effect: Allow
            Action:
              - autoscaling:DescribeAutoScalingGroups
              - autoscaling:DescribePolicies
              - autoscaling:DescribeScheduledActions
            Resource: '*'
          - Sid: CePermissions
            Effect: Allow
            Action:
              - ce:GetCostAndUsage
              - ce:GetCostAndUsageWithResources
              - ce:GetDimensionValues
            Resource: '*'
          - Sid: CloudfrontPermissions
            Effect: Allow
            Action:
              - cloudfront:GetDistribution
              - cloudfront:ListDistributions
            Resource: '*'
          - Sid: CloudhsmPermissions
            Effect: Allow
            Action:
              - cloudhsm:DescribeClusters
            Resource: '*'
          - Sid: DynamodbPermissions
            Effect: Allow
            Action:
              - dynamodb:DescribeContinuousBackups
              - dynamodb:DescribeTable
              - dynamodb:ListTables
              - dynamodb:ListTagsOfResource
            Resource: '*'
          - Sid: EcsPermissions
            Effect: Allow
            Action:
              - ecs:DescribeClusters
              - ecs:DescribeContainerInstances
              - ecs:DescribeServices
              - ecs:DescribeTaskDefinition
              - ecs:DescribeTasks
              - ecs:ListClusters
              - ecs:ListContainerInstances
              - ecs:ListServices
              - ecs:ListTasks
            Resource: '*'
          - Sid: ElasticloadbalancingPermissions
            Effect: Allow
            Action:
              - elasticloadbalancing:DescribeLoadBalancers
              - elasticloadbalancing:DescribeTags
              - elasticloadbalancing:DescribeTargetGroups
              - elasticloadbalancing:DescribeTargetHealth
            Resource: '*'
          - Sid: ElasticmapreducePermissions
            Effect: Allow
            Action:
              - elasticmapreduce:DescribeCluster
              - elasticmapreduce:ListClusters
              - elasticmapreduce:ListInstanceFleets
              - elasticmapreduce:ListInstanceGroups
            Resource: '*'
          - Sid: FsxPermissions
            Effect: Allow
            Action:
              - fsx:DescribeFileSystems
            Resource: '*'
          - Sid: GlacierPermissions
            Effect: Allow
            Action:
              - glacier:ListVaults
            Resource: '*'
          - Sid: KmsPermissions
            Effect: Allow
            Action:
              - kms:DescribeKey
              - kms:ListKeys
              - kms:ListResourceTags
            Resource: '*'
          - Sid: LightsailPermissions
            Effect: Allow
            Action:
              - lightsail:GetInstances
            Resource: '*'
          - Sid: MqPermissions
            Effect: Allow
            Action:
              - mq:DescribeBroker
              - mq:ListBrokers
            Resource: '*'
          - Sid: NetworkFirewallPermissions
            Effect: Allow
            Action:
              - network-firewall:DescribeFirewall
              - network-firewall:ListFirewalls
            Resource: '*'
          - Sid: RdsPermissions
            Effect: Allow
            Action:
              - rds:DescribeDBClusters
              - rds:DescribeDBInstances
              - rds:DescribeDBProxies
              - rds:DescribeDBProxyTargets
              - rds:DescribeDBSnapshots
              - rds:DescribeDBSubnetGroups
              - rds:DescribeGlobalClusters
              - rds:ListTagsForResource
            Resource: '*'
          - Sid: RedshiftPermissions
            Effect: Allow
            Action:
              - redshift:DescribeClusters
            Resource: '*'
          - Sid: SagemakerPermissions
            Effect: Allow
            Action:
              - sagemaker:DescribeApp
              - sagemaker:DescribeAutoMLJobV2
              - sagemaker:DescribeCluster
              - sagemaker:DescribeCompilationJob
              - sagemaker:DescribeEndpoint
              - sagemaker:DescribeEndpointConfig
              - sagemaker:DescribeFeatureGroup
              - sagemaker:DescribeHyperParameterTuningJob
              - sagemaker:DescribeInferenceComponent
              - sagemaker:DescribeLabelingJob
              - sagemaker:DescribeNotebookInstance
              - sagemaker:DescribeProcessingJob
              - sagemaker:DescribeSpace
              - sagemaker:DescribeTrainingJob
              - sagemaker:DescribeTransformJob
              - sagemaker:ListApps
              - sagemaker:ListAutoMLJobs
              - sagemaker:ListClusters
              - sagemaker:ListCompilationJobs
              - sagemaker:ListEndpoints
              - sagemaker:ListFeatureGroups
              - sagemaker:ListHyperParameterTuningJobs
              - sagemaker:ListInferenceComponents
              - sagemaker:ListLabelingJobs
              - sagemaker:ListNotebookInstances
              - sagemaker:ListProcessingJobs
              - sagemaker:ListSpaces
              - sagemaker:ListTags
              - sagemaker:ListTrainingJobs
              - sagemaker:ListTransformJobs
            Resource: '*'
          - Sid: TransferPermissions
            Effect: Allow
            Action:
              - transfer:DescribeServer
              - transfer:ListServers
            Resource: '*'
          - Sid: WorkspacesPermissions
            Effect: Allow
            Action:
              - workspaces:DescribeWorkspaces
            Resource: '*'
          - Sid: XrayPermissions
            Effect: Allow
            Action:
              - xray:GetSamplingRules
            Resource: '*'
          # GENERATED-END

  ZopNightReadPolicyB:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          # GENERATED-BEGIN: zopnight-aws-read-policy-b
          # Regenerated from docs/permissions/zopnight/aws.json by the
          # WIF CloudFormation workflow. Do not edit by hand.
          - Sid: AcmPermissions
            Effect: Allow
            Action:
              - acm:DescribeCertificate
              - acm:ListCertificates
              - acm:ListTagsForCertificate
            Resource: '*'
          - Sid: AirflowPermissions
            Effect: Allow
            Action:
              - airflow:ListEnvironments
            Resource: '*'
          - Sid: ApprunnerPermissions
            Effect: Allow
            Action:
              - apprunner:DescribeService
              - apprunner:ListServices
            Resource: '*'
          - Sid: BackupPermissions
            Effect: Allow
            Action:
              - backup:ListBackupVaults
              - backup:ListRecoveryPointsByBackupVault
            Resource: '*'
          - Sid: BedrockPermissions
            Effect: Allow
            Action:
              - bedrock:GetAgent
              - bedrock:GetCustomModel
              - bedrock:GetEvaluationJob
              - bedrock:GetFoundationModelAvailability
              - bedrock:GetGuardrail
              - bedrock:GetKnowledgeBase
              - bedrock:GetMarketplaceModelEndpoint
              - bedrock:GetModelInvocationLoggingConfiguration
              - bedrock:GetProvisionedModelThroughput
              - bedrock:ListAgentActionGroups
              - bedrock:ListAgentAliases
              - bedrock:ListAgentVersions
              - bedrock:ListAgents
              - bedrock:ListCustomModels
              - bedrock:ListDataSources
              - bedrock:ListEvaluationJobs
              - bedrock:ListFlowAliases
              - bedrock:ListFlowVersions
              - bedrock:ListFlows
              - bedrock:ListFoundationModels
              - bedrock:ListGuardrails
              - bedrock:ListInferenceProfiles
              - bedrock:ListKnowledgeBases
              - bedrock:ListModelCustomizationJobs
              - bedrock:ListModelInvocationJobs
              - bedrock:ListPrompts
              - bedrock:ListProvisionedModelThroughputs
            Resource: '*'
          - Sid: CloudtrailPermissions
            Effect: Allow
            Action:
              - cloudtrail:DescribeTrails
              - cloudtrail:GetTrailStatus
              - cloudtrail:LookupEvents
            Resource: '*'
          - Sid: CodebuildPermissions
            Effect: Allow
            Action:
              - codebuild:BatchGetProjects
              - codebuild:ListBuildsForProject
              - codebuild:ListProjects
            Resource: '*'
          - Sid: CostOptimizationHubPermissions
            Effect: Allow
            Action:
              - cost-optimization-hub:GetPreferences
              - cost-optimization-hub:ListEnrollmentStatuses
              - cost-optimization-hub:ListRecommendations
            Resource: '*'
          - Sid: EcrPermissions
            Effect: Allow
            Action:
              - ecr:DescribeImages
              - ecr:DescribeRepositories
              - ecr:GetAuthorizationToken
              - ecr:GetLifecyclePolicy
              - ecr:GetRepositoryPolicy
              - ecr:ListTagsForResource
            Resource: '*'
          - Sid: EksPermissions
            Effect: Allow
            Action:
              - eks:DescribeAddon
              - eks:DescribeCluster
              - eks:DescribeNodegroup
              - eks:DescribeUpdate
              - eks:ListAccessEntries
              - eks:ListClusters
              - eks:ListFargateProfiles
              - eks:ListNodegroups
            Resource: '*'
          - Sid: ElasticachePermissions
            Effect: Allow
            Action:
              - elasticache:DescribeCacheClusters
              - elasticache:DescribeCacheSubnetGroups
              - elasticache:DescribeGlobalReplicationGroups
              - elasticache:DescribeReplicationGroups
              - elasticache:ListTagsForResource
            Resource: '*'
          - Sid: GluePermissions
            Effect: Allow
            Action:
              - glue:GetJob
              - glue:GetJobs
              - glue:GetTags
            Resource: '*'
          - Sid: IdentitystorePermissions
            Effect: Allow
            Action:
              - identitystore:ListUsers
            Resource: '*'
          - Sid: InvoicingPermissions
            Effect: Allow
            Action:
              - invoicing:ListInvoiceSummaries
            Resource: '*'
          - Sid: KafkaPermissions
            Effect: Allow
            Action:
              - kafka:ListClustersV2
            Resource: '*'
          - Sid: LambdaPermissions
            Effect: Allow
            Action:
              - lambda:GetFunction
              - lambda:GetFunctionConcurrency
              - lambda:GetFunctionConfiguration
              - lambda:ListEventSourceMappings
              - lambda:ListFunctions
              - lambda:ListTags
            Resource: '*'
          - Sid: S3Permissions
            Effect: Allow
            Action:
              - s3:GetBucketAccelerateConfiguration
              - s3:GetBucketLocation
              - s3:GetBucketPolicy
              - s3:GetBucketPolicyStatus
              - s3:GetBucketReplication
              - s3:GetBucketRequestPayment
              - s3:GetBucketTagging
              - s3:GetBucketVersioning
              - s3:GetLifecycleConfiguration
              - s3:GetObject
              - s3:ListAllMyBuckets
              - s3:ListBucket
              - s3:ListBucketMultipartUploads
              - s3:ListBucketVersions
            Resource: '*'
          - Sid: SecretsmanagerPermissions
            Effect: Allow
            Action:
              - secretsmanager:ListSecrets
            Resource: '*'
          - Sid: SsmPermissions
            Effect: Allow
            Action:
              - ssm:DescribeInstanceInformation
            Resource: '*'
          - Sid: StsPermissions
            Effect: Allow
            Action:
              - sts:GetCallerIdentity
            Resource: '*'
          - Sid: TagPermissions
            Effect: Allow
            Action:
              - tag:GetResources
            Resource: '*'
          - Sid: Wafv2Permissions
            Effect: Allow
            Action:
              - wafv2:GetWebACL
              - wafv2:ListTagsForResource
            Resource: '*'
          # GENERATED-END

  ZopNightReadPolicyC:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          # GENERATED-BEGIN: zopnight-aws-read-policy-c
          # Regenerated from docs/permissions/zopnight/aws.json by the
          # WIF CloudFormation workflow. Do not edit by hand.
          - Sid: AppstreamPermissions
            Effect: Allow
            Action:
              - appstream:DescribeFleets
            Resource: '*'
          - Sid: CloudwatchPermissions
            Effect: Allow
            Action:
              - cloudwatch:DescribeAlarms
              - cloudwatch:GetMetricData
              - cloudwatch:GetMetricStatistics
              - cloudwatch:ListDashboards
              - cloudwatch:ListMetricStreams
              - cloudwatch:ListMetrics
              - cloudwatch:ListTagsForResource
            Resource: '*'
          - Sid: ConfigPermissions
            Effect: Allow
            Action:
              - config:DescribeConfigRuleEvaluationStatus
              - config:DescribeConfigRules
              - config:DescribeConfigurationRecorderStatus
              - config:DescribeConfigurationRecorders
            Resource: '*'
          - Sid: DaxPermissions
            Effect: Allow
            Action:
              - dax:DescribeClusters
            Resource: '*'
          - Sid: DmsPermissions
            Effect: Allow
            Action:
              - dms:DescribeReplicationInstances
            Resource: '*'
          - Sid: Ec2Permissions
            Effect: Allow
            Action:
              - ec2:DescribeAddresses
              - ec2:DescribeAvailabilityZones
              - ec2:DescribeFlowLogs
              - ec2:DescribeImages
              - ec2:DescribeInstances
              - ec2:DescribeLaunchTemplates
              - ec2:DescribeNatGateways
              - ec2:DescribeNetworkInterfaces
              - ec2:DescribeRegions
              - ec2:DescribeRouteTables
              - ec2:DescribeSecurityGroupRules
              - ec2:DescribeSecurityGroups
              - ec2:DescribeSnapshots
              - ec2:DescribeSubnets
              - ec2:DescribeTags
              - ec2:DescribeTransitGatewayPeeringAttachments
              - ec2:DescribeTransitGateways
              - ec2:DescribeVolumes
              - ec2:DescribeVpcEndpoints
              - ec2:DescribeVpcPeeringConnections
              - ec2:DescribeVpcs
              - ec2:DescribeVpnConnections
            Resource: '*'
          - Sid: ElasticbeanstalkPermissions
            Effect: Allow
            Action:
              - elasticbeanstalk:DescribeConfigurationSettings
              - elasticbeanstalk:DescribeEnvironments
            Resource: '*'
          - Sid: ElasticfilesystemPermissions
            Effect: Allow
            Action:
              - elasticfilesystem:DescribeFileSystems
              - elasticfilesystem:DescribeMountTargets
              - elasticfilesystem:DescribeReplicationConfigurations
            Resource: '*'
          - Sid: EmrServerlessPermissions
            Effect: Allow
            Action:
              - emr-serverless:GetApplication
              - emr-serverless:ListApplications
            Resource: '*'
          - Sid: EsPermissions
            Effect: Allow
            Action:
              - es:DescribeDomains
              - es:DescribeOutboundConnections
              - es:ListDomainNames
              - es:ListTags
            Resource: '*'
          - Sid: GuarddutyPermissions
            Effect: Allow
            Action:
              - guardduty:GetDetector
              - guardduty:ListDetectors
            Resource: '*'
          - Sid: IamPermissions
            Effect: Allow
            Action:
              - iam:GenerateCredentialReport
              - iam:GetAccountPasswordPolicy
              - iam:GetAccountSummary
              - iam:GetCredentialReport
              - iam:GetGroup
              - iam:GetInstanceProfile
              - iam:GetLoginProfile
              - iam:GetOpenIDConnectProvider
              - iam:GetRole
              - iam:ListAccessKeys
              - iam:ListAttachedRolePolicies
              - iam:ListGroupPolicies
              - iam:ListGroups
              - iam:ListGroupsForUser
              - iam:ListMFADevices
              - iam:ListOpenIDConnectProviders
              - iam:ListRolePolicies
              - iam:ListRoles
              - iam:ListUserPolicies
              - iam:ListUserTags
              - iam:ListUsers
              - iam:SimulatePrincipalPolicy
            Resource: '*'
          - Sid: Inspector2Permissions
            Effect: Allow
            Action:
              - inspector2:BatchGetAccountStatus
            Resource: '*'
          - Sid: KinesisPermissions
            Effect: Allow
            Action:
              - kinesis:DescribeStream
              - kinesis:DescribeStreamSummary
              - kinesis:ListStreams
            Resource: '*'
          - Sid: LogsPermissions
            Effect: Allow
            Action:
              - logs:DescribeLogGroups
              - logs:DescribeMetricFilters
              - logs:DescribeSubscriptionFilters
              - logs:GetQueryResults
              - logs:ListTagsForResource
              - logs:StartQuery
            Resource: '*'
          - Sid: MemorydbPermissions
            Effect: Allow
            Action:
              - memorydb:DescribeClusters
            Resource: '*'
          - Sid: ResourceExplorer2Permissions
            Effect: Allow
            Action:
              - resource-explorer-2:Search
            Resource: '*'
          - Sid: Route53Permissions
            Effect: Allow
            Action:
              - route53:GetChange
              - route53:GetHealthCheckStatus
              - route53:GetHostedZone
              - route53:ListHealthChecks
              - route53:ListHostedZones
              - route53:ListResourceRecordSets
              - route53:ListTagsForResources
            Resource: '*'
          - Sid: Route53resolverPermissions
            Effect: Allow
            Action:
              - route53resolver:ListResolverEndpoints
            Resource: '*'
          - Sid: SesPermissions
            Effect: Allow
            Action:
              - ses:ListEmailIdentities
            Resource: '*'
          - Sid: SsoPermissions
            Effect: Allow
            Action:
              - sso:ListInstances
            Resource: '*'
          - Sid: StatesPermissions
            Effect: Allow
            Action:
              - states:ListExecutions
            Resource: '*'
          # GENERATED-END

  # Catalog reads AWS-managed ReadOnlyAccess leaves out (catalog role
  # ZopNightReadPolicy). Its own policy, so the policy a customer is told to fix
  # is the one this stack carries. Kept out of the A/B/C bins by the generator.
  ZopNightReadPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          # GENERATED-BEGIN: zopnight-aws-custom-read-policy
          # Regenerated from docs/permissions/zopnight/aws.json by the
          # WIF CloudFormation workflow. Do not edit by hand.
          - Sid: AirflowPermissions
            Effect: Allow
            Action:
              - airflow:GetEnvironment
            Resource: '*'
          - Sid: BcmDataExportsPermissions
            Effect: Allow
            Action:
              - bcm-data-exports:GetExport
              - bcm-data-exports:ListExports
            Resource: '*'
          - Sid: BedrockPermissions
            Effect: Allow
            Action:
              - bedrock:ListCustomModelDeployments
              - bedrock:ListDataAutomationProjects
              - bedrock:ListImportedModels
              - bedrock:ListMarketplaceModelEndpoints
              - bedrock:ListModelCopyJobs
              - bedrock:ListTagsForResource
            Resource: '*'
          - Sid: TimestreamInfluxdbPermissions
            Effect: Allow
            Action:
              - timestream-influxdb:ListDbInstances
            Resource: '*'
          # GENERATED-END

  ZopNightRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Federated: !GetAtt OIDCProviderLookup.Arn
            Action: sts:AssumeRoleWithWebIdentity
            Condition:
              StringEquals:
                "accounts.google.com:aud": "108571531846883966629"
                "accounts.google.com:sub": "108571531846883966629"
      ManagedPolicyArns:
        # ReadOnlyAccess stays as a net for reads we have not declared; the
        # ZopNight read managed policies carry every catalog read explicitly.
        - arn:aws:iam::aws:policy/ReadOnlyAccess
        - !Ref ZopNightReadPolicyA
        - !Ref ZopNightReadPolicyB
        - !Ref ZopNightReadPolicyC
        - !Ref ZopNightReadPolicy
        - !If [IsReadWrite, !Ref ZopNightWritePolicy, !Ref 'AWS::NoValue']
        - !If [IsReadWrite, !Ref ZopNightRemediationPolicy, !Ref 'AWS::NoValue']

Outputs:
  RoleArn:
    Description: The ARN of the ZopNight IAM Role - paste this in ZopNight
    Value: !GetAtt ZopNightRole.Arn
