AWSTemplateFormatVersion: '2010-09-09'
Description: Deploy a CloudFront Distribution with Custom Domain Name and Transfer web app configured as origin.

Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Parameters:
          - WebAppEndpoint
          - AccessEndpoint
          - AcmCertificateArn

Parameters:
  WebAppEndpoint:
    Type: String
    AllowedPattern: https://[a-z0-9.-]+
    Description: The WebAppEndpoint for your web app. Include https://. Do not include a trailing slash.
  AccessEndpoint:
    Type: String
    AllowedPattern: https://[a-z0-9.-]+
    Description: The custom AccessEndpoint for your web app. Include https://. Do not include a trailing slash.
  AcmCertificateArn:
    Type: String
    AllowedPattern: "arn:aws:acm:us-east-1:[0-9]{12}:certificate/.*"
    Description: An ACM Certificate for the custom domain name used by the AccessEndpoint. Certificate must be in us-east-1.

Resources:
  CloudFrontDistribution:
    Type: AWS::CloudFront::Distribution
    Properties:
      DistributionConfig:
        Enabled: true
        HttpVersion: http2
        IPV6Enabled: true
        DefaultCacheBehavior:
          TargetOriginId: WebAppOrigin
          ViewerProtocolPolicy: https-only
          AllowedMethods:
            - GET
            - HEAD
            - OPTIONS
            - PUT
            - POST
            - PATCH
            - DELETE
          CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad # Cache Policy: Caching Disabled
          OriginRequestPolicyId: b689b0a8-53d0-40ab-baf2-68738e2966ac # Origin Request Policy: AllViewerExceptHostHeader
          # Documentation link: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html
        PriceClass: PriceClass_100
        ViewerCertificate:
          AcmCertificateArn: !Ref AcmCertificateArn
          MinimumProtocolVersion: "TLSv1.2_2021"
          SslSupportMethod: "sni-only"
        Aliases:
          - Fn::Select:
              - 1
              - Fn::Split:
                - https://
                - !Ref AccessEndpoint
        Origins:
          - Id: WebAppOrigin
            DomainName:
              Fn::Select:
                - 1
                - Fn::Split:
                  - https://
                  - !Ref WebAppEndpoint
            OriginPath: ""
            OriginCustomHeaders:
              - HeaderName: X-Transfer-WebApp-Custom-Domain-Template-Version
                HeaderValue: 2024-12-01
            CustomOriginConfig:
              HTTPSPort: 443
              OriginProtocolPolicy: https-only
              OriginSSLProtocols:
                - TLSv1.2

Outputs:
  CloudFrontDistributionId:
    Value: !Ref CloudFrontDistribution
  CloudFrontDistributionDomainName:
    Value: !GetAtt CloudFrontDistribution.DomainName
  WebAppEndpoint:
    Value: !Ref WebAppEndpoint
  AccessEndpoint:
    Value: !Ref AccessEndpoint
