AWSTemplateFormatVersion: '2010-09-09'
Description: >-
  SaaSLayer per-region foundation stack: region-bound resources for a SaaSLayer host account, starting
  with the shared deployment-artifact bucket every SaaSLayer service deploys into. Installed once per
  account+region, after the account-global saaslayer-foundation (IAM) stack.

Parameters:
  ArtifactsBucketName:
    Type: String
    AllowedPattern: '^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$'
    Description: >-
      Name of the shared deployment-artifact bucket. Passed in (not derived here) because the name is
      sl-artifacts-<opaqueAccountToken>-<regionCode> where opaqueAccountToken = sha256(accountId|'artifacts')
      — CloudFormation cannot hash, so the deployer derives it (artifactsBucketName in @saaslayer/config /
      deployer refs.ts) and passes it, guaranteeing the bucket and the injected SERVERLESS_DEPLOYMENT_BUCKET
      agree byte-for-byte. Opaque (no raw account id) so a globally-probeable S3 name never confirms the
      account is SaaSLayer-managed.
  EmailSenderDomain:
    Type: String
    Default: ''
    AllowedPattern: '^(([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63})?$'
    Description: >-
      Optional domain this account sends email from (e.g. acme.com). When set, an SES identity with Easy DKIM is
      created and its three DKIM CNAME records are output for the domain's DNS. Empty = no sender domain.
  SmsOriginationNumberType:
    Type: String
    AllowedValues: [none, toll-free, simulator]
    Default: none
    Description: >-
      The account's SMS sending number in this region: none, a toll-free number (sends once its registration is
      approved), or a simulator number (dev only; delivers to AWS simulator destinations). Set by saaslayer sms setup and
      moved back to none only by saaslayer sms release.
  SmsHelpMessage:
    Type: String
    MinLength: 1
    MaxLength: 160
    Default: 'Account verification and sign-in codes. Msg and data rates may apply. Reply STOP to opt out.'
    Description: >-
      The number's automatic reply when someone texts HELP (carriers expect the sender's name, a contact and how to opt
      out, in one SMS). Set by saaslayer sms setup --help-message; the default is the generic reply.

  TemplateGuard:
    Type: String
    AllowedValues: ['off', warn]
    Default: 'off'
    Description: >-
      The template guard on SaaSLayer module stacks in this region: off, or warn (rule failures are reported as stack events
      and the deploy continues). Set by saaslayer foundation upgrade --template-guard.

Conditions:
  HasTemplateGuard: !Equals [!Ref TemplateGuard, warn]
  HasEmailSenderDomain: !Not [!Equals [!Ref EmailSenderDomain, '']]
  HasSmsOriginationNumber: !Not [!Equals [!Ref SmsOriginationNumberType, none]]
  IsSmsSimulator: !Equals [!Ref SmsOriginationNumberType, simulator]

Mappings:
  Meta:
    FoundationRegion:
      Version: '1.5.0'

