AWSTemplateFormatVersion: '2010-09-09'
Description: >-
  Creates the cross-account role Sheetloom uses to deploy Sheetloom into this
  account. Permissions are scoped to a single tenant in the region this stack is
  launched in. When the stack completes, the role ARN is sent to Sheetloom
  automatically; delete this stack at any time to remove Sheetloom's access.

Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label: { default: Provided by Sheetloom }
        Parameters: [Tenant, ExternalId]
      - Label: { default: Advanced (leave as default) }
        Parameters: [SheetloomAccountId, ImageAccountId, CallbackUrl]

Parameters:
  Tenant:
    Type: String
    Description: Tenant name provided by Sheetloom.
    AllowedPattern: '^[a-z0-9][a-z0-9-]*[a-z0-9]$'
    # CloudFormation shortens auto-generated names that would exceed the service limit, which
    # breaks the sheetloom-<tenant>-* patterns below. 28 is the longest tenant where
    # sheetloom-<tenant>-AdminIAMRole-<12> (64) and sheetloom-<tenant>-dbinstance1-<12> (63) still fit.
    MaxLength: 28
    ConstraintDescription: Lowercase letters, numbers and hyphens; must start and end with a letter or number.
  ExternalId:
    Type: String
    NoEcho: true
    MinLength: 16
    Description: External ID provided by Sheetloom.
  SheetloomAccountId:
    Type: String
    Default: '383060934358'
    AllowedPattern: '^\d{12}$'
    Description: Sheetloom AWS account allowed to assume the role.
  ImageAccountId:
    Type: String
    Default: '383060934358'
    AllowedPattern: '^\d{12}$'
    Description: Sheetloom AWS account that hosts the container images.
  CallbackUrl:
    Type: String
    Default: 'https://ul0zf6fg5m.execute-api.eu-west-1.amazonaws.com/prod/marketplace/role-callback'
    AllowedPattern: '^https://.+'
    Description: Sheetloom endpoint that receives the role ARN when this stack is created or deleted.

