Exemple #1
0
 def _cache_behavior(origin_id, pattern):
     return cloudfront.CacheBehavior(
         TargetOriginId=origin_id,
         DefaultTTL=context['cloudfront']['default-ttl'],
         ForwardedValues=cloudfront.ForwardedValues(QueryString=False),
         PathPattern=pattern,
         ViewerProtocolPolicy='allow-all',
     )
    def add_cache_behaviors(self, title, cf_cache_behavior_config):
        """
        Create Cloudfront CacheBehavior objects and append to list of cache_behaviors
        :param title: Title of this Cloudfront Distribution
        :param cf_cache_behavior_config: list of CFCacheBehavior
        """

        default_cache_behavior_count = 0
        cache_behavior_count = 0

        for number, cache_behavior in enumerate(cf_cache_behavior_config):

            forwarded_values = cloudfront.ForwardedValues(
                Cookies=cloudfront.Cookies(
                    Forward=cache_behavior.forward_cookies),
                QueryString=cache_behavior.query_string)
            if cache_behavior.forwarded_headers is not None:
                forwarded_values.Headers = cache_behavior.forwarded_headers

            cf_cache_behavior_params = {
                'AllowedMethods': cache_behavior.allowed_methods,
                'CachedMethods': cache_behavior.cached_methods,
                'Compress': False,
                'TargetOriginId': cache_behavior.target_origin_id,
                'ForwardedValues': forwarded_values,
                'TrustedSigners': cache_behavior.trusted_signers,
                'ViewerProtocolPolicy': cache_behavior.viewer_protocol_policy,
                'MinTTL': cache_behavior.min_ttl,
                'DefaultTTL': cache_behavior.default_ttl,
                'MaxTTL': cache_behavior.max_ttl,
                'SmoothStreaming': False
            }

            if cache_behavior.is_default:
                # Add default cache behavior
                self.default_cache_behavior = cloudfront.DefaultCacheBehavior(
                    '{0}DefaultCacheBehavior'.format(title),
                    **cf_cache_behavior_params)

                default_cache_behavior_count += 1
            else:
                # Append additional cache behaviors to list
                cf_cache_behavior_params[
                    'PathPattern'] = cache_behavior.path_pattern

                created_cache_behavior = cloudfront.CacheBehavior(
                    '{0}CacheBehavior{1}'.format(title, number),
                    **cf_cache_behavior_params)

                self.cache_behaviors.append(created_cache_behavior)
                cache_behavior_count += 1

            # if there is at least one cache behavior, there must be exactly one default cache behavior
            if cache_behavior_count > 0 and default_cache_behavior_count != 1:
                raise CloudfrontConfigError(
                    'Error: cf_distribution_unit {0} must have exactly one default cache behavior.'
                    .format(title))
Exemple #3
0
 def _cache_behavior(origin_id, pattern, headers=None, cookies=None):
     return cloudfront.CacheBehavior(
         TargetOriginId=origin_id,
         DefaultTTL=context['cloudfront']['default-ttl'],
         ForwardedValues=cloudfront.ForwardedValues(
             Cookies=_cookies(cookies),
             QueryString=False,
             Headers=headers if headers else []),
         PathPattern=pattern,
         ViewerProtocolPolicy='allow-all',
     )
Exemple #4
0
    def build(self):

        fw = ForwardedValues(QueryString=self.forward_querystring)

        if self.forward_cookies == 'none':
            fw.Cookies = Cookies(Forward='none')
        elif self.forward_cookies == 'all':
            fw.Cookies = Cookies(Forward='all')
        else:
            fw.Cookies = Cookies(Forward='whitelist',
                                 WhitelistNames=self.cookie_list)

        if len(self.querystring_list) > 0:
            fw.QueryStringCacheKeys = self.querystring_list

        if self.headers:
            fw.Headers = self.headers

        kw = {
            'AllowedMethods': self.allowed_methods,
            'CachedMethods': self.cache_methods,
            'Compress': self.compress,
            'ForwardedValues': fw,
            'SmoothStreaming': self.streaming,
            'TargetOriginId': self.origin_id,
        }

        if self.default_ttl is not None:
            kw['DefaultTTL'] = self.default_ttl
        if self.max_ttl is not None:
            kw['MaxTTL'] = self.max_ttl
        if self.min_ttl is not None:
            kw['MinTTL'] = self.min_ttl

        if self.force_https:
            kw['ViewerProtocolPolicy'] = 'redirect-to-https'
        elif self.https:
            kw['ViewerProtocolPolicy'] = 'https-only'
        else:
            kw['ViewerProtocolPolicy'] = 'allow-all'

        if self.default:
            b = cloudfront.DefaultCacheBehavior(**kw)
        else:
            kw['PathPattern'] = self.pattern
            b = cloudfront.CacheBehavior(**kw)
        return b
Exemple #5
0
        ],
        DefaultCacheBehavior=cloudfront.DefaultCacheBehavior(
            TargetOriginId="staticv1",
            ForwardedValues=cloudfront.ForwardedValues(
                QueryString=False,
            ),
            ViewerProtocolPolicy="allow-all",
            MinTTL=1,
            MaxTTL=60,
        ),
        CacheBehaviors=[
            cloudfront.CacheBehavior(
                TargetOriginId='apiv1',
                ForwardedValues=cloudfront.ForwardedValues(
                    QueryString=True,
                ),
                ViewerProtocolPolicy="allow-all",
                MinTTL=1,
                MaxTTL=60,
                PathPattern='/api/v1/*',
            ),
        ],
        Enabled=True,
        HttpVersion='http1.1',
    ),
))
stack.add_output([
    Output(
        "VisibilityUrl",
        Value=Join("", ["http://", GetAtt(cloudfront_distribution, "DomainName")])
    )
])
Exemple #6
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()
        }
Exemple #7
0
)

# Create the CloudFront distirbutions.
frontend_distribution = template.add_resource(
    cloudfront.Distribution(
        'FrontendDistribution',
        DistributionConfig=cloudfront.DistributionConfig(
            Aliases=[
                Ref(frontend_cname)
            ],
            CacheBehaviors=[
                cloudfront.CacheBehavior(
                    AllowedMethods=['HEAD', 'GET'],
                    CachedMethods=['HEAD', 'GET'],
                    ForwardedValues=cloudfront.ForwardedValues(
                        QueryString=False
                    ),
                    PathPattern='*',
                    TargetOriginId=Join('-', ['S3', Ref(frontend_bucket)]),
                    ViewerProtocolPolicy='redirect-to-https'
                )
            ],
            CustomErrorResponses=[
                cloudfront.CustomErrorResponse(
                    ErrorCode=404,
                    ResponseCode=200,
                    ResponsePagePath='/index.html'
                )
            ],
            DefaultCacheBehavior=cloudfront.DefaultCacheBehavior(
                ForwardedValues=cloudfront.ForwardedValues(
                    QueryString=False
Exemple #8
0
# endregion

# region Resources
distribution = template.add_resource(
    cloudfront.Distribution(
        'Distribution',
        DistributionConfig=cloudfront.DistributionConfig(
            Aliases=[Ref(domain)],
            CacheBehaviors=[
                cloudfront.CacheBehavior(
                    Compress=True,
                    ForwardedValues=cloudfront.ForwardedValues(
                        Cookies=cloudfront.Cookies(Forward='none'),
                        QueryString=False,
                    ),
                    PathPattern=Ref(media_pattern),
                    TargetOriginId=Sub(
                        '${domain}${path}', **{
                            'domain': Ref(media_domain),
                            'path': Ref(media_path)
                        }),
                    ViewerProtocolPolicy='redirect-to-https',
                )
            ],
            Comment=Sub('${AWS::StackName}'),
            DefaultCacheBehavior=cloudfront.DefaultCacheBehavior(
                Compress=True,
                ForwardedValues=cloudfront.ForwardedValues(
                    Cookies=cloudfront.Cookies(Forward='none'),
                    QueryString=False,
                ),
                TargetOriginId=Sub(
Exemple #9
0
    def get_distribution_options(
        self,
        bucket: s3.Bucket,
        oai: cloudfront.CloudFrontOriginAccessIdentity,
        lambda_funcs: List[cloudfront.LambdaFunctionAssociation],
        check_auth_lambda_version: awslambda.Version,
        http_headers_lambda_version: awslambda.Version,
        parse_auth_lambda_version: awslambda.Version,
        refresh_auth_lambda_version: awslambda.Version,
        sign_out_lambda_version: awslambda.Version,
    ) -> Dict[str, Any]:
        """Retrieve the options for our CloudFront distribution.

        Keyword Args:
            bucket: The bucket resource.
            oai: The origin access identity resource.
            lambda_funcs: List of Lambda Function associations.
            check_auth_lambda_version: Lambda Function Version to use.
            http_headers_lambda_version: Lambda Function Version to use.
            parse_auth_lambda_version: Lambda Function Version to use.
            refresh_auth_lambda_version: Lambda Function Version to use.
            sign_out_lambda_version: Lambda Function Version to use.

        Return:
            The CloudFront Distribution Options.

        """
        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=self.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=self.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=self.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":
            self.variables["PriceClass"],
            "Enabled":
            True,
            "WebACLId":
            self.add_web_acl(),
            "CustomErrorResponses":
            self._get_error_responses(),
            "ViewerCertificate":
            self.add_acm_cert(),
        }
Exemple #10
0
             OriginProtocolPolicy='https-only',
             OriginSSLProtocols=['TLSv1.2', 'TLSv1.1', 'TLSv1']),
     ),
 ],
 CacheBehaviors=[
     cloudfront.CacheBehavior(
         # The authorizer hijacks a set of URL-paths from your website. All paths are prefixed
         # with `/auth-<UUID>/`, so they are very unlikely to collide with your content.
         # Insert this as the first Behaviour.
         PathPattern=Join('', [
             ImportValue(
                 Sub('${' + authorizer_stack.title +
                     '}-magic-path')),
             '/*',
         ]),
         ViewerProtocolPolicy='https-only',
         TargetOriginId='Authorizer',
         ForwardedValues=cloudfront.ForwardedValues(
             QueryString=True,
             Cookies=cloudfront.Cookies(
                 Forward='all',  # Needed to allow Set-Cookie:-headers
             ),
         ),
         MinTTL=0,
         DefaultTTL=0,
         MaxTTL=0,
     )
 ],
 DefaultCacheBehavior=cloudfront.DefaultCacheBehavior(
     ViewerProtocolPolicy=
     'redirect-to-https',  # HTTPS required. Cookies need to be sent securely
     LambdaFunctionAssociations=[