-
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.
- Loading branch information
0 parents
commit 3420ca0
Showing
16 changed files
with
4,940 additions
and
0 deletions.
There are no files selected for viewing
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,41 @@ | ||
name: Build & Test | ||
|
||
on: [push] | ||
|
||
jobs: | ||
test: | ||
runs-on: ubuntu-latest | ||
steps: | ||
- name: Checkout | ||
uses: actions/checkout@v4 | ||
|
||
- name: Install Node.js | ||
uses: actions/setup-node@v4 | ||
with: | ||
node-version: 22 | ||
|
||
- name: npm ci | ||
run: npm ci | ||
|
||
- name: Test | ||
run: npm run test | ||
|
||
build: | ||
runs-on: ubuntu-latest | ||
steps: | ||
- name: Checkout | ||
uses: actions/checkout@v4 | ||
|
||
- name: Install Node.js | ||
uses: actions/setup-node@v4 | ||
with: | ||
node-version: 22 | ||
|
||
- name: Install AWS CDK | ||
run: npm install -g aws-cdk | ||
|
||
- name: npm ci | ||
run: npm ci | ||
|
||
- name: CDK Synth | ||
run: cdk synth --context stage=test |
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,7 @@ | ||
cdk.out | ||
|
||
node_modules | ||
|
||
.idea | ||
|
||
links.json |
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,24 @@ | ||
This is free and unencumbered software released into the public domain. | ||
|
||
Anyone is free to copy, modify, publish, use, compile, sell, or | ||
distribute this software, either in source code form or as a compiled | ||
binary, for any purpose, commercial or non-commercial, and by any | ||
means. | ||
|
||
In jurisdictions that recognize copyright laws, the author or authors | ||
of this software dedicate any and all copyright interest in the | ||
software to the public domain. We make this dedication for the benefit | ||
of the public at large and to the detriment of our heirs and | ||
successors. We intend this dedication to be an overt act of | ||
relinquishment in perpetuity of all present and future rights to this | ||
software under copyright law. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | ||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | ||
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR | ||
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, | ||
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | ||
OTHER DEALINGS IN THE SOFTWARE. | ||
|
||
For more information, please refer to <https://unlicense.org> |
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,63 @@ | ||
# cloud-url | ||
|
||
A CDK-managed URL-shortener implemented in a CloudFront viewer function | ||
|
||
Features: | ||
- 1-click deploy via AWS CDK | ||
- ~100ms response time | ||
- Link management via a JSON file | ||
- Expiring links | ||
- Request logging | ||
|
||
Try it out [here](https://i.adriank.dev/cloud-url) | ||
|
||
## Deploying | ||
|
||
Bootstrap: | ||
``` | ||
npm i | ||
cdk bootstrap | ||
``` | ||
|
||
Deploy: | ||
``` | ||
cdk deploy --context stage=main | ||
``` | ||
|
||
🎉 You can now access links at: `https://{cloudfront_distribution_id}/{link_id}` | ||
|
||
🔗 The console output will contain the URL of the CloudFront distribution which uses | ||
the redirect viewer function. | ||
|
||
🌍 The region is locked to us-east-1, as this allows us to configure the function log group | ||
from the CDK. | ||
|
||
⏳ CloudFront functions take ~5 minutes to deploy. The CDK deploy process is | ||
synchronous, unlike the AWS console which processes function updates asynchronously. | ||
|
||
📄 You can deploy multiple instances by altering the `stage` context value. | ||
|
||
## Managing links | ||
|
||
Update [`links.json`](./links.json) and deploy! | ||
|
||
Links can be added either in the format: | ||
```javascript | ||
{ | ||
// Simple format, no expiration | ||
"LINK_ID": "URL", | ||
// Object format, with optional expiration | ||
"LINK_ID": { | ||
"url": "URL", | ||
"expiresAt": "ISO8601 date" | ||
} | ||
} | ||
``` | ||
|
||
## Tests | ||
|
||
Run unit tests with `npm run test` | ||
|
||
## License | ||
|
||
[The Unlicense](./LICENSE) |
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,26 @@ | ||
#!/usr/bin/env node | ||
import 'source-map-support/register'; | ||
import * as cdk from 'aws-cdk-lib'; | ||
import { CloudUrlStack } from '../infra/cloud-url-stack'; | ||
|
||
const app = new cdk.App(); | ||
const stage = app.node.tryGetContext('stage') | ||
|
||
new CloudUrlStack(app, 'CloudUrlStack', { | ||
|
||
stage, | ||
|
||
/* If you don't specify 'env', this stack will be environment-agnostic. | ||
* Account/Region-dependent features and context lookups will not work, | ||
* but a single synthesized template can be deployed anywhere. */ | ||
|
||
/* Uncomment the next line to specialize this stack for the AWS Account | ||
* and Region that are implied by the current CLI configuration. */ | ||
// env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION }, | ||
|
||
/* Uncomment the next line if you know exactly what Account and Region you | ||
* want to deploy the stack to. */ | ||
// env: { account: '123456789012', region: 'us-east-1' }, | ||
|
||
/* For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html */ | ||
}); |
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,68 @@ | ||
{ | ||
"app": "npx ts-node --prefer-ts-exts bin/cloud-url.ts", | ||
"watch": { | ||
"include": [ | ||
"**" | ||
], | ||
"exclude": [ | ||
"README.md", | ||
"cdk*.json", | ||
"**/*.d.ts", | ||
"**/*.js", | ||
"tsconfig.json", | ||
"package*.json", | ||
"yarn.lock", | ||
"node_modules", | ||
"test" | ||
] | ||
}, | ||
"context": { | ||
"@aws-cdk/aws-lambda:recognizeLayerVersion": true, | ||
"@aws-cdk/core:checkSecretUsage": true, | ||
"@aws-cdk/core:target-partitions": [ | ||
"aws", | ||
"aws-cn" | ||
], | ||
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true, | ||
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true, | ||
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true, | ||
"@aws-cdk/aws-iam:minimizePolicies": true, | ||
"@aws-cdk/core:validateSnapshotRemovalPolicy": true, | ||
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true, | ||
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true, | ||
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true, | ||
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true, | ||
"@aws-cdk/core:enablePartitionLiterals": true, | ||
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true, | ||
"@aws-cdk/aws-iam:standardizedServicePrincipals": true, | ||
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true, | ||
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true, | ||
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true, | ||
"@aws-cdk/aws-route53-patters:useCertificate": true, | ||
"@aws-cdk/customresources:installLatestAwsSdkDefault": false, | ||
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true, | ||
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true, | ||
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true, | ||
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true, | ||
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true, | ||
"@aws-cdk/aws-redshift:columnId": true, | ||
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true, | ||
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true, | ||
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true, | ||
"@aws-cdk/aws-kms:aliasNameRef": true, | ||
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true, | ||
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true, | ||
"@aws-cdk/aws-efs:denyAnonymousAccess": true, | ||
"@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true, | ||
"@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true, | ||
"@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true, | ||
"@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true, | ||
"@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true, | ||
"@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true, | ||
"@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true, | ||
"@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": true, | ||
"@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": true, | ||
"@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": true, | ||
"@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": true | ||
} | ||
} |
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,121 @@ | ||
import {aws_cloudfront, aws_logs, Stack, StackProps, Tags} from 'aws-cdk-lib'; | ||
import {Construct} from 'constructs'; | ||
import { | ||
AllowedMethods, | ||
CfnDistribution, | ||
CfnFunction, Distribution, | ||
FunctionEventType, | ||
HttpVersion, | ||
ViewerProtocolPolicy | ||
} from "aws-cdk-lib/aws-cloudfront"; | ||
import {HttpOrigin} from "aws-cdk-lib/aws-cloudfront-origins"; | ||
import {OutputSet} from "./constructs/output-set"; | ||
import {CfnLogGroup, LogGroup, RetentionDays} from "aws-cdk-lib/aws-logs"; | ||
import {readFileSync} from "fs"; | ||
import {readLinksFromFile} from "./utils"; | ||
|
||
export type LinkRecords = { | ||
[key: string]: string | { url: string, expiresAt: string } | ||
}; | ||
|
||
type CloudUrlStackProps = StackProps & { | ||
stage?: string, | ||
} | ||
|
||
export class CloudUrlStack extends Stack { | ||
|
||
stage: string; | ||
|
||
constructor(scope: Construct, id: string, props?: CloudUrlStackProps) { | ||
|
||
if (props?.stage == null) { | ||
throw new Error('Stage not set'); | ||
} | ||
|
||
super(scope, id, { | ||
...props, | ||
stackName: `CloudUrl-${props?.stage}`, | ||
env: { | ||
// Force us-east-1 as this is our only option if we want to control the log group :-/ | ||
region: 'us-east-1', | ||
} | ||
}); | ||
|
||
this.stage = props.stage; | ||
|
||
// Tag all resources | ||
Tags.of(this).add('STAGE', this.stage); | ||
|
||
const functionName = `CloudUrl-Redirect-${this.stage}`; | ||
|
||
const logGroup = this.createLogGroup(functionName); | ||
|
||
const links = readLinksFromFile(); | ||
|
||
const redirectFn = this.createRedirectFunction(functionName, logGroup, links); | ||
|
||
const distribution = this.createDistribution(redirectFn); | ||
|
||
new OutputSet(this, 'Outputs', { | ||
values: { | ||
distributionId: distribution.distributionId, | ||
distributionUrl: `https://${distribution.distributionDomainName}`, | ||
linkCount: Object.keys(links).length.toString(), | ||
logGroup: logGroup.logGroupName, | ||
}, | ||
}) | ||
} | ||
|
||
createLogGroup(functionName: string): LogGroup { | ||
const logGroup = new aws_logs.LogGroup(this, 'LogGroup', { | ||
retention: RetentionDays.THREE_MONTHS, | ||
logGroupName: `/aws/cloudfront/function/${functionName}`, | ||
}); | ||
(logGroup.node.defaultChild as CfnLogGroup).overrideLogicalId('LogGroup'); | ||
return logGroup; | ||
} | ||
|
||
createRedirectFunction(functionName: string, logGroup: LogGroup, links: LinkRecords): aws_cloudfront.Function { | ||
|
||
const functionCode = readFileSync('./src/handler.js').toString() | ||
// Strip module.exports (required to test the function) | ||
.replace(/module.exports = { (.*) };/i, '') | ||
// Inject the link records | ||
.replace('// LINKS_HERE', `links = Object.assign(links, ${JSON.stringify(links)});`); | ||
|
||
const redirectFn = new aws_cloudfront.Function(this, 'Function', { | ||
functionName, | ||
comment: 'CloudUrl redirect viewer function', | ||
code: aws_cloudfront.FunctionCode.fromInline(functionCode), | ||
runtime: aws_cloudfront.FunctionRuntime.JS_2_0, | ||
}); | ||
// Create the function after the log group, forcing AWS to use the log group we created, rather than creating | ||
// one automatically | ||
redirectFn.node.addDependency(logGroup); | ||
(redirectFn.node.defaultChild as CfnFunction).overrideLogicalId('Function'); | ||
|
||
return redirectFn; | ||
} | ||
|
||
createDistribution(redirectFn: aws_cloudfront.Function): Distribution { | ||
const distribution = new aws_cloudfront.Distribution(this, 'CfDistribution', { | ||
comment: `CloudUrl distribution - ${this.stage}`, | ||
defaultBehavior: { | ||
// CF needs to exist in front of _something_, so we'll use a random domain that will never exist | ||
origin: new HttpOrigin('not-real.invalid'), | ||
functionAssociations: [ | ||
{ | ||
function: redirectFn, | ||
eventType: FunctionEventType.VIEWER_REQUEST, | ||
} | ||
], | ||
allowedMethods: AllowedMethods.ALLOW_GET_HEAD_OPTIONS, | ||
viewerProtocolPolicy: ViewerProtocolPolicy.HTTPS_ONLY, | ||
}, | ||
httpVersion: HttpVersion.HTTP2_AND_3, | ||
}); | ||
(distribution.node.defaultChild as CfnDistribution).overrideLogicalId('CfDistribution'); | ||
|
||
return distribution; | ||
} | ||
} |
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,22 @@ | ||
import { Construct } from 'constructs'; | ||
import { CfnOutput } from 'aws-cdk-lib'; | ||
|
||
export type OutputSetProps = { | ||
values: Record<string, string>; | ||
}; | ||
|
||
export class OutputSet extends Construct { | ||
public outputs: Record<string, CfnOutput>; | ||
|
||
constructor(scope: Construct, id: string, props: OutputSetProps) { | ||
super(scope, id); | ||
|
||
this.outputs = {}; | ||
Object.entries(props.values).forEach(([key, value]) => { | ||
this.outputs[key] = new CfnOutput(this, `Output-${key}`, { | ||
key, | ||
value, | ||
}); | ||
}); | ||
} | ||
} |
Oops, something went wrong.