-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge 'feature/s3-temp-web-storage' into main
- Loading branch information
Showing
9 changed files
with
207 additions
and
4 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
This folder contains utilities for a common pattern where S3 is used as temporary storage for a website, and an apigateway provides access to get pre-signed s3 urls to access objects in the s3 bucket. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
import {fileURLToPath} from 'node:url' | ||
import {dirname, resolve} from 'node:path' | ||
|
||
import {Aws, RemovalPolicy, Duration, Fn} from 'aws-cdk-lib' | ||
import {CfnAccount} from 'aws-cdk-lib/aws-apigateway' | ||
import {HttpLambdaIntegration} from '@aws-cdk/aws-apigatewayv2-integrations-alpha' | ||
import {HttpApi, HttpMethod, CorsHttpMethod} from '@aws-cdk/aws-apigatewayv2-alpha' | ||
import {Bucket, HttpMethods, BucketEncryption} from 'aws-cdk-lib/aws-s3' | ||
import {PolicyStatement} from 'aws-cdk-lib/aws-iam' | ||
import {NodejsFunction} from 'aws-cdk-lib/aws-lambda-nodejs' | ||
import {Runtime} from 'aws-cdk-lib/aws-lambda' | ||
import {AllowedMethods} from 'aws-cdk-lib/aws-cloudfront' | ||
|
||
const __dirname = dirname(fileURLToPath(import.meta.url)) | ||
|
||
export class S3TempWebStorageResources { | ||
#bucket | ||
#httpApi | ||
|
||
constructor(stack, cloudFrontResources, corsAllowedOrigins, objectExpiry, httpApiPrefix, getItemUrlsEndpoint) { | ||
new CfnAccount(stack, 'agiGatewayAccount', { | ||
//use a centrally created role so that it doesn't get deleted when this stack is torn down | ||
cloudWatchRoleArn: Fn.importValue('AllAccountsStack-apiGatewayCloudWatchRoleArn') | ||
}) | ||
|
||
let bucketProps = { | ||
removalPolicy: RemovalPolicy.DESTROY, | ||
encryption: BucketEncryption.S3_MANAGED, | ||
autoDeleteObjects: true, | ||
lifecycleRules: [ | ||
{ | ||
id: 'expire', | ||
expiration: objectExpiry //e.g. Duration.days(1) | ||
}, | ||
{ | ||
id: 'cleanup', | ||
abortIncompleteMultipartUploadAfter: Duration.days(1) | ||
} | ||
] | ||
} | ||
if (corsAllowedOrigins != null) { | ||
bucketProps.cors = [ | ||
{ | ||
allowedMethods: [HttpMethods.GET, HttpMethods.PUT], | ||
allowedOrigins: corsAllowedOrigins, | ||
allowedHeaders: ['Content-Type'] | ||
} | ||
] | ||
} | ||
this.#bucket = new Bucket(stack, 'filesBucket', bucketProps) | ||
|
||
const httpApiProps = { | ||
apiName: `${Aws.STACK_NAME}-httpApi` | ||
} | ||
if (corsAllowedOrigins != null) { | ||
httpApiProps.corsPreflight = { | ||
allowMethods: [CorsHttpMethod.POST], | ||
allowOrigins: corsAllowedOrigins | ||
} | ||
} | ||
this.#httpApi = new HttpApi(stack, 'httpApi', httpApiProps) | ||
|
||
cloudFrontResources.addHttpApi(`${httpApiPrefix}/*`, this.#httpApi, AllowedMethods.ALLOW_ALL) | ||
|
||
this.#buildHandler(stack, getItemUrlsEndpoint, 'get-item-urls', httpApiPrefix) | ||
} | ||
|
||
#buildHandler(stack, name, entry, httpApiPrefix) { | ||
let handler = this.#buildGenericHandler(stack, `${name}-handler`, entry, { | ||
BUCKET: this.#bucket.bucketName | ||
}) | ||
handler.addToRolePolicy( | ||
new PolicyStatement({ | ||
resources: [ | ||
this.#bucket.arnForObjects('*') //"arn:aws:s3:::bucketname/*" | ||
], | ||
actions: ['s3:GetObject', 's3:PutObject'] | ||
}) | ||
) | ||
let integration = new HttpLambdaIntegration(`${name}-integration`, handler) | ||
this.#httpApi.addRoutes({ | ||
path: `/${httpApiPrefix}/${name}`, | ||
methods: [HttpMethod.POST], | ||
integration: integration | ||
}) | ||
} | ||
|
||
#buildGenericHandler(stack, name, entry, envs) { | ||
const handler = new NodejsFunction(stack, name, { | ||
entry: resolve(__dirname, `../src/${entry}.js`), | ||
memorySize: 128, | ||
timeout: Duration.seconds(20), | ||
runtime: Runtime.NODEJS_20_X, | ||
environment: envs | ||
}) | ||
return handler | ||
} | ||
|
||
get httpApi() { | ||
return this.#httpApi | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
export const endpointFileNameParam = 'fileName' | ||
export const endpointPrefixesParam = 'prefixes' |
40 changes: 40 additions & 0 deletions
40
aws/utils/src/stacks/s3-temp-web-storage/src/get-item-urls.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import {randomUUID} from 'crypto' | ||
|
||
import {BUCKET, aws} from './utils.js' | ||
import {endpointFileNameParam, endpointPrefixesParam} from '../shared/constants.js' | ||
const s3 = new aws.S3() | ||
|
||
export async function handler(event) { | ||
let {body} = event | ||
if (event.isBase64Encoded) { | ||
body = Buffer.from(event.body, 'base64') | ||
} | ||
body = JSON.parse(body) | ||
const fileName = body?.[endpointFileNameParam] | ||
const prefixes = body?.[endpointPrefixesParam] | ||
let errors = [] | ||
if (fileName == null || fileName.length == 0) { | ||
errors.push(`parameter '${endpointFileNameParam}' must be specified and non-empty string`) | ||
} | ||
if (prefixes != null && (!Array.isArray(prefixes) || prefixes.length == 0)) { | ||
errors.push(`if specified, parameter '${endpointPrefixesParam}' must be a non-zero length array`) | ||
} | ||
if (errors.length > 0) { | ||
return { | ||
isBase64Encoded: false, | ||
statusCode: 400, | ||
body: errors.join('; ') | ||
} | ||
} | ||
const randomizer = randomUUID() //prevents object names in the bucket being predictable, and also prevents clashes by different files that are named the same | ||
const prefix = prefixes != null && prefixes.length > 0 ? [...prefixes, ''].join('/') : '' | ||
const key = `${prefix}${fileName}-${randomizer}` | ||
const sign = async operation => await s3.getSignedUrlPromise(operation, {Bucket: BUCKET, Key: key}) | ||
const getUrl = await sign('getObject') | ||
const putUrl = await sign('putObject') | ||
|
||
return { | ||
getUrl, | ||
putUrl | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
import dotenv from 'dotenv' | ||
import aws from 'aws-sdk' | ||
|
||
dotenv.config() | ||
|
||
aws.config.apiVersions = { | ||
s3: '2006-03-01' | ||
} | ||
|
||
export {aws} | ||
|
||
export const {BUCKET} = process.env |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters