Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
@aws-cdk/aws-cloudfront
Advanced tools
Features | Stability |
---|---|
CFN Resources | |
Higher level constructs for Distribution | |
Higher level constructs for CloudFrontWebDistribution |
CFN Resources: All classes with the
Cfn
prefix in this module (CFN Resources) are always stable and safe to use.
Developer Preview: Higher level constructs in this module that are marked as developer preview have completed their phase of active development and are looking for adoption and feedback. While the same caveats around non-backward compatible as Experimental constructs apply, they will undergo fewer breaking changes. Just as with Experimental constructs, these are not subject to the Semantic Versioning model and breaking changes will be announced in the release notes.
Stable: Higher level constructs in this module that are marked stable will not undergo any breaking changes. They will strictly follow the Semantic Versioning model.
Amazon CloudFront is a web service that speeds up distribution of your static and dynamic web content, such as .html, .css, .js, and image files, to your users. CloudFront delivers your content through a worldwide network of data centers called edge locations. When a user requests content that you're serving with CloudFront, the user is routed to the edge location that provides the lowest latency, so that content is delivered with the best possible performance.
The Distribution
API is currently being built to replace the existing CloudFrontWebDistribution
API. The Distribution
API is optimized for the
most common use cases of CloudFront distributions (e.g., single origin and behavior, few customizations) while still providing the ability for more
advanced use cases. The API focuses on simplicity for the common use cases, and convenience methods for creating the behaviors and origins necessary
for more complex use cases.
CloudFront distributions deliver your content from one or more origins; an origin is the location where you store the original version of your
content. Origins can be created from S3 buckets or a custom origin (HTTP server). Constructs to define origins are in the @aws-cdk/aws-cloudfront-origins
module.
Each distribution has a default behavior which applies to all requests to that distribution, and routes requests to a primary origin. Additional behaviors may be specified for an origin with a given URL path pattern. Behaviors allow routing with multiple origins, controlling which HTTP methods to support, whether to require users to use HTTPS, and what query strings or cookies to forward to your origin, among other settings.
An S3 bucket can be added as an origin. If the bucket is configured as a website endpoint, the distribution can use S3 redirects and S3 custom error documents.
import * as cloudfront from '@aws-cdk/aws-cloudfront';
import * as origins from '@aws-cdk/aws-cloudfront-origins';
// Creates a distribution for a S3 bucket.
const myBucket = new s3.Bucket(this, 'myBucket');
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: { origin: new origins.S3Origin(myBucket) },
});
The above will treat the bucket differently based on if IBucket.isWebsite
is set or not. If the bucket is configured as a website, the bucket is
treated as an HTTP origin, and the built-in S3 redirects and error pages can be used. Otherwise, the bucket is handled as a bucket origin and
CloudFront's redirect and error handling will be used. In the latter case, the Origin wil create an origin access identity and grant it access to the
underlying bucket. This can be used in conjunction with a bucket that is not public to require that your users access your content using CloudFront
URLs and not S3 URLs directly.
An Elastic Load Balancing (ELB) v2 load balancer may be used as an origin. In order for a load balancer to serve as an origin, it must be publicly
accessible (internetFacing
is true). Both Application and Network load balancers are supported.
import * as ec2 from '@aws-cdk/aws-ec2';
import * as elbv2 from '@aws-cdk/aws-elasticloadbalancingv2';
const vpc = new ec2.Vpc(...);
// Create an application load balancer in a VPC. 'internetFacing' must be 'true'
// for CloudFront to access the load balancer and use it as an origin.
const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', {
vpc,
internetFacing: true
});
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: { origin: new origins.LoadBalancerV2Origin(lb) },
});
Origins can also be created from any other HTTP endpoint, given the domain name, and optionally, other origin properties.
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: { origin: new origins.HttpOrigin('www.example.com') },
});
When you create a distribution, CloudFront assigns a domain name for the distribution, for example: d111111abcdef8.cloudfront.net
; this value can
be retrieved from distribution.distributionDomainName
. CloudFront distributions use a default certificate (*.cloudfront.net
) to support HTTPS by
default. If you want to use your own domain name, such as www.example.com
, you must associate a certificate with your distribution that contains
your domain name, and provide one (or more) domain names from the certificate for the distribution.
The certificate must be present in the AWS Certificate Manager (ACM) service in the US East (N. Virginia) region; the certificate may either be created by ACM, or created elsewhere and imported into ACM. When a certificate is used, the distribution will support HTTPS connections from SNI only and a minimum protocol version of TLSv1.2_2019.
const myCertificate = new acm.DnsValidatedCertificate(this, 'mySiteCert', {
domainName: 'www.example.com',
hostedZone,
});
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: { origin: new origins.S3Origin(myBucket) },
domainNames: ['www.example.com'],
certificate: myCertificate,
});
Each distribution has a default behavior which applies to all requests to that distribution; additional behaviors may be specified for a given URL path pattern. Behaviors allow routing with multiple origins, controlling which HTTP methods to support, whether to require users to use HTTPS, and what query strings or cookies to forward to your origin, among others.
The properties of the default behavior can be adjusted as part of the distribution creation. The following example shows configuring the HTTP methods and viewer protocol policy of the cache.
const myWebDistribution = new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: {
origin: new origins.S3Origin(myBucket),
allowedMethods: AllowedMethods.ALLOW_ALL,
viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
}
});
Additional behaviors can be specified at creation, or added after the initial creation. Each additional behavior is associated with an origin,
and enable customization for a specific set of resources based on a URL path pattern. For example, we can add a behavior to myWebDistribution
to
override the default viewer protocol policy for all of the images.
myWebDistribution.addBehavior('/images/*.jpg', new origins.S3Origin(myBucket), {
viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
});
These behaviors can also be specified at distribution creation time.
const bucketOrigin = new origins.S3Origin(myBucket);
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: {
origin: bucketOrigin,
allowedMethods: AllowedMethods.ALLOW_ALL,
viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
},
additionalBehaviors: {
'/images/*.jpg': {
origin: bucketOrigin,
viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
},
},
});
You can use a cache policy to improve your cache hit ratio by controlling the values (URL query strings, HTTP headers, and cookies) that are included in the cache key, and/or adjusting how long items remain in the cache via the time-to-live (TTL) settings. CloudFront provides some predefined cache policies, known as managed policies, for common use cases. You can use these managed policies, or you can create your own cache policy that’s specific to your needs. See https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html for more details.
// Using an existing cache policy
new cloudfront.Distribution(this, 'myDistManagedPolicy', {
defaultBehavior: {
origin: bucketOrigin,
cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED,
},
});
// Creating a custom cache policy -- all parameters optional
const myCachePolicy = new cloudfront.CachePolicy(this, 'myCachePolicy', {
cachePolicyName: 'MyPolicy',
comment: 'A default policy',
defaultTtl: Duration.days(2),
minTtl: Duration.minutes(1),
maxTtl: Duration.days(10),
cookieBehavior: cloudfront.CacheCookieBehavior.all(),
headerBehavior: cloudfront.CacheHeaderBehavior.allowList('X-CustomHeader'),
queryStringBehavior: cloudfront.CacheQueryStringBehavior.denyList('username'),
enableAcceptEncodingGzip: true,
enableAcceptEncodingBrotli: true,
});
new cloudfront.Distribution(this, 'myDistCustomPolicy', {
defaultBehavior: {
origin: bucketOrigin,
cachePolicy: myCachePolicy,
},
});
When CloudFront makes a request to an origin, the URL path, request body (if present), and a few standard headers are included. Other information from the viewer request, such as URL query strings, HTTP headers, and cookies, is not included in the origin request by default. You can use an origin request policy to control the information that’s included in an origin request. CloudFront provides some predefined origin request policies, known as managed policies, for common use cases. You can use these managed policies, or you can create your own origin request policy that’s specific to your needs. See https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html for more details.
// Using an existing origin request policy
new cloudfront.Distribution(this, 'myDistManagedPolicy', {
defaultBehavior: {
origin: bucketOrigin,
originRequestPolicy: cloudfront.OriginRequestPolicy.CORS_S3_ORIGIN,
},
});
// Creating a custom origin request policy -- all parameters optional
const myOriginRequestPolicy = new cloudfront.OriginRequestPolicy(stack, 'OriginRequestPolicy', {
originRequestPolicyName: 'MyPolicy',
comment: 'A default policy',
cookieBehavior: cloudfront.OriginRequestCookieBehavior.none(),
headerBehavior: cloudfront.OriginRequestHeaderBehavior.all('CloudFront-Is-Android-Viewer'),
queryStringBehavior: cloudfront.OriginRequestQueryStringBehavior.allowList('username'),
});
new cloudfront.Distribution(this, 'myDistCustomPolicy', {
defaultBehavior: {
origin: bucketOrigin,
cachePolicy: myCachePolicy,
originRequestPolicy: myOriginRequestPolicy,
},
});
Lambda@Edge is an extension of AWS Lambda, a compute service that lets you execute functions that customize the content that CloudFront delivers. You can author Node.js or Python functions in the US East (N. Virginia) region, and then execute them in AWS locations globally that are closer to the viewer, without provisioning or managing servers. Lambda@Edge functions are associated with a specific behavior and event type. Lambda@Edge can be used rewrite URLs, alter responses based on headers or cookies, or authorize requests based on headers or authorization tokens.
The following shows a Lambda@Edge function added to the default behavior and triggered on every request:
const myFunc = new lambda.Function(...);
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: {
origin: new origins.S3Origin(myBucket),
edgeLambdas: [
{
functionVersion: myFunc.currentVersion,
eventType: cloudfront.LambdaEdgeEventType.VIEWER_REQUEST,
}
],
},
});
Lambda@Edge functions can also be associated with additional behaviors, either at Distribution creation time, or after.
// assigning at Distribution creation
const myOrigin = new origins.S3Origin(myBucket);
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: { origin: myOrigin },
additionalBehaviors: {
'images/*': {
origin: myOrigin,
edgeLambdas: [
{
functionVersion: myFunc.currentVersion,
eventType: cloudfront.LambdaEdgeEventType.ORIGIN_REQUEST,
includeBody: true, // Optional - defaults to false
},
],
},
},
});
// assigning after creation
myDistribution.addBehavior('images/*', myOrigin, {
edgeLambdas: [
{
functionVersion: myFunc.currentVersion,
eventType: cloudfront.LambdaEdgeEventType.VIEWER_RESPONSE,
},
],
});
Adding an existing Lambda@Edge function created in a different stack to a CloudFront distribution.
const functionVersion = lambda.Version.fromVersionArn(this, 'Version', 'arn:aws:lambda:us-east-1:123456789012:function:functionName:1');
new cloudfront.Distribution(this, 'distro', {
defaultBehavior: {
origin: new origins.S3Origin(s3Bucket),
edgeLambdas: [
{
functionVersion,
eventType: cloudfront.LambdaEdgeEventType.VIEWER_REQUEST
},
],
},
});
You can configure CloudFront to create log files that contain detailed information about every user request that CloudFront receives. The logs can go to either an existing bucket, or a bucket will be created for you.
// Simplest form - creates a new bucket and logs to it.
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: { origin: new origins.HttpOrigin('www.example.com') },
enableLogging: true,
});
// You can optionally log to a specific bucket, configure whether cookies are logged, and give the log files a prefix.
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: { origin: new origins.HttpOrigin('www.example.com') },
enableLogging: true, // Optional, this is implied if loggingBucket is specified
loggingBucket: new s3.Bucket(this, 'LoggingBucket'),
loggingFilePrefix: 'distribution-access-logs/',
loggingIncludesCookies: true,
});
Existing distributions can be imported as well; note that like most imported constructs, an imported distribution cannot be modified. However, it can be used as a reference for other higher-level constructs.
const distribution = cloudfront.Distribution.fromDistributionAttributes(scope, 'ImportedDist', {
domainName: 'd111111abcdef8.cloudfront.net',
distributionId: '012345ABCDEF',
});
A CloudFront construct - for setting up the AWS CDN with ease!
Example usage:
const sourceBucket = new Bucket(this, 'Bucket');
const distribution = new CloudFrontWebDistribution(this, 'MyDistribution', {
originConfigs: [
{
s3OriginSource: {
s3BucketSource: sourceBucket
},
behaviors : [ {isDefaultBehavior: true}]
}
]
});
By default, CloudFront Web Distributions will answer HTTPS requests with CloudFront's default certificate, only containing the distribution domainName
(e.g. d111111abcdef8.cloudfront.net).
You can customize the viewer certificate property to provide a custom certificate and/or list of domain name aliases to fit your needs.
See Using Alternate Domain Names and HTTPS in the CloudFront User Guide.
You can customize the default certificate aliases. This is intended to be used in combination with CNAME records in your DNS zone.
Example:
create a distrubution with an default certificiate example
You can change the default certificate by one stored AWS Certificate Manager, or ACM. Those certificate can either be generated by AWS, or purchased by another CA imported into ACM.
For more information, see the aws-certificatemanager module documentation or Importing Certificates into AWS Certificate Manager in the AWS Certificate Manager User Guide.
Example:
create a distrubution with an acm certificate example
You can also import a certificate into the IAM certificate store.
See Importing an SSL/TLS Certificate in the CloudFront User Guide.
Example:
create a distrubution with an iam certificate example
CloudFront supports adding restrictions to your distribution.
See Restricting the Geographic Distribution of Your Content in the CloudFront User Guide.
Example:
new cloudfront.CloudFrontWebDistribution(stack, 'MyDistribution', {
//...
geoRestriction: GeoRestriction.whitelist('US', 'UK')
});
CloudFront provides you even more control over the connection behaviors between CloudFront and your origin. You can now configure the number of connection attempts CloudFront will make to your origin and the origin connection timeout for each attempt.
See Origin Connection Attempts
Example usage:
const distribution = new CloudFrontWebDistribution(this, 'MyDistribution', {
originConfigs: [
{
...,
connectionAttempts: 3,
connectionTimeout: cdk.Duration.seconds(10),
}
]
});
In case the origin source is not available and answers with one of the specified status code the failover origin source will be used.
new CloudFrontWebDistribution(stack, 'ADistribution', {
originConfigs: [
{
s3OriginSource: {
s3BucketSource: s3.Bucket.fromBucketName(stack, 'aBucket', 'myoriginbucket'),
originPath: '/',
originHeaders: {
'myHeader': '42',
},
},
failoverS3OriginSource: {
s3BucketSource: s3.Bucket.fromBucketName(stack, 'aBucketFallback', 'myoriginbucketfallback'),
originPath: '/somwhere',
originHeaders: {
'myHeader2': '21',
},
},
failoverCriteriaStatusCodes: [FailoverStatusCode.INTERNAL_SERVER_ERROR],
behaviors: [
{
isDefaultBehavior: true,
},
],
},
],
});
1.75.0 (2020-11-24)
keyId
property uses the ARN instead of the keyId
to support cross-account encryption key usage. The filesystem will be replaced.esbuild
to be installed.projectRoot
has been replaced by depsLockFilePath
. It should point to your dependency lock file (package-lock.json
or yarn.lock
)parcelEnvironment
has been renamed to bundlingEnvironment
sourceMaps
has been renamed to sourceMap
IVirtualNode
no longer has the addBackends()
method. A backend can be added to VirtualNode
using the addBackend()
method which accepts a single IVirtualService
IVirtualNode
no longer has the addListeners()
method. A listener can be added to VirtualNode
using the addListener()
method which accepts a single VirtualNodeListener
VirtualNode
no longer has a default listener. It is valid to have a VirtualNode
without any listenerslistener
of VirtualNode
has been renamed to listeners
, and its type changed to an array of listenersVirtualNodeListener
has been removed. To create Virtual Node listeners, use the static factory methods of the VirtualNodeListener
class--no-lookups
flag to disable context lookups (#11489) (0445a6e), closes #11461fromAccessPointAttributes()
(#10712) (ec72c85)targetRequestsPerSecond
is actually requests per minute (#11457) (39e277f), closes #11446extraRunOrderSpace
(#11511) (9b72fc8)FAQs
The CDK Construct Library for AWS::CloudFront
The npm package @aws-cdk/aws-cloudfront receives a total of 50,338 weekly downloads. As such, @aws-cdk/aws-cloudfront popularity was classified as popular.
We found that @aws-cdk/aws-cloudfront demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.