Resources:
  SheetloomDeployRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub 'SheetloomDeployRole-${Tenant}'
      Description: Assumed by Sheetloom to deploy and maintain the Sheetloom stack.
      MaxSessionDuration: 14400
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              AWS: !Sub 'arn:aws:iam::${SheetloomAccountId}:root'
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                sts:ExternalId: !Ref ExternalId
      ManagedPolicyArns:
        - !Ref OrchestrationPolicy
        - !Ref ComputePolicy
        - !Ref NetworkDataPolicy
        - !Ref IdentityPolicy

  # CloudFormation / SAM, S3, SSM, Secrets Manager, KMS
  OrchestrationPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      ManagedPolicyName: !Sub 'SheetloomDeploy-${Tenant}-Orchestration'
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Sid: CfnStacks
            Effect: Allow
            Action:
              - cloudformation:CreateStack
              - cloudformation:UpdateStack
              - cloudformation:DeleteStack
              - cloudformation:DescribeStacks
              - cloudformation:DescribeStackEvents
              - cloudformation:DescribeStackResource
              - cloudformation:DescribeStackResources
              - cloudformation:ListStackResources
              - cloudformation:GetTemplate
              - cloudformation:GetTemplateSummary
              - cloudformation:CreateChangeSet
              - cloudformation:DescribeChangeSet
              - cloudformation:ExecuteChangeSet
              - cloudformation:DeleteChangeSet
              - cloudformation:ListChangeSets
            Resource:
              - !Sub 'arn:aws:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/sheetloom-${Tenant}/*'
              - !Sub 'arn:aws:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/aws-sam-cli-managed-default/*'
          # sam deploy (resolve_image_repos) checks whether an image companion stack exists; it never creates one.
          - Sid: SamCompanionStackLookup
            Effect: Allow
            Action: cloudformation:DescribeStacks
            Resource: !Sub 'arn:aws:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/sheetloom-${Tenant}-*-CompanionStack/*'
          - Sid: CfnServerlessTransform
            Effect: Allow
            Action: cloudformation:CreateChangeSet
            Resource: !Sub 'arn:aws:cloudformation:${AWS::Region}:aws:transform/Serverless-2016-10-31'
          - Sid: CfnGlobal
            Effect: Allow
            Action:
              - cloudformation:ValidateTemplate
              - cloudformation:ListStacks
              - cloudformation:ListExports
              # Pre-provisioning quota checks CloudFormation runs as the caller
              - servicequotas:GetServiceQuota
              - iam:GetAccountSummary
              - lambda:GetAccountSettings
            Resource: '*'
          # The CloudFormation S3 handler reads back every bucket setting after create/update.
          - Sid: StackBucketsReadBack
            Effect: Allow
            Action:
              - s3:GetBucket*
              - s3:Get*Configuration
              - s3:ListTagsForResource
            Resource:
              - 'arn:aws:s3:::aws-sam-cli-managed-default-samclisourcebucket-*'
              - !Sub 'arn:aws:s3:::${Tenant}-sheetloom-templates'
          - Sid: SamArtifactBucket
            Effect: Allow
            Action:
              - s3:CreateBucket
              - s3:DeleteBucket
              - s3:ListBucket
              - s3:PutBucketPolicy
              - s3:DeleteBucketPolicy
              - s3:PutBucketVersioning
              - s3:PutEncryptionConfiguration
              - s3:PutBucketPublicAccessBlock
              - s3:PutBucketTagging
              - s3:TagResource
              - s3:GetObject
              - s3:GetObjectVersion
              - s3:PutObject
            Resource:
              - 'arn:aws:s3:::aws-sam-cli-managed-default-samclisourcebucket-*'
          - Sid: TenantBucket
            Effect: Allow
            Action:
              - s3:CreateBucket
              - s3:DeleteBucket
              - s3:ListBucket
              - s3:ListBucketVersions
              - s3:ListBucketMultipartUploads
              - s3:AbortMultipartUpload
              - s3:PutBucketVersioning
              - s3:PutBucketCORS
              - s3:PutBucketTagging
              - s3:TagResource
              - s3:GetObject
              - s3:PutObject
              - s3:DeleteObject
              - s3:DeleteObjectVersion
            Resource:
              - !Sub 'arn:aws:s3:::${Tenant}-sheetloom-templates'
              - !Sub 'arn:aws:s3:::${Tenant}-sheetloom-templates/*'
          - Sid: SampleBucketRead
            Effect: Allow
            Action:
              - s3:ListBucket
              - s3:GetObject
            Resource:
              - 'arn:aws:s3:::sheetloom-sample-bucket'
              - 'arn:aws:s3:::sheetloom-sample-bucket/*'
          - Sid: AllowedTenantsParameter
            Effect: Allow
            Action:
              - ssm:PutParameter
              - ssm:GetParameter
              - ssm:GetParameters
              - ssm:DeleteParameter
              - ssm:AddTagsToResource
              - ssm:RemoveTagsFromResource
              - ssm:ListTagsForResource
            Resource: !Sub 'arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/api/allowed-tenants'
          # sheetloom/<tenant> (DB credentials) and sheetloom/<tenant>/automation; the -?????? is the random ARN suffix.
          - Sid: TenantSecrets
            Effect: Allow
            Action:
              - secretsmanager:CreateSecret
              - secretsmanager:DeleteSecret
              - secretsmanager:DescribeSecret
              - secretsmanager:UpdateSecret
              - secretsmanager:GetSecretValue
              - secretsmanager:PutSecretValue
              - secretsmanager:TagResource
              - secretsmanager:UntagResource
            Resource:
              - !Sub 'arn:aws:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:sheetloom/${Tenant}-??????'
              - !Sub 'arn:aws:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:sheetloom/${Tenant}/automation-??????'
          - Sid: SecretsGlobal
            Effect: Allow
            Action:
              - secretsmanager:GetRandomPassword
              - secretsmanager:ListSecrets
            Resource: '*'
          # AWS-managed keys only, and only when used through these services.
          - Sid: KmsViaManagedServices
            Effect: Allow
            Action:
              - kms:Encrypt
              - kms:Decrypt
              - kms:GenerateDataKey
              - kms:DescribeKey
            Resource: '*'
            Condition:
              StringEquals:
                kms:ViaService:
                  - !Sub 'secretsmanager.${AWS::Region}.amazonaws.com'
                  - !Sub 'lambda.${AWS::Region}.amazonaws.com'
                  - !Sub 'rds.${AWS::Region}.amazonaws.com'
                  - !Sub 's3.${AWS::Region}.amazonaws.com'

  # Lambda, ECR (cross-account pull), API Gateway, EventBridge
  ComputePolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      ManagedPolicyName: !Sub 'SheetloomDeploy-${Tenant}-Compute'
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Sid: LambdaFunctions
            Effect: Allow
            Action:
              - lambda:CreateFunction
              - lambda:DeleteFunction
              - lambda:GetFunction
              - lambda:GetFunctionConfiguration
              - lambda:UpdateFunctionCode
              - lambda:UpdateFunctionConfiguration
              - lambda:AddPermission
              - lambda:RemovePermission
              - lambda:GetPolicy
              - lambda:TagResource
              - lambda:UntagResource
              - lambda:ListTags
              - lambda:GetFunctionRecursionConfig
              - lambda:PutFunctionRecursionConfig
              - lambda:GetRuntimeManagementConfig
              - lambda:GetFunctionCodeSigningConfig
              - lambda:GetFunctionScalingConfig
            Resource: !Sub 'arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:sheetloom-*'
          - Sid: EcrPullSheetloomImages
            Effect: Allow
            Action:
              - ecr:BatchGetImage
              - ecr:GetDownloadUrlForLayer
              - ecr:DescribeImages
            Resource: !Sub 'arn:aws:ecr:${AWS::Region}:${ImageAccountId}:repository/sheetloom-*'
          - Sid: ApiGateway
            Effect: Allow
            Action:
              - apigateway:GET
              - apigateway:POST
              - apigateway:PUT
              - apigateway:PATCH
              - apigateway:DELETE
            Resource:
              - !Sub 'arn:aws:apigateway:${AWS::Region}::/restapis'
              - !Sub 'arn:aws:apigateway:${AWS::Region}::/restapis/*'
              - !Sub 'arn:aws:apigateway:${AWS::Region}::/tags/*'
          - Sid: EcrEventBus
            Effect: Allow
            Action:
              - events:CreateEventBus
              - events:DeleteEventBus
              - events:DescribeEventBus
              - events:UpdateEventBus
              - events:TagResource
              - events:UntagResource
              - events:ListTagsForResource
            Resource: !Sub 'arn:aws:events:${AWS::Region}:${AWS::AccountId}:event-bus/${Tenant}-sheetloom-ecr-bus'
          # PutPermission/RemovePermission have no resource-level scoping in IAM (the bus is named in the request).
          - Sid: EcrEventBusPolicy
            Effect: Allow
            Action:
              - events:PutPermission
              - events:RemovePermission
            Resource: '*'
            Condition:
              StringEquals:
                aws:RequestedRegion: !Ref AWS::Region
          - Sid: EcrEventRule
            Effect: Allow
            Action:
              - events:PutRule
              - events:DeleteRule
              - events:DescribeRule
              - events:PutTargets
              - events:RemoveTargets
              - events:ListTargetsByRule
              - events:TagResource
              - events:UntagResource
              - events:ListTagsForResource
            Resource: !Sub 'arn:aws:events:${AWS::Region}:${AWS::AccountId}:rule/${Tenant}-sheetloom-ecr-bus/SheetloomImageRefresher'

  # VPC + bastion, Aurora cluster, RDS Data API
  NetworkDataPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      ManagedPolicyName: !Sub 'SheetloomDeploy-${Tenant}-NetworkData'
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          # The template doesn't tag EC2 resources, so these are limited to the region rather than by tag.
          - Sid: Ec2NetworkAndBastion
            Effect: Allow
            Action:
              - ec2:CreateVpc
              - ec2:DeleteVpc
              - ec2:ModifyVpcAttribute
              - ec2:CreateSubnet
              - ec2:DeleteSubnet
              - ec2:ModifySubnetAttribute
              - ec2:CreateInternetGateway
              - ec2:DeleteInternetGateway
              - ec2:AttachInternetGateway
              - ec2:DetachInternetGateway
              - ec2:CreateRouteTable
              - ec2:DeleteRouteTable
              - ec2:AssociateRouteTable
              - ec2:DisassociateRouteTable
              - ec2:CreateRoute
              - ec2:DeleteRoute
              - ec2:CreateVpcEndpoint
              - ec2:DeleteVpcEndpoints
              - ec2:ModifyVpcEndpoint
              - ec2:CreateSecurityGroup
              - ec2:DeleteSecurityGroup
              - ec2:AuthorizeSecurityGroupIngress
              - ec2:RevokeSecurityGroupIngress
              - ec2:AuthorizeSecurityGroupEgress
              - ec2:RevokeSecurityGroupEgress
              - ec2:RunInstances
              - ec2:TerminateInstances
              - ec2:ModifyInstanceAttribute
              - ec2:AllocateAddress
              - ec2:ReleaseAddress
              - ec2:AssociateAddress
              - ec2:DisassociateAddress
              - ec2:CreateTags
              - ec2:DeleteTags
            Resource: '*'
            Condition:
              StringEquals:
                aws:RequestedRegion: !Ref AWS::Region
          # Read-only. Also used by RDS on the caller's behalf when it validates the subnet group.
          - Sid: Ec2Describe
            Effect: Allow
            Action:
              - ec2:DescribeVpcs
              - ec2:DescribeVpcAttribute
              - ec2:DescribeSubnets
              - ec2:DescribeNetworkAcls
              - ec2:DescribeRouteTables
              - ec2:DescribeInternetGateways
              - ec2:DescribeSecurityGroups
              - ec2:DescribeSecurityGroupRules
              - ec2:DescribeVpcEndpoints
              - ec2:DescribeInstances
              - ec2:DescribeInstanceStatus
              - ec2:DescribeInstanceAttribute
              - ec2:DescribeInstanceCreditSpecifications
              - ec2:DescribeLaunchTemplates
              - ec2:DescribeVolumes
              - ec2:DescribeAddresses
              - ec2:DescribeAvailabilityZones
              - ec2:DescribeImages
              - ec2:DescribeKeyPairs
              - ec2:DescribeNetworkInterfaces
              - ec2:DescribePrefixLists
              - ec2:DescribeAccountAttributes
              - ssm:ListAssociations
              - ssm:DescribeAssociation
            Resource: '*'
          - Sid: BastionKeyPair
            Effect: Allow
            Action:
              - ec2:CreateKeyPair
              - ec2:DeleteKeyPair
            Resource: !Sub 'arn:aws:ec2:${AWS::Region}:${AWS::AccountId}:key-pair/${Tenant}-sheetloom-bastion-keypair'
          # RDS also authorizes these calls against the default parameter and option groups the cluster uses.
          - Sid: RdsClusterAndInstances
            Effect: Allow
            Action:
              - rds:CreateDBCluster
              - rds:DeleteDBCluster
              - rds:ModifyDBCluster
              - rds:EnableHttpEndpoint
              - rds:DisableHttpEndpoint
              - rds:CreateDBInstance
              - rds:DeleteDBInstance
              - rds:ModifyDBInstance
              - rds:CreateDBSubnetGroup
              - rds:DeleteDBSubnetGroup
              - rds:ModifyDBSubnetGroup
              - rds:AddTagsToResource
              - rds:RemoveTagsFromResource
              - rds:ListTagsForResource
            Resource:
              - !Sub 'arn:aws:rds:${AWS::Region}:${AWS::AccountId}:cluster:${Tenant}-sheetloom-db-cluster'
              - !Sub 'arn:aws:rds:${AWS::Region}:${AWS::AccountId}:db:sheetloom-${Tenant}-*'
              - !Sub 'arn:aws:rds:${AWS::Region}:${AWS::AccountId}:subgrp:sheetloom-${Tenant}-*'
              - !Sub 'arn:aws:rds:${AWS::Region}:${AWS::AccountId}:cluster-pg:default.aurora-postgresql*'
              - !Sub 'arn:aws:rds:${AWS::Region}:${AWS::AccountId}:pg:default.aurora-postgresql*'
              - !Sub 'arn:aws:rds:${AWS::Region}:${AWS::AccountId}:og:default:aurora-postgresql*'
          - Sid: RdsDescribe
            Effect: Allow
            Action:
              - rds:DescribeDBClusters
              - rds:DescribeDBInstances
              - rds:DescribeDBSubnetGroups
              - rds:DescribeDBEngineVersions
              - rds:DescribeOrderableDBInstanceOptions
              - rds:DescribeEvents
              - rds:DescribeGlobalClusters
            Resource: '*'
          - Sid: RdsDataApi
            Effect: Allow
            Action: rds-data:ExecuteStatement
            Resource: !Sub 'arn:aws:rds:${AWS::Region}:${AWS::AccountId}:cluster:${Tenant}-sheetloom-db-cluster'

  # IAM roles created by the Sheetloom stack, Cognito, Amplify
  IdentityPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      ManagedPolicyName: !Sub 'SheetloomDeploy-${Tenant}-Identity'
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Sid: StackRoles
            Effect: Allow
            Action:
              - iam:CreateRole
              - iam:DeleteRole
              - iam:GetRole
              - iam:UpdateRole
              - iam:UpdateRoleDescription
              - iam:UpdateAssumeRolePolicy
              - iam:PutRolePolicy
              - iam:GetRolePolicy
              - iam:DeleteRolePolicy
              - iam:ListRolePolicies
              - iam:ListAttachedRolePolicies
              - iam:TagRole
              - iam:UntagRole
            Resource:
              - !Sub 'arn:aws:iam::${AWS::AccountId}:role/sheetloom-${Tenant}-*'
              - !Sub 'arn:aws:iam::${AWS::AccountId}:role/${Tenant}-sheetloom-lambda-execution-role'
              - !Sub 'arn:aws:iam::${AWS::AccountId}:role/${Tenant}-SheetloomGlueRole'
              # Auto-named: CloudFormation shortens the stack-name part when the full name is over 64 chars
              # (tenants longer than 11), so the tenant can't be matched exactly. Only this one role name is covered.
              - !Sub 'arn:aws:iam::${AWS::AccountId}:role/sheetloom-*-GetSecretsLambdaExecution-*'
          - Sid: PassStackRoles
            Effect: Allow
            Action: iam:PassRole
            Resource:
              - !Sub 'arn:aws:iam::${AWS::AccountId}:role/sheetloom-${Tenant}-*'
              - !Sub 'arn:aws:iam::${AWS::AccountId}:role/${Tenant}-sheetloom-lambda-execution-role'
            Condition:
              StringEquals:
                iam:PassedToService: lambda.amazonaws.com
          # Cognito doesn't send iam:PassedToService when it checks PassRole, so these
          # three roles are named exactly instead. Each one trusts only Cognito.
          - Sid: PassCognitoRoles
            Effect: Allow
            Action: iam:PassRole
            Resource:
              - !Sub 'arn:aws:iam::${AWS::AccountId}:role/sheetloom-${Tenant}-SmsRole-*'
              - !Sub 'arn:aws:iam::${AWS::AccountId}:role/sheetloom-${Tenant}-AdminIAMRole-*'
              - !Sub 'arn:aws:iam::${AWS::AccountId}:role/sheetloom-${Tenant}-UserIAMRole-*'
          - Sid: ServiceLinkedRoles
            Effect: Allow
            Action: iam:CreateServiceLinkedRole
            Resource: '*'
            Condition:
              StringEquals:
                iam:AWSServiceName:
                  - ops.apigateway.amazonaws.com
                  - rds.amazonaws.com
          # These have no resource-level scoping in IAM. SetIdentityPoolRoles can only attach roles PassStackRoles allows.
          - Sid: CognitoGlobal
            Effect: Allow
            Action:
              - cognito-idp:CreateUserPool
              - cognito-idp:ListUserPools
              - cognito-idp:DescribeUserPoolDomain
              - cognito-identity:CreateIdentityPool
              - cognito-identity:ListIdentityPools
              - cognito-identity:SetIdentityPoolRoles
              - sns:GetSMSSandboxAccountStatus
              - sms-voice:DescribeAccountAttributes
            Resource: '*'
            Condition:
              StringEquals:
                aws:RequestedRegion: !Ref AWS::Region
          - Sid: CognitoUserPool
            Effect: Allow
            Action:
              - cognito-idp:DescribeUserPool
              - cognito-idp:UpdateUserPool
              - cognito-idp:DeleteUserPool
              - cognito-idp:AddCustomAttributes
              - cognito-idp:GetUserPoolMfaConfig
              - cognito-idp:SetUserPoolMfaConfig
              - cognito-idp:CreateUserPoolClient
              - cognito-idp:DescribeUserPoolClient
              - cognito-idp:UpdateUserPoolClient
              - cognito-idp:DeleteUserPoolClient
              - cognito-idp:ListUserPoolClients
              - cognito-idp:ListUserPoolClientSecrets
              - cognito-idp:CreateUserPoolDomain
              - cognito-idp:UpdateUserPoolDomain
              - cognito-idp:DeleteUserPoolDomain
              - cognito-idp:CreateGroup
              - cognito-idp:GetGroup
              - cognito-idp:UpdateGroup
              - cognito-idp:DeleteGroup
              - cognito-idp:CreateResourceServer
              - cognito-idp:DescribeResourceServer
              - cognito-idp:UpdateResourceServer
              - cognito-idp:DeleteResourceServer
              - cognito-idp:AdminCreateUser
              - cognito-idp:AdminAddUserToGroup
              - cognito-idp:TagResource
              - cognito-idp:UntagResource
              - cognito-idp:ListTagsForResource
            Resource: !Sub 'arn:aws:cognito-idp:${AWS::Region}:${AWS::AccountId}:userpool/*'
          - Sid: CognitoIdentityPool
            Effect: Allow
            Action:
              - cognito-identity:DescribeIdentityPool
              - cognito-identity:UpdateIdentityPool
              - cognito-identity:DeleteIdentityPool
              - cognito-identity:GetIdentityPoolRoles
              - cognito-identity:TagResource
              - cognito-identity:UntagResource
              - cognito-identity:ListTagsForResource
            Resource: !Sub 'arn:aws:cognito-identity:${AWS::Region}:${AWS::AccountId}:identitypool/*'
          - Sid: AmplifyGlobal
            Effect: Allow
            Action:
              - amplify:CreateApp
              - amplify:ListApps
            Resource: '*'
            Condition:
              StringEquals:
                aws:RequestedRegion: !Ref AWS::Region
          - Sid: AmplifyApp
            Effect: Allow
            Action:
              - amplify:GetApp
              - amplify:UpdateApp
              - amplify:DeleteApp
              - amplify:CreateBranch
              - amplify:GetBranch
              - amplify:DeleteBranch
              - amplify:ListBranches
              - amplify:StartJob
              - amplify:GetJob
              - amplify:ListJobs
              - amplify:TagResource
            Resource: !Sub 'arn:aws:amplify:${AWS::Region}:${AWS::AccountId}:apps/*'

  # Sends the role ARN to Sheetloom on create, and tells Sheetloom access was removed on delete.
  # Sheetloom checks the ExternalId and that this account is the Marketplace subscriber;
  # if either is wrong the stack fails and the role is rolled back.
  # Named outside the sheetloom-* patterns above so the deploy role cannot modify it.
  RegistrationFunctionRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub 'SheetloomAccessCallbackRole-${Tenant}'
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: Logs
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - logs:CreateLogGroup
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Resource: !Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/SheetloomAccessCallback-${Tenant}:*'

  RegistrationFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Sub 'SheetloomAccessCallback-${Tenant}'
      Description: Notifies Sheetloom of the deploy role ARN. Runs only when this stack is created, updated or deleted.
      Runtime: python3.12
      Handler: index.handler
      Timeout: 30
      MemorySize: 128
      Role: !GetAtt RegistrationFunctionRole.Arn
      Code:
        ZipFile: |
          import json
          import urllib.error
          import urllib.request

          import cfnresponse


          def handler(event, context):
              props = event["ResourceProperties"]
              request_type = event["RequestType"]
              body = json.dumps({
                  "request_type": request_type,
                  "tenant_id": props["Tenant"],
                  "external_id": props["ExternalId"],
                  "role_arn": props["RoleArn"],
                  "region": props["Region"],
                  "stack_id": event["StackId"],
              }).encode()
              req = urllib.request.Request(
                  props["CallbackUrl"], data=body, method="POST",
                  headers={"Content-Type": "application/json"},
              )
              physical_id = "sheetloom-access-" + props["Tenant"]
              try:
                  with urllib.request.urlopen(req, timeout=20) as resp:
                      resp.read()
                  cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, physical_id)
              except Exception as exc:
                  reason = str(exc)
                  if isinstance(exc, urllib.error.HTTPError):
                      try:
                          reason = json.loads(exc.read().decode()).get("error", reason)
                      except Exception:
                          pass
                  print("Sheetloom callback failed: " + reason)
                  # Never block stack deletion on our endpoint.
                  status = cfnresponse.SUCCESS if request_type == "Delete" else cfnresponse.FAILED
                  cfnresponse.send(event, context, status, {}, physical_id, reason="Sheetloom: " + reason)

  RegisterRoleWithSheetloom:
    Type: Custom::SheetloomAccessRegistration
    Properties:
      ServiceToken: !GetAtt RegistrationFunction.Arn
      Tenant: !Ref Tenant
      ExternalId: !Ref ExternalId
      RoleArn: !GetAtt SheetloomDeployRole.Arn
      Region: !Ref AWS::Region
      CallbackUrl: !Ref CallbackUrl

Outputs:
  RoleArn:
    Description: Role Sheetloom assumes to deploy. Already sent to Sheetloom; no action needed.
    Value: !GetAtt SheetloomDeployRole.Arn
