Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support cloudfront for gateway and static unit #27

Merged
merged 3 commits into from
Jan 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@ type (
PubSub map[string]*PubSub `json:"pubsub,omitempty" yaml:"pubsub,omitempty" toml:"pubsub,omitempty"`
}
Expose struct {
Type string `json:"type" yaml:"type" toml:"type"`
InfraParams InfraParams `json:"pulumi_params,omitempty" yaml:"pulumi_params,omitempty" toml:"pulumi_params,omitempty"`
Type string `json:"type" yaml:"type" toml:"type"`
ContentDeliveryNetwork ContentDeliveryNetwork `json:"content_delivery_network,omitempty" yaml:"content_delivery_network,omitempty" toml:"content_delivery_network,omitempty"`
InfraParams InfraParams `json:"pulumi_params,omitempty" yaml:"pulumi_params,omitempty" toml:"pulumi_params,omitempty"`
}

Persist struct {
Expand All @@ -58,8 +59,9 @@ type (
}

StaticUnit struct {
Type string `json:"type" yaml:"type" toml:"type"`
InfraParams InfraParams `json:"pulumi_params,omitempty" yaml:"pulumi_params,omitempty" toml:"pulumi_params,omitempty"`
Type string `json:"type" yaml:"type" toml:"type"`
InfraParams InfraParams `json:"pulumi_params,omitempty" yaml:"pulumi_params,omitempty" toml:"pulumi_params,omitempty"`
ContentDeliveryNetwork ContentDeliveryNetwork `json:"content_delivery_network,omitempty" yaml:"content_delivery_network,omitempty" toml:"content_delivery_network,omitempty"`
}

Defaults struct {
Expand All @@ -84,6 +86,10 @@ type (
RedisCluster KindDefaults `json:"redis_cluster" yaml:"redis_cluster" toml:"redis_cluster"`
}

ContentDeliveryNetwork struct {
Id string `json:"id,omitempty" yaml:"id,omitempty" toml:"id,omitempty"`
}

// InfraParams are passed as-is to the generated IaC
InfraParams map[string]interface{}
)
Expand Down Expand Up @@ -150,6 +156,7 @@ func (cfg *Expose) Merge(other Expose) {
if other.Type != "" {
cfg.Type = other.Type
}
cfg.ContentDeliveryNetwork = other.ContentDeliveryNetwork
cfg.InfraParams.Merge(other.InfraParams)
}

Expand All @@ -171,6 +178,7 @@ func (cfg *StaticUnit) Merge(other StaticUnit) {
if other.Type != "" {
cfg.Type = other.Type
}
cfg.ContentDeliveryNetwork = other.ContentDeliveryNetwork
cfg.InfraParams.Merge(other.InfraParams)
}

Expand Down
21 changes: 12 additions & 9 deletions pkg/infra/pulumi_aws/deploylib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,15 @@ import * as fs from 'fs'
import * as requestRetry from 'requestretry'
import * as crypto from 'crypto'
import { setupElasticacheCluster } from './iac/elasticache'

import * as analytics from './iac/analytics'

import { LoadBalancerPlugin } from './iac/load_balancing'
import {
DefaultEksClusterOptions,
Eks,
EksExecUnit,
EksExecUnitArgs,
HelmChart,
plugins as EksPlugins,
} from './iac/eks'
import { DefaultEksClusterOptions, Eks, EksExecUnit, HelmChart } from './iac/eks'
import { setupMemoryDbCluster } from './iac/memorydb'

export enum Resource {
exec_unit = 'exec_unit',
static_unit = 'static_unit',
gateway = 'gateway',
kv = 'persist_kv',
fs = 'persist_fs',
Expand All @@ -35,6 +28,11 @@ export enum Resource {
pubsub = 'pubsub',
}

export interface ResourceKey {
Kind: string
Name: string
}

interface ResourceInfo {
id: string
urn: string
Expand Down Expand Up @@ -73,6 +71,9 @@ export class CloudCCLib {
execUnitToPolicyStatements = new Map<string, aws.iam.PolicyStatement[]>()
execUnitToImage = new Map<string, pulumi.Output<String>>()

gatewayToUrl = new Map<string, pulumi.Output<string>>()
siteBuckets = new Map<string, aws.s3.Bucket>()

topologySpecOutputs: pulumi.Output<ResourceInfo>[] = []
connectionString = new Map<string, pulumi.Output<string>>()

Expand Down Expand Up @@ -1069,6 +1070,8 @@ export class CloudCCLib {
}))
)

this.gatewayToUrl.set(providedName, stage.invokeUrl)

return stage.invokeUrl
}