Resources:
  DeploymentArtifactBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Ref ArtifactsBucketName
      OwnershipControls:
        Rules:
          - ObjectOwnership: BucketOwnerEnforced
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256
      VersioningConfiguration:
        Status: Enabled
      LifecycleConfiguration:
        Rules:
          - Id: expire-old-artifacts
            Status: Enabled
            ExpirationInDays: 90
            NoncurrentVersionExpiration:
              NoncurrentDays: 30
            AbortIncompleteMultipartUpload:
              DaysAfterInitiation: 7

  DeploymentArtifactBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref DeploymentArtifactBucket
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Sid: DenyInsecureTransport
            Effect: Deny
            Principal: '*'
            Action: 's3:*'
            Resource:
              - !GetAtt DeploymentArtifactBucket.Arn
              - !Sub '${DeploymentArtifactBucket.Arn}/*'
            Condition:
              Bool:
                aws:SecureTransport: 'false'
          - Sid: DenyArtifactWritesBySaaSLayerRolesButDeploy
            Effect: Deny
            Principal: '*'
            Action:
              - 's3:PutObject'
              - 's3:DeleteObject*'
              - 's3:PutBucket*'
              - 's3:DeleteBucket*'
            Resource:
              - !GetAtt DeploymentArtifactBucket.Arn
              - !Sub '${DeploymentArtifactBucket.Arn}/*'
            Condition:
              ArnLike:
                aws:PrincipalArn: !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/sl-*'
              ArnNotLike:
                aws:PrincipalArn: !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/sl-foundation-deploy-role'

  EmailSenderIdentity:
    Type: AWS::SES::EmailIdentity
    Condition: HasEmailSenderDomain
    Properties:
      EmailIdentity: !Ref EmailSenderDomain

  SmsOriginationNumber:
    Type: AWS::SMSVOICE::PhoneNumber
    Condition: HasSmsOriginationNumber
    DeletionPolicy: Delete
    UpdateReplacePolicy: Delete
    Properties:
      IsoCountryCode: US
      NumberType: !If [IsSmsSimulator, SIMULATOR, TOLL_FREE]
      NumberCapabilities: [SMS]
      MandatoryKeywords:
        HELP:
          Message: !Ref SmsHelpMessage
        STOP:
          Message: 'You are unsubscribed and will receive no further messages from this number.'
      Tags:
        - Key: saaslayer:sender
          Value: default

  TemplateGuardRole:
    Type: AWS::IAM::Role
    Condition: HasTemplateGuard
    Properties:
      RoleName: !Sub sl-foundation-template-guard-${AWS::Region}
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: hooks.cloudformation.amazonaws.com
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                aws:SourceAccount: !Ref AWS::AccountId
      Policies:
        - PolicyName: read-guard-rules
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action: s3:GetObject
                Resource: arn:aws:s3:::saaslayer-templates/foundation-region/*/saaslayer-template-guard.guard

  TemplateGuardHook:
    Type: AWS::CloudFormation::GuardHook
    Condition: HasTemplateGuard
    Properties:
      Alias: SaaSLayer::Foundation::TemplateGuard
      ExecutionRole: !GetAtt TemplateGuardRole.Arn
      FailureMode: WARN
      HookStatus: ENABLED
      RuleLocation:
        Uri: !Sub
          - s3://saaslayer-templates/foundation-region/${Version}/saaslayer-template-guard.guard
          - Version: !FindInMap [Meta, FoundationRegion, Version]
      TargetOperations: [RESOURCE]
      TargetFilters:
        Actions: [CREATE, UPDATE]
      StackFilters:
        FilteringCriteria: ANY
        StackNames:
          Include: ['sl-*']
        StackRoles:
          Include:
            - !Sub arn:${AWS::Partition}:iam::${AWS::AccountId}:role/sl-foundation-cfn-exec-role

Outputs:
  SmsOriginationIdentityArn:
    Condition: HasSmsOriginationNumber
    Description: ARN of the account's SMS sending number (the user-service PhoneSmsOriginationIdentity setting).
    Value: !GetAtt SmsOriginationNumber.Arn
  EmailSenderIdentityArn:
    Condition: HasEmailSenderDomain
    Description: SES identity ARN of the account's email sender domain (the user-service CognitoEmailSenderArn setting).
    Value: !Sub arn:${AWS::Partition}:ses:${AWS::Region}:${AWS::AccountId}:identity/${EmailSenderDomain}
  EmailSenderDkimRecords:
    Condition: HasEmailSenderDomain
    Description: The three DKIM CNAME records ('name CNAME value', one per line) to add to the sender domain's DNS.
    Value: !Join
      - "\n"
      - - !Join [' ', [!GetAtt EmailSenderIdentity.DkimDNSTokenName1, CNAME, !GetAtt EmailSenderIdentity.DkimDNSTokenValue1]]
        - !Join [' ', [!GetAtt EmailSenderIdentity.DkimDNSTokenName2, CNAME, !GetAtt EmailSenderIdentity.DkimDNSTokenValue2]]
        - !Join [' ', [!GetAtt EmailSenderIdentity.DkimDNSTokenName3, CNAME, !GetAtt EmailSenderIdentity.DkimDNSTokenValue3]]
  ArtifactsBucketName:
    Description: Shared deployment-artifact bucket every SaaSLayer service in this account+region deploys into.
    Value: !Ref DeploymentArtifactBucket
  FoundationRegionVersion:
    Description: Version of this per-region foundation template installed in the account+region.
    Value: !FindInMap [Meta, FoundationRegion, Version]
