Example #1
0
    def __init__(self, title, index, **kwargs):
        super().__init__(title, **kwargs)

        name = self.title
        key = cfg.CloudFrontOrigins[index]

        CustomHeaders = []
        if 'Headers' in key:
            for n in key['Headers']:
                headername = f'{name}Headers{n}'
                CustomHeader = CFOriginCustomHeader(headername)

                CustomHeaders.append(CustomHeader)

        if key['Type'] == 'custom':
            CustomOrigin = CFCustomOrigin(name, key=key)
            self.CustomOriginConfig = CustomOrigin
        else:
            self.S3OriginConfig = clf.S3OriginConfig()
            if 'OriginAccessIdentity' in key:
                self.S3OriginConfig.OriginAccessIdentity = get_subvalue(
                    'origin-access-identity/cloudfront/${1M}',
                    f'{name}OriginAccessIdentity')

        self.DomainName = get_endvalue(f'{name}DomainName')
        self.OriginPath = get_endvalue(f'{name}Path')
        self.Id = get_endvalue(f'{name}Id')
        self.OriginCustomHeaders = CustomHeaders
Example #2
0
    def distribution(self) -> cloudfront.Distribution:
        """Return cloudfront distribution with bucket as origin."""
        origin = cloudfront.Origin(
            S3OriginConfig=cloudfront.S3OriginConfig(OriginAccessIdentity=Join(
                "",
                [
                    "origin-access-identity/cloudfront/",
                    Ref(self.origin_access_identity),
                ],
            )),
            DomainName=f"{self.bucket.name}.s3.amazonaws.com",
            Id="S3Origin",
        )
        cache_params = {
            "AllowedMethods": ["GET", "HEAD", "OPTIONS"],
            "CachePolicyId": Ref(self.cache_policy),
            "TargetOriginId": "S3Origin",
            "ViewerProtocolPolicy": "redirect-to-https",
        }
        if self.lambda_edge_function_arns:
            cache_params["LambdaFunctionAssociations"] = [
                cloudfront.LambdaFunctionAssociation(
                    EventType="viewer-request", LambdaFunctionARN=lambda_arn)
                for lambda_arn in self.lambda_edge_function_arns
            ]

        default_cache_behavior = cloudfront.DefaultCacheBehavior(
            **cache_params)
        return cloudfront.Distribution(
            name_to_id(self.name),
            DistributionConfig=cloudfront.DistributionConfig(
                Aliases=self.aliases,
                DefaultRootObject=self.root_object,
                DefaultCacheBehavior=default_cache_behavior,
                Enabled="True",
                HttpVersion="http2",
                Origins=[origin],
                ViewerCertificate=cloudfront.ViewerCertificate(
                    AcmCertificateArn=self.certificate_arn,
                    SslSupportMethod="sni-only",
                    MinimumProtocolVersion="TLSv1.2_2021",
                ),
            ),
        )