Expand Down
151 changes: 151 additions & 0 deletions pkg/infra/pulumi_aws/iac/cloudfront.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import * as aws from '@pulumi/aws'
import * as pulumi from '@pulumi/pulumi'
import * as mime from 'mime'
import * as fs from 'fs'
import * as path from 'path'
import { CloudCCLib, ResourceKey, Resource } from '../deploylib'

export interface CloudfrontDistribution {
Id: string
Origins: ResourceKey[]
DefaultRootObject: string
}

interface TargetOrigin {
type?: Resource.static_unit | Resource.gateway
id?: string
}

export class Cloudfront {
constructor(lib: CloudCCLib, cloudfrontDistributions: CloudfrontDistribution[]) {
for (const dist of cloudfrontDistributions) {
const origins: aws.types.input.cloudfront.DistributionOrigin[] = []
let targetOrigin: TargetOrigin = {}
const indexDocument = dist.DefaultRootObject == '' ? undefined : dist.DefaultRootObject
for (const origin of dist.Origins) {
if (origin.Kind == Resource.gateway) {
origins.push(
this.createCustomOrigin(origin.Name, lib.gatewayToUrl.get(origin.Name)!)
)
if (!targetOrigin.id) {
targetOrigin = {
type: Resource.gateway,
id: origin.Name,
}
}
} else if (origin.Kind == Resource.static_unit) {
const bucket = lib.siteBuckets.get(origin.Name)!
origins.push(this.createS3Origin(origin.Name, bucket))
targetOrigin = {
type: Resource.static_unit,
id: origin.Name,
}
}
}
this.createDistribution(dist.Id, origins, targetOrigin, indexDocument)
}
}

createCustomOrigin(
name: string,
domainName: pulumi.Output<string>
): aws.types.input.cloudfront.DistributionOrigin {
const origin: aws.types.input.cloudfront.DistributionOrigin = {
originId: name,
customOriginConfig: {
httpPort: 80,
httpsPort: 443,
originProtocolPolicy: 'https-only',
originSslProtocols: ['SSLv3', 'TLSv1', 'TLSv1.1', 'TLSv1.2'],
},
domainName: domainName.apply((d) => d.split('//')[1].split('/')[0]),
originPath: domainName.apply((d) => '/' + d.split('//')[1].split('/')[1]),
}
return origin
}

createS3Origin(
name: string,
siteBucket: aws.s3.Bucket
): aws.types.input.cloudfront.DistributionOrigin {
const originAccessIdentity = new aws.cloudfront.OriginAccessIdentity(
`${siteBucket}-originAccessIdentity`,
{
comment: 'this is needed to setup s3 polices and make s3 not public.',
}
)

new aws.s3.BucketPolicy('bucketPolicy', {
bucket: siteBucket.id, // refer to the bucket created earlier
policy: pulumi
.all([originAccessIdentity.iamArn, siteBucket.arn])
.apply(([oaiArn, bucketArn]) =>
JSON.stringify({
Version: '2012-10-17',
Statement: [
{
Effect: 'Allow',
Principal: {
AWS: oaiArn,
}, // Only allow Cloudfront read access.
Action: ['s3:GetObject'],
Resource: [`${bucketArn}/*`], // Give Cloudfront access to the entire bucket.
},
],
})
),
})

const origin = {
domainName: siteBucket.bucketRegionalDomainName,
originId: name,
s3OriginConfig: {
originAccessIdentity: originAccessIdentity.cloudfrontAccessIdentityPath,
},
}

return origin
}

createDistribution(
name,
origins,
targetOrigin: TargetOrigin,
indexDocument?
): aws.cloudfront.Distribution {
let defaultTtl = 3600
if (targetOrigin.type == Resource.gateway) {
defaultTtl = 0
}

const distribution = new aws.cloudfront.Distribution(name, {
origins,
enabled: true,
viewerCertificate: {
cloudfrontDefaultCertificate: true,
},
defaultCacheBehavior: {
allowedMethods: ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT'],
cachedMethods: ['HEAD', 'GET'],
targetOriginId: targetOrigin.id!,
forwardedValues: {
queryString: true,
cookies: {
forward: 'none',
},
},
viewerProtocolPolicy: 'allow-all',
minTtl: 0,
defaultTtl,
maxTtl: 86400,
},
restrictions: {
geoRestriction: {
restrictionType: 'none',
},
},
defaultRootObject: indexDocument,
})
return distribution
}
}
106 changes: 6 additions & 100 deletions pkg/infra/pulumi_aws/iac/static_s3_website.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,121 +3,27 @@ import * as pulumi from '@pulumi/pulumi'
import * as mime from 'mime'
import * as fs from 'fs'
import * as path from 'path'
import { CloudCCLib } from '../deploylib'

