Skip to content

Commit

Permalink
Initial commit - 1.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
Igrom committed Apr 22, 2018
0 parents commit df7a532
Show file tree
Hide file tree
Showing 10 changed files with 1,402 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*.sh
node_modules
13 changes: 13 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Copyright [Year, e.g., 2017] Cimpress

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
127 changes: 127 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
# Gatefold

The compact URL shortener, developed at Cimpress.

Gatefold is a quick to set up, simple to use URL shortener built with Amazon API Gateway and Amazon DynamoDB and codified with Amazon CloudFormation.

Features:
- deploy a URL shortener to your AWS account in **five seconds**!
- shorten URLs and store a token to change it later
- create vanity URLs by passing custom strings
- specify a TTL for all shortened URLs on the domain.

The entire setup is bootstrapped with a CLI tool written in Node.js, which allows you to deploy or delete Gatefold stacks for several domains in multiple AWS accounts and regions. It is also possible to print the pre-populated API definition or the CloudFormation template to standard output for external processing.

No computing engines apart from API Gateway's VTL mapping templates are used, where all logic is stored.

## Getting Started

Install the [Gatefold package](https://www.npmjs.com/package/gatefold) using npm or yarn:
```
npm install -g gatefold
```
To check your installation, run `gatefold --version`.

Now that you've installed Gatefold, you can deploy your custom URL shortener service:
```
gatefold deploy example.org
```
This will create a new Gatefold stack in your default AWS account and region. To change the target, use `--profile <profile>` and `--region <region>`.
```
gatefold deploy \
--profile my-other-profile \
--region eu-west-1 \
example.org
```
Afterwards, [set up a custom domain name](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-custom-domains.html) and [add an ALIAS record](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-creating.html) for the Amazon CloudFront distribution to hook it up to your domain. Both operations are easily accessible in the web console.
Wait for it to become available:
```
until host example.org | grep address; do sleep 5; done \
&& echo "It's up!"
```

## Consuming the API

Create your first shortened URL:
```
POST HTTP/1.1
Host: example.org
Content-Type: application/json
{
"longUrl": "https://cimpress.com"
}
```

The server responds with the shortened URL and a token:
```
HTTP/1.1 200 OK
Content-Type: application/json
{
"longUrl": "https://cimpress.com",
"shortUrl": "https://example.org/f530e741",
"token": "a2354cd3-463e-11e8-ad00-8a820fb8b897"
}
```

You can also create a vanity URL passing a custom string:
```
PUT /gatefold HTTP/1.1
Host: example.org
Content-Type: application/json
{
"longUrl": "https://cimpress.com",
"token": "vas12tmsuo"
}
```
Update it by repeating the request with the same token.

## Commands
You can see more information about a command by passing `--help` to the command, e.g. `gatefold deploy --help`.

##### gatefold deploy **domain**
Creates a new Gatefold stack in your AWS account or updates an existing one.
Specify TTL in days with `--ttl <ttl>`. The default is 3650, i.e. ten years.

##### gatefold delete **domain**
Deletes a Gatefold stack from your AWS account.

For `gatefold deploy` and `gatefold delete` possible to switch your default AWS account or region by passing `--profile <profile>` and `--region <region>` respectively.

##### gatefold get-swagger **domain**
Builds the Swagger API definition for Gatefold and prints it to standard output.
Specify TTL in days with `--ttl <ttl>`. The default is 3650, i.e. ten years.


##### gatefold get-cloudformation **domain**
Builds the CloudFormation template for Gatefold and prints it to standard output.
Specify TTL in days with `--ttl <ttl>`. The default is 3650, i.e. ten years.

## Built With

* [commander.js](https://github.com/tj/commander.js/) - Node.js CLI framework
* [cfn](https://github.com/Nordstrom/cfn) - Amazon CloudFormation automation
* [Swagger 2.0](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md) - RESTful API description
* [Amazon API Gateway](https://aws.amazon.com/api-gateway/) - reliable API publishing
* [Amazon DynamoDB](https://aws.amazon.com/dynamodb/) - low-cost NoSQL document store
* [Amazon CloudFormation](https://aws.amazon.com/cloudformation/) - Infrastructure-as-Code (IaC), Infrastructure-as-a-Service (IaaS) solution

## Contributing

Have you benefited from the tool? Have you found or fixed a bug? Would you like to see a new feature implemented? We are eager to collaborate with you on GitHub.

## Versioning

We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/your/project/tags).

## Authors

* **Igor Sowinski** <[[email protected]](mailto:[email protected]), [[email protected]](mailto:[email protected])> - [GitHub](https://github.com/Igrom)

See also the list of [contributors](https://github.com/your/project/contributors) who participated in this project.

## License

This project is licensed under the Apache 2.0 license - see the [LICENSE.md](LICENSE.md) file for details.
93 changes: 93 additions & 0 deletions bin/gatefold.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
#!/usr/bin/env node

const commander = require("commander");
const cfn = require("cfn");
const aws = require("aws-sdk");
const path = require("path");
const util = require("util");

const { Gatefold } = require(path.join(__dirname, "../index"));

const swaggerPath = path.join(__dirname, "../src/swagger.json");
const cloudformationPath = path.join(__dirname, "../src/gatefold.template");
const version = require(path.join(__dirname, "../package.json")).version;

const configureAWS = (profile, region) => {
aws.config.credentials = new aws.SharedIniFileCredentials({profile: profile || "default"});
aws.config.region = region || aws.config.region;
};

const makeStackName = domain => `Gatefold-${domain.replace(new RegExp("\\.", "g"), "-")}`;

commander.version(version);

commander
.command("deploy <domain>")
.description("Create or update a Gatefold stack")
.option("-r, --region <region>", "select another AWS region")
.option("-p, --profile <profile>", "select another AWS profile\n")
.option("-t, --ttl <ttl>", "provide a TTL in days", "3650")
.action((domain, options) => {
configureAWS(options.profile, options.region);

let name = makeStackName(domain);
let ttl = options["ttl"];

let gatefold = new Gatefold(swaggerPath, cloudformationPath);
let template = gatefold.build(false, domain, ttl);

cfn({
name,
capabilities: ["CAPABILITY_NAMED_IAM"]
}, template)
.then(() => console.log("Done!"))
.catch(err => {
console.error(err.message);
process.exit(1);
});
});

commander
.command("get-swagger <domain>")
.description("Build and return a Gatefold Swagger API definition")
.option("-t, --ttl <ttl>", "provide a TTL in days", "3650")
.option("-s, --scrub-aws", "remove AWS integration options", false)
.action((domain, options) => {
let ttl = options["ttl"];
let scrubAws = options["scrubAws"];

let gatefold = new Gatefold(swaggerPath, cloudformationPath);
let swagger = gatefold.buildSwagger(scrubAws, domain, ttl);
console.log(JSON.stringify(swagger, null, 4));
});

commander
.command("get-cloudformation <domain>")
.description("Build and return a Gatefold Cloudformation template")
.option("-t, --ttl <ttl>", "provide a TTL in days", "3650")
.action((domain, options) => {
let ttl = options["ttl"];

let gatefold = new Gatefold(swaggerPath, cloudformationPath);

let template = gatefold.build(false, domain, ttl);
console.log(JSON.stringify(template, null, 4));
});

commander
.command("delete <domain>")
.description("Delete a Gatefold stack")
.option("-r, --region <region>", "select another AWS region")
.option("-p, --profile <profile>", "select another AWS profile\n")
.action((domain, options) => { configureAWS(options.profile, options.region);
let name = makeStackName(domain);

cfn.delete(name)
.then(() => console.log(`Stack ${name} has been removed.`))
.catch(err => {
console.error(err.message);
process.exit(1);
});
});

commander.parse(process.argv);
1 change: 1 addition & 0 deletions file
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"AWSTemplateFormatVersion":"2010-09-09","Resources":{"GatefoldAPIGateway":{"Type":"AWS::ApiGateway::RestApi","Properties":{"Body":{"swagger":"2.0","info":{"version":"2018-04-19T14:20:40Z","title":"Gatefold"},"host":"sowinski.blue","schemes":["https"],"paths":{"/":{"post":{"consumes":["application/json"],"produces":["application/json"],"responses":{"200":{"description":"200 response","schema":{"$ref":"#/definitions/Empty"},"headers":{"Access-Control-Allow-Origin":{"type":"string"}}}},"security":[{"auth0":[]}],"x-amazon-apigateway-integration":{"credentials":{"Fn::GetAtt":["GatefoldAPIRole","Arn"]},"uri":"arn:aws:apigateway:eu-west-1:dynamodb:action/PutItem","responses":{"default":{"statusCode":"200","responseParameters":{"method.response.header.Access-Control-Allow-Origin":"'*'"},"responseTemplates":{"application/json":"#set ($rand = $context.requestId.substring(28))\n\n{\n \"shortUrl\": \"https://sowinski.blue/$rand\"\n}"}}},"passthroughBehavior":"never","httpMethod":"POST","requestTemplates":{"application/json":"#set ($rand = $context.requestId.substring(28))\n{\n \"TableName\": \"gatefold\",\n \"Item\": {\n \"ShortUrl\": {\n \"S\": \"$rand\"\n },\n \"LongUrl\": {\n \"S\": $input.json('$.longUrl')\n }\n }\n}\n"},"type":"aws"}},"options":{"consumes":["application/json"],"produces":["application/json"],"responses":{"200":{"description":"200 response","schema":{"$ref":"#/definitions/Empty"},"headers":{"Access-Control-Allow-Origin":{"type":"string"},"Access-Control-Allow-Methods":{"type":"string"},"Access-Control-Allow-Headers":{"type":"string"}}}},"x-amazon-apigateway-integration":{"responses":{"default":{"statusCode":"200","responseParameters":{"method.response.header.Access-Control-Allow-Methods":"'POST,OPTIONS'","method.response.header.Access-Control-Allow-Headers":"'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'","method.response.header.Access-Control-Allow-Origin":"'*'"}}},"passthroughBehavior":"when_no_match","requestTemplates":{"application/json":"{\"statusCode\": 200}"},"type":"mock"}}},"/livecheck":{"get":{"consumes":["application/json"],"produces":["application/json"],"responses":{"200":{"description":"200 response","schema":{"$ref":"#/definitions/Empty"}}},"x-amazon-apigateway-integration":{"responses":{"default":{"statusCode":"200"}},"passthroughBehavior":"when_no_match","requestTemplates":{"application/json":"{\"statusCode\": 200}"},"type":"mock"}}},"/not-found":{"get":{"consumes":["application/json"],"responses":{"404":{"description":"404 response"}},"x-amazon-apigateway-integration":{"responses":{"default":{"statusCode":"404"}},"passthroughBehavior":"when_no_match","requestTemplates":{"application/json":"{\"statusCode\": 404}"},"type":"mock"}},"options":{"consumes":["application/json"],"produces":["application/json"],"responses":{"200":{"description":"200 response","schema":{"$ref":"#/definitions/Empty"},"headers":{"Access-Control-Allow-Origin":{"type":"string"},"Access-Control-Allow-Methods":{"type":"string"},"Access-Control-Allow-Headers":{"type":"string"}}}},"x-amazon-apigateway-integration":{"responses":{"default":{"statusCode":"200","responseParameters":{"method.response.header.Access-Control-Allow-Methods":"'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'","method.response.header.Access-Control-Allow-Headers":"'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'","method.response.header.Access-Control-Allow-Origin":"'*'"}}},"passthroughBehavior":"when_no_match","requestTemplates":{"application/json":"{\"statusCode\": 200}"},"type":"mock"}}},"/{id}":{"get":{"produces":["application/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"string"}],"responses":{"302":{"description":"302 response","headers":{"Location":{"type":"string"}}}},"x-amazon-apigateway-integration":{"uri":"https://sowinski.blue/{id}/proxied","responses":{"default":{"statusCode":"302","responseParameters":{"method.response.header.Location":"integration.response.body.longUrl"},"responseTemplates":{"application/json":"#set($inputRoot = $input.path('$'))\n{ }"}}},"requestParameters":{"integration.request.path.id":"method.request.path.id"},"passthroughBehavior":"when_no_match","httpMethod":"GET","type":"http"}}},"/{id}/proxied":{"get":{"consumes":["application/json"],"produces":["application/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"string"}],"responses":{"200":{"description":"200 response"}},"x-amazon-apigateway-integration":{"credentials":{"Fn::GetAtt":["GatefoldAPIRole","Arn"]},"uri":"arn:aws:apigateway:eu-west-1:dynamodb:action/GetItem","responses":{"default":{"statusCode":"200","responseTemplates":{"application/json":"#set($inputRoot = $input.path('$'))\n#if($inputRoot.Item.LongUrl.S.isEmpty())\n#set($val = \"https://sowinski.blue/not-found\")\n#else\n #set($val = $inputRoot.Item.LongUrl.S)\n#end\n\n{\n \"longUrl\": \"$val\"\n}"}}},"passthroughBehavior":"never","httpMethod":"POST","requestTemplates":{"application/json":"{\n \"TableName\": \"gatefold\",\n \"Key\": {\n \"ShortUrl\": {\n \"S\": \"$input.params(\"id\")\"\n }\n }\n}"},"type":"aws"}},"options":{"produces":["application/json"],"responses":{"200":{"description":"200 response","schema":{"$ref":"#/definitions/Empty"},"headers":{"Access-Control-Allow-Origin":{"type":"string"},"Access-Control-Allow-Methods":{"type":"string"},"Access-Control-Allow-Headers":{"type":"string"}}}},"x-amazon-apigateway-integration":{"credentials":{"Fn::GetAtt":["GatefoldAPIRole","Arn"]},"uri":"arn:aws:apigateway:eu-west-1:dynamodb:action/GetItem","responses":{"default":{"statusCode":"200"}},"passthroughBehavior":"never","httpMethod":"POST","type":"aws"}}}},"securityDefinitions":{"auth0":{"type":"apiKey","name":"Authorization","in":"header","x-amazon-apigateway-authtype":"custom","x-amazon-apigateway-authorizer":{"authorizerUri":"arn:aws:apigateway:eu-west-1:lambda:path/2015-03-31/functions/arn:aws:lambda:eu-west-1:601343171996:function:Auth0Authorizer:GenericV2Only/invocations","authorizerResultTtlInSeconds":60,"type":"token"}}},"definitions":{"Empty":{"type":"object","title":"Empty Schema"}}},"Description":"The most compact URL shortener. Developed at Cimpress.","Name":"Gatefold"}},"GatefoldDDBTable":{"Type":"AWS::DynamoDB::Table","Properties":{"KeySchema":[{"AttributeName":"ShortUrl","KeyType":"HASH"}],"ProvisionedThroughput":{"ReadCapacityUnits":1,"WriteCapacityUnits":1},"TableName":"gatefold"}},"GatefoldAPIDDBRole":{"Type":"AWS::IAM::Role","Properties":{"AssumeRolePolicyDocument":{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":["apigateway.amazonaws.com"]},"Action":"sts:AssumeRole"}]},"Policies":[{"PolicyName":"GatefoldAPIDDBPermission","PolicyDocument":{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["dynamodb:GetItem","dynamodb:PutItem"],"Resource":{"Fn::GetAtt":["GatefoldDDBTable","Arn"]}}]}}],"RoleName":"GatefoldAPIDDBRole"}}}}
79 changes: 79 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"use strict";

const fs = require("fs");

const dfsScrubAws = obj => {
Object.keys(obj).map(k => {
if (k.startsWith("x-amazon")) {
delete obj[k];
return;
}

if (typeof obj[k] === "object") {
dfsScrubAws(obj[k])
}
});
};

class Gatefold {
constructor(swaggerPath, cloudformationPath) {
this.swag = fs.readFileSync(swaggerPath).toString();
this.cl = fs.readFileSync(cloudformationPath).toString();
}

build(scrubAws, domain, ttl) {
return this.buildCloudformationTemplate(this.buildSwagger(scrubAws, domain, ttl), domain);
}

buildSwagger(scrubAws, domain, ttl) {
const replacements = {
"GATEFOLD_DOMAIN": domain,
"GATEFOLD_TTL": ttl
};

let substituted = this.swag;
Object.keys(replacements).map(r => {
substituted = substituted.replace(new RegExp(`\\$${r}`, "g"), () => replacements[r]);
});

let output;
try {
output = JSON.parse(substituted);
} catch(err) {
throw new Error("There were errors in the Swagger API definition after building it.");
}

if (scrubAws) {
dfsScrubAws(output);
}

return output;
}

buildCloudformationTemplate(swagger, domain) {
if (typeof swagger === "object") {
swagger = JSON.stringify(swagger);
}

const replacements = {
"GATEFOLD_API": swagger,
"GATEFOLD_DOMAIN": domain
};

let substituted = this.cl;
Object.keys(replacements).map(r => {
substituted = substituted.replace(new RegExp(`\\$${r}`, "g"), () => replacements[r]);
});

let output;
try {
output = JSON.parse(substituted);
} catch(err) {
throw new Error("There were errors in the CloudFormation template after building it.");
}

return output;
}
}

module.exports = { Gatefold };
Loading

0 comments on commit df7a532

Please sign in to comment.