Example #3
0
    def get_distribution_options(self,
                                 bucket,  # type: s3.Bucket
                                 oai,  # type: cloudfront.CloudFrontOriginAccessIdentity
                                 lambda_funcs,  # type: List[cloudfront.LambdaFunctionAssociation]
                                 check_auth_lambda_version,  # type: awslambda.Version
                                 http_headers_lambda_version,  # type: awslambda.Version
                                 parse_auth_lambda_version,  # type: awslambda.Version
                                 refresh_auth_lambda_version,  # type: awslambda.Version
                                 sign_out_lambda_version  # type: awslambda.Version
                                ):  # noqa: E124
        # type: (...) -> Dict[str, Any]
        """Retrieve the options for our CloudFront distribution.

        Keyword Args:
            bucket (dict): The bucket resource
            oai (dict): The origin access identity resource

        Return:
            dict: The CloudFront Distribution Options

        """
        variables = self.get_variables()

        default_cache_behavior_lambdas = lambda_funcs
        default_cache_behavior_lambdas.append(
            cloudfront.LambdaFunctionAssociation(
                EventType='viewer-request',
                LambdaFunctionARN=check_auth_lambda_version.ref()
            )
        )
        default_cache_behavior_lambdas.append(
            cloudfront.LambdaFunctionAssociation(
                EventType='origin-response',
                LambdaFunctionARN=http_headers_lambda_version.ref()
            )
        )

        return {
            'Aliases': self.add_aliases(),
            'Origins': [
                cloudfront.Origin(
                    DomainName=Join(
                        '.',
                        [bucket.ref(),
                         's3.amazonaws.com']),
                    S3OriginConfig=cloudfront.S3OriginConfig(
                        OriginAccessIdentity=Join(
                            '',
                            ['origin-access-identity/cloudfront/',
                             oai.ref()])
                    ),
                    Id='protected-bucket'
                )
            ],
            'CacheBehaviors': [
                cloudfront.CacheBehavior(
                    PathPattern=variables['RedirectPathSignIn'],
                    Compress=True,
                    ForwardedValues=cloudfront.ForwardedValues(
                        QueryString=True
                    ),
                    LambdaFunctionAssociations=[
                        cloudfront.LambdaFunctionAssociation(
                            EventType='viewer-request',
                            LambdaFunctionARN=parse_auth_lambda_version.ref()
                        )
                    ],
                    TargetOriginId='protected-bucket',
                    ViewerProtocolPolicy="redirect-to-https"
                ),
                cloudfront.CacheBehavior(
                    PathPattern=variables['RedirectPathAuthRefresh'],
                    Compress=True,
                    ForwardedValues=cloudfront.ForwardedValues(
                        QueryString=True
                    ),
                    LambdaFunctionAssociations=[
                        cloudfront.LambdaFunctionAssociation(
                            EventType='viewer-request',
                            LambdaFunctionARN=refresh_auth_lambda_version.ref()
                        )
                    ],
                    TargetOriginId='protected-bucket',
                    ViewerProtocolPolicy="redirect-to-https"
                ),
                cloudfront.CacheBehavior(
                    PathPattern=variables['SignOutUrl'],
                    Compress=True,
                    ForwardedValues=cloudfront.ForwardedValues(
                        QueryString=True
                    ),
                    LambdaFunctionAssociations=[
                        cloudfront.LambdaFunctionAssociation(
                            EventType='viewer-request',
                            LambdaFunctionARN=sign_out_lambda_version.ref()
                        )
                    ],
                    TargetOriginId='protected-bucket',
                    ViewerProtocolPolicy="redirect-to-https"
                ),
            ],
            'DefaultCacheBehavior': cloudfront.DefaultCacheBehavior(
                AllowedMethods=['GET', 'HEAD'],
                Compress=True,
                DefaultTTL='86400',
                ForwardedValues=cloudfront.ForwardedValues(
                    QueryString=True,
                ),
                LambdaFunctionAssociations=default_cache_behavior_lambdas,
                TargetOriginId='protected-bucket',
                ViewerProtocolPolicy='redirect-to-https'
            ),
            'DefaultRootObject': 'index.html',
            'Logging': self.add_logging_bucket(),
            'PriceClass': variables['PriceClass'],
            'Enabled': True,
            'WebACLId': self.add_web_acl(),
            'CustomErrorResponses': self._get_error_responses(),
            'ViewerCertificate': self.add_acm_cert()
        }