export const createStaticS3Website = (
staticUnit: string,
indexDocument: string,
params
): pulumi.Output<string> => {
contentDeliveryNetworkId: string,
lib: CloudCCLib
) => {
// Create an S3 bucket

const bucketArgs: aws.s3.BucketArgs = {}

if (indexDocument != '' && !params.cloudFrontEnabled) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does this !params.cloudFrontEnabled still need to exist? The cloudfrontenabled code was moved out but i'm assuming the following code still shouldn't be run if it is enabled?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah youre right, we should still be checking if its enabled here. will need to update

if (indexDocument != '' && contentDeliveryNetworkId == '') {
bucketArgs['website'] = {
indexDocument: indexDocument,
}
}

let siteBucket = new aws.s3.Bucket(`static-website-${staticUnit}`, bucketArgs)
lib.siteBuckets.set(staticUnit, siteBucket)
createAllObjects(staticUnit, siteBucket)

if (params.cloudFrontEnabled) {
// Generate Origin Access Identity to access the private s3 bucket.
const originAccessIdentity = new aws.cloudfront.OriginAccessIdentity(
'originAccessIdentity',
{
comment: 'this is needed to setup s3 polices and make s3 not public.',
}
)

const bucketPolicy = new aws.s3.BucketPolicy('bucketPolicy', {
bucket: siteBucket.id, // refer to the bucket created earlier
policy: pulumi
.all([originAccessIdentity.iamArn, siteBucket.arn])
.apply(([oaiArn, bucketArn]) =>
JSON.stringify({
Version: '2012-10-17',
Statement: [
{
Effect: 'Allow',
Principal: {
AWS: oaiArn,
}, // Only allow Cloudfront read access.
Action: ['s3:GetObject'],
Resource: [`${bucketArn}/*`], // Give Cloudfront access to the entire bucket.
},
],
})
),
})

const distribution = new aws.cloudfront.Distribution(`cdn-static-${staticUnit}`, {
origins: [
{
domainName: siteBucket.bucketRegionalDomainName,
originId: siteBucket.arn,
s3OriginConfig: {
originAccessIdentity: originAccessIdentity.cloudfrontAccessIdentityPath,
},
},
],
enabled: true,
viewerCertificate: {
cloudfrontDefaultCertificate: true,
},
defaultCacheBehavior: {
allowedMethods: ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT'],
cachedMethods: ['GET', 'HEAD'],
targetOriginId: siteBucket.arn,
forwardedValues: {
queryString: false,
cookies: {
forward: 'none',
},
},
viewerProtocolPolicy: 'allow-all',
minTtl: 0,
defaultTtl: 3600,
maxTtl: 86400,
},
restrictions: {
geoRestriction: {
restrictionType: 'none',
},
},
defaultRootObject: indexDocument,
})

return distribution.domainName
} else {
// Create an S3 Bucket Policy to allow public read of all objects in bucket
// This reusable function can be pulled out into its own module
function publicReadPolicyForBucket(bucketName) {
return JSON.stringify({
Version: '2012-10-17',
Statement: [
{
Effect: 'Allow',
Principal: '*',
Action: ['s3:GetObject'],
Resource: [
`arn:aws:s3:::${bucketName}/*`, // policy refers to bucket name explicitly
],
},
],
})
}

// Set the access policy for the bucket so all objects are readable
let bucketPolicy = new aws.s3.BucketPolicy('bucketPolicy', {
bucket: siteBucket.bucket, // depends on siteBucket -- see explanation below
policy: siteBucket.bucket.apply(publicReadPolicyForBucket),
// transform the siteBucket.bucket output property -- see explanation below
})

return siteBucket.websiteEndpoint
}
}

const createAllObjects = (staticUnit, siteBucket, prefixPath = '') => {
Expand Down
Loading