Example #4
0
 DistributionConfig=cloudfront.DistributionConfig(
     Comment="Example distribution for restricted access",
     Aliases=[domain_name],
     Enabled=True,
     IPV6Enabled=True,
     HttpVersion='http2',
     PriceClass='PriceClass_100',
     Origins=[
         # Your usual config goes here, example:
         cloudfront.Origin(
             Id="ExampleS3",
             DomainName=Join(
                 '', [Ref(example_bucket), '.s3.amazonaws.com']),
             S3OriginConfig=cloudfront.S3OriginConfig(
                 OriginAccessIdentity=Join('', [
                     'origin-access-identity/cloudfront/',
                     Ref(example_bucket_oai),
                 ])),
         ),
     ],
     DefaultRootObject=
     "index.html",  # Needed for this example only, adapt to your requirements
     CacheBehaviors=[
         # If you have additional cache behaviours,
         # make sure that (at least) the behaviour matching
         # /auth-89CE3FEF-FCF6-43B3-9DBA-7C410CAAE220/set-cookie
         # has the Lambda-function associated.
     ],
     DefaultCacheBehavior=cloudfront.DefaultCacheBehavior(
         ViewerProtocolPolicy=
         'redirect-to-https',  # HTTPS required. Cookies need to be sent securely
Example #5
0
                Tags=Tags(Name=f"{bucket}-{randomPrefix}"),
            )
        )

        if "cloudfront" in bucket:
            cloudfrontBucket = f"{bucket.lower()}-{randomPrefix}"

    cloudfront = t.add_resource(
        cloudfront.Distribution(
            "Cloudfront",
            DistributionConfig=cloudfront.DistributionConfig(
                Origins=[
                    cloudfront.Origin(
                        Id="1",
                        DomainName=f"{cloudfrontBucket}.s3-ap-southeast-2.amazonaws.com",
                        S3OriginConfig=cloudfront.S3OriginConfig(),
                    )
                ],
                DefaultCacheBehavior=cloudfront.DefaultCacheBehavior(
                    TargetOriginId="1",
                    ForwardedValues=cloudfront.ForwardedValues(QueryString=False),
                    ViewerProtocolPolicy="allow-all",
                ),
                Enabled=True,
                HttpVersion="http2",
            ),
        )
    )

    with open("template.yml", "w") as file:
        file.write(t.to_yaml())
Example #6
0
    def get_cloudfront_distribution_options(
        self,
        bucket,  # type: s3.Bucket
        oai,  # type: cloudfront.CloudFrontOriginAccessIdentity
        lambda_function_associations,  # type: List[cloudfront.LambdaFunctionAssociation]
    ):
        # type: (...) -> Dict[str, Any]
        """Retrieve the options for our CloudFront distribution.

        Args:
            bucket: The bucket resource
            oai: The origin access identity resource.
            lambda_function_associations: List of Lambda Function associations.

        Return:
            The CloudFront Distribution Options.

        """
        variables = self.get_variables()

        if os.getenv("AWS_REGION") == "us-east-1":
            # use global endpoint for us-east-1
            origin = Join(".", [bucket.ref(), "s3.amazonaws.com"])
        else:
            # use reginal endpoint to avoid "temporary" redirect that can last over an hour
            # https://forums.aws.amazon.com/message.jspa?messageID=677452
            origin = Join(".", [bucket.ref(), "s3", Region, "amazonaws.com"])

        return {
            "Aliases": self.add_aliases(),
            "Origins": [
                cloudfront.Origin(
                    DomainName=origin,
                    S3OriginConfig=cloudfront.S3OriginConfig(
                        OriginAccessIdentity=Join(
                            "", ["origin-access-identity/cloudfront/", oai.ref()]
                        )
                    ),
                    Id="S3Origin",
                )
            ],
            "DefaultCacheBehavior": cloudfront.DefaultCacheBehavior(
                AllowedMethods=["GET", "HEAD"],
                Compress=False,
                DefaultTTL="86400",
                ForwardedValues=cloudfront.ForwardedValues(
                    Cookies=cloudfront.Cookies(Forward="none"), QueryString=False,
                ),
                LambdaFunctionAssociations=lambda_function_associations,
                TargetOriginId="S3Origin",
                ViewerProtocolPolicy="redirect-to-https",
            ),
            "DefaultRootObject": "index.html",
            "Logging": self.add_logging_bucket(),
            "PriceClass": variables["PriceClass"],
            "CustomErrorResponses": [
                cloudfront.CustomErrorResponse(
                    ErrorCode=response["ErrorCode"],
                    ResponseCode=response["ResponseCode"],
                    ResponsePagePath=response["ResponsePagePath"],
                )
                for response in variables["custom_error_responses"]
            ],
            "Enabled": True,
            "WebACLId": self.add_web_acl(),
            "ViewerCertificate": self.add_acm_cert(),
        }