├── .eslintrc ├── .gitignore ├── .npmignore ├── LICENSE ├── README.md ├── __tests__ ├── custom-domain.js ├── remove-mapping.js ├── serverless.yml └── utils.js ├── custom-domain.js ├── lib ├── custom-resource.js ├── remove-mapping.js └── utils.js ├── package-lock.json └── package.json /.eslintrc: -------------------------------------------------------------------------------- 1 | root: true 2 | 3 | env: 4 | node: true 5 | es6: true 6 | 7 | extends: 8 | "eslint:recommended" 9 | 10 | ecmaFeatures: 11 | generators: true 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | coverage 2 | .nyc_output 3 | node_modules 4 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .nyc_output 2 | coverage 3 | __tests__ 4 | .eslintrc 5 | .gitignore 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2017 Doug Moscrop 4 | 5 | The following license applies to all parts of this software except as 6 | documented below: 7 | 8 | ==== 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | 28 | ==== 29 | 30 | All files located in the node_modules and external directories are 31 | externally maintained libraries used by this software which have their 32 | own licenses; we recommend you read them, as their terms may differ from 33 | the terms above. 34 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # serverless-plugin-custom-domain 2 | 3 | This is a plugin for Serverless that injects a [CloudFormation Custom Resource](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) in your deployed stack that sets up a base path mapping between the `ApiGateway::Deployment` that Serverless creates, and an [API Gateway Custom Domain](http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-custom-domains.html). 4 | 5 | ## 4.0.0 6 | 7 | This version uses a newer version of add-custom-resource which requires a newer Node.js runtime. 8 | 9 | ## 3.0.0 10 | 11 | This release brings in a new version of add-custom-resource that updates the runtime version of Lambda. This means your custom resources may re-execute, and should be idempotent. No actual changes in this library have been made, but this is just to be cautious. 12 | 13 | ## Upgrading from 1.x 14 | 15 | A bug in 1.x caused an extra, unused LogGroup to be created, called `/aws/lambdaservice-stage-CustomBasePathMa--` instead of `/aws/lambda/service-stage-CustomBasePathMa--`. However, AWS automatically creates a LogGroup for your functions with the correct name. This means that any deployments using 1.x have two LogGroups. After upgrading to 2.x+, deployments *may* fail due to a CloudFormation error that "the log group already exists". Sorry about this! It doesn't always happen, but thankfully, the fix is pretty straightforward if it does and it should only happen the one time. 16 | 17 | - **delete** the log group (it's the 'correctly' named one, e.g. `/aws/lambda/service-stage-CustomBasePathMa--`) 18 | - redeploy! 19 | - feel free to delete the other, incorrectly named log group, it was never used too 20 | 21 | ## Usage 22 | 23 | ```yaml 24 | 25 | service: my-service 26 | 27 | plugins: 28 | - serverless-plugin-custom-domain 29 | 30 | custom: 31 | domain: "${opt:region}.myservice.foo.com" 32 | ``` 33 | 34 | ## Advanced Usage 35 | 36 | `custom.domain` can also be an object, with the following propeties: 37 | 38 | - `name`: the domain name, same as the above string e.g. `${opt:region}.myservice.foo.com` 39 | - `basePath:` a custom base path, instead of the default `(none)` - a base path is a prefix e.g. `/v1` 40 | 41 | ## Notes 42 | 43 | ### Why a Custom Resource? 44 | 45 | CloudFormation supports `ApiGateway::BasePathMapping` resources but I found they frequently fail to update correctly. Implementing the (relatively simple) logic to get-and-update-or-create combined with a `remove` hook for cleanup has proven to be more reliable. 46 | 47 | ### Setting up the Custom Domain 48 | 49 | These take a long time to provision and are long-lived persistent resources that have Route53 entires pointing at them as well as ACM certificates that have to be requested and approved. You should manage these outside of Serverless, either via CloudFormation or something like Terraform. 50 | -------------------------------------------------------------------------------- /__tests__/custom-domain.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const test = require('ava'); 4 | const sinon = require('sinon'); 5 | 6 | const Plugin = require('..'); 7 | 8 | test.beforeEach(t => { 9 | t.context.template = { 10 | Resources: {} 11 | }; 12 | t.context.serverless = { 13 | version: '1.13.2', 14 | getProvider: () => null, 15 | service: { 16 | provider: { 17 | compiledCloudFormationTemplate: t.context.template 18 | }, 19 | custom: { 20 | domain: 'foo.com' 21 | } 22 | } 23 | }; 24 | t.context.plugin = new Plugin(t.context.serverless, { 25 | stage: 'test' 26 | }); 27 | }); 28 | 29 | test('custom-domain adds hooks', t => { 30 | t.deepEqual(Object.keys(t.context.plugin.hooks), [ 31 | 'before:aws:package:finalize:mergeCustomProviderResources', 32 | 'before:remove:remove', 33 | ]); 34 | }); 35 | 36 | test('throws if unable to find domain name', t => { 37 | t.context.plugin.serverless.service.custom.domain = {}; 38 | t.throws(() => { 39 | t.context.plugin.beforePackage(); 40 | }); 41 | }) 42 | 43 | test('throws if unable to find ApiGatewayDeployment', t => { 44 | t.context.plugin.serverless.service.custom.domain = 'foo.com'; 45 | 46 | t.throws(() => { 47 | t.context.plugin.beforePackage(); 48 | }); 49 | }); 50 | 51 | test('throws if serverless is wrong versino', t => { 52 | const e = t.throws(() => { 53 | t.context.plugin = new Plugin({ 54 | version: '1.10.0' 55 | }); 56 | }); 57 | 58 | t.true(e.message.indexOf('requires serverless') !== -1); 59 | }); 60 | 61 | test('remove does nothing if no domain set up', t => { 62 | t.context.plugin.serverless.service.custom.domain = null; 63 | const stub = sinon.stub(t.context.plugin, 'removeMapping'); 64 | 65 | t.context.plugin.beforeRemove(); 66 | t.false(stub.called); 67 | }); 68 | 69 | test('remove calls when configured', t => { 70 | t.context.plugin.serverless.service.custom.domain = 'foo.com'; 71 | 72 | const removeMapping = sinon.stub(t.context.plugin, 'removeMapping'); 73 | 74 | sinon.stub(t.context.plugin, 'getDomainName').returns('foo.com'); 75 | sinon.stub(t.context.plugin, 'getBasePath').returns('banana'); 76 | 77 | t.context.plugin.beforeRemove(); 78 | 79 | t.true(removeMapping.calledWith('banana', 'foo.com')); 80 | }); 81 | -------------------------------------------------------------------------------- /__tests__/remove-mapping.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const test = require('ava'); 4 | const sinon = require('sinon'); 5 | 6 | const Plugin = require('..'); 7 | 8 | test.beforeEach(t => { 9 | t.context.provider = { 10 | request: Function.prototype 11 | }; 12 | t.context.serverless = { 13 | version: '1.13.2', 14 | getProvider: () => t.context.provider, 15 | service: { 16 | provider: { 17 | compiledCloudFormationTemplate: t.context.template 18 | } 19 | } 20 | }; 21 | t.context.plugin = new Plugin(t.context.serverless, { 22 | stage: 'test' 23 | }); 24 | t.context.plugin.log = sinon.spy(); 25 | }); 26 | 27 | test('removeMapping calls remove', t => { 28 | const mock = sinon.mock(t.context.provider) 29 | 30 | mock.expects('request').returns(Promise.resolve()); 31 | 32 | return t.context.plugin.removeMapping('(none)', 'foo.com') 33 | .then(() => { 34 | mock.verify(); 35 | t.true(t.context.plugin.log.calledOnce); 36 | }); 37 | }); 38 | -------------------------------------------------------------------------------- /__tests__/serverless.yml: -------------------------------------------------------------------------------- 1 | service: groups-admn-bff 2 | 3 | provider: 4 | name: aws 5 | runtime: nodejs8.10 6 | region: ${opt:region} 7 | stage: ${opt:stage} 8 | profile: groups-admn-bff-${opt:stage} 9 | iamRoleStatements: ${file(./serverless/iamRoleStatements.yml)} 10 | 11 | plugins: 12 | - serverless-plugin-include-dependencies 13 | - serverless-plugin-common-excludes 14 | - serverless-plugin-custom-domain 15 | - serverless-plugin-aws-alerts 16 | - serverless-plugin-log-subscription 17 | - serverless-plugin-tracing 18 | - serverless-prune-plugin 19 | 20 | package: 21 | exclude: 22 | - terraform/** 23 | - serverless/** 24 | 25 | custom: 26 | alerts: ${file(./serverless/alerts.yml)} 27 | config: ${file(./serverless/config/${opt:stage}-${opt:region}.yml)} 28 | domain: ${self:custom.config.domain} 29 | logSubscription: ${self:custom.config.logSubscription} 30 | prune: 31 | automatic: true 32 | number: 3 33 | 34 | functions: 35 | app: 36 | handler: src/app/index.handler 37 | memorySize: 1024 38 | timeout: 30 39 | environment: ${self:custom.config.env} 40 | events: 41 | - http: ANY / 42 | - http: 43 | method: ANY 44 | path: /{any+} 45 | cors: 46 | origins: 47 | - '*' 48 | headers: 49 | - Content-Type 50 | - X-Amz-Date 51 | - Authorization 52 | - X-Api-Key 53 | - X-Amz-Security-Token 54 | - X-Amz-User-Agent 55 | - X-Request-Id 56 | allowCredentials: true 57 | -------------------------------------------------------------------------------- /__tests__/utils.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const test = require('ava'); 4 | 5 | const Plugin = require('..'); 6 | 7 | test.beforeEach(t => { 8 | t.context.template = { 9 | Resources: {} 10 | }; 11 | t.context.resources = { 12 | Resources: {} 13 | }; 14 | t.context.serverless = { 15 | version: '1.13.2', 16 | getProvider: () => null, 17 | service: { 18 | provider: { 19 | compiledCloudFormationTemplate: t.context.template 20 | }, 21 | resources: t.context.resources 22 | } 23 | }; 24 | t.context.plugin = new Plugin(t.context.serverless, { 25 | stage: 'test' 26 | }); 27 | }); 28 | 29 | test('finds deployment id', t => { 30 | const id = 'ApiGatewayDeployment12345'; 31 | 32 | t.context.template.Resources[id] = { 33 | Type: 'AWS::ApiGateway::Deployment', 34 | }; 35 | 36 | t.true(id === t.context.plugin.getApiGatewayDeploymentId()); 37 | }); 38 | 39 | test('finds stage name from deployment', t => { 40 | const expected = { 41 | name: 'dev' 42 | }; 43 | 44 | t.context.template.Resources['ApiGatewayDeployment12345'] = { 45 | Type: 'AWS::ApiGateway::Deployment', 46 | Properties: { 47 | StageName: 'dev' 48 | } 49 | }; 50 | 51 | const actual = t.context.plugin.getApiGatewayStage('ApiGatewayDeployment12345'); 52 | t.deepEqual(expected, actual); 53 | }); 54 | 55 | test('finds stage name from stage', t => { 56 | const expected = { 57 | name: 'foo_dev', 58 | id: 'ApiGatewayStage' 59 | }; 60 | 61 | t.context.template.Resources['ApiGatewayDeployment12345'] = { 62 | Type: 'AWS::ApiGateway::Deployment', 63 | Properties: { 64 | StageName: 'dev' 65 | } 66 | }; 67 | 68 | t.context.resources.Resources['ApiGatewayStage'] = { 69 | Type: 'AWS::ApiGateway::Stage', 70 | Properties: { 71 | StageName: 'foo_dev', 72 | DeploymentId: { 73 | Ref: 'ApiGatewayDeployment12345' 74 | } 75 | } 76 | }; 77 | 78 | const actual = t.context.plugin.getApiGatewayStage('ApiGatewayDeployment12345'); 79 | t.deepEqual(expected, actual); 80 | }); 81 | 82 | test('getDomainName string', t => { 83 | t.true('foo' === t.context.plugin.getDomainName('foo')); 84 | }); 85 | 86 | test('getDomainName object', t => { 87 | t.true('bar' === t.context.plugin.getDomainName({ name: 'bar' })); 88 | }); 89 | 90 | test('getBasePath set', t => { 91 | t.true('baz' === t.context.plugin.getBasePath({ basePath: 'baz' })); 92 | }); 93 | 94 | test('getBasePath undefined', t => { 95 | t.true('(none)' === t.context.plugin.getBasePath({})); 96 | }); 97 | 98 | test('getBasePath emptry string', t => { 99 | t.true('(none)' === t.context.plugin.getBasePath({ basePath: '' })); 100 | }); 101 | -------------------------------------------------------------------------------- /custom-domain.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const addCustomResource = require('add-custom-resource'); 4 | const path = require('path'); 5 | const semver = require('semver'); 6 | 7 | const removeMapping = require('./lib/remove-mapping'); 8 | const utils = require('./lib/utils'); 9 | 10 | module.exports = class CustomDomain { 11 | 12 | constructor(serverless, options) { 13 | if (!semver.satisfies(serverless.version, '>= 1.13')) { 14 | throw new Error('serverless-plugin-custom-domain requires serverless 1.13 or higher!'); 15 | } 16 | 17 | this.serverless = serverless; 18 | this.options = options; 19 | this.provider = this.serverless.getProvider('aws'); 20 | 21 | Object.assign(this, 22 | { addCustomResource }, 23 | { removeMapping }, 24 | utils 25 | ); 26 | 27 | this.hooks = { 28 | 'before:aws:package:finalize:mergeCustomProviderResources': this.beforePackage.bind(this), 29 | 'before:remove:remove': this.beforeRemove.bind(this), 30 | }; 31 | } 32 | 33 | beforePackage() { 34 | const domain = this.serverless.service.custom.domain; 35 | const template = this.serverless.service.provider.compiledCloudFormationTemplate; 36 | 37 | if (domain) { 38 | const domainName = this.getDomainName(domain); 39 | const basePath = this.getBasePath(domain); 40 | const deploymentId = this.getApiGatewayDeploymentId(); 41 | 42 | console.log('deployent', deploymentId); 43 | if (deploymentId) { 44 | const stage = this.getApiGatewayStage(deploymentId); 45 | const dependencies = ['ApiGatewayRestApi', deploymentId]; 46 | 47 | console.log('stage', stage); 48 | if (stage.id) { 49 | dependencies.push(stage.id); 50 | } 51 | 52 | return addCustomResource(template, { 53 | name: 'ApiGatewayBasePathMapping', 54 | sourceCodePath: path.join(__dirname, 'lib/custom-resource.js'), 55 | resource: { 56 | properties: { 57 | DomainName: domainName, 58 | BasePath: basePath, 59 | Stage: stage.name, 60 | RestApi: { 61 | Ref: 'ApiGatewayRestApi' 62 | } 63 | }, 64 | dependencies 65 | }, 66 | role: { 67 | policies: [{ 68 | PolicyName: 'apigateway-permissions', 69 | PolicyDocument: { 70 | Version: '2012-10-17', 71 | Statement: [{ 72 | Effect: 'Allow', 73 | Action: ['apigateway:*'], 74 | Resource: 'arn:aws:apigateway:*:*:*' 75 | }] 76 | } 77 | }] 78 | } 79 | }); 80 | } else { 81 | throw new Error('Could not find AWS::ApiGateway::Deployment resource in CloudFormation template!'); 82 | } 83 | } 84 | } 85 | 86 | beforeRemove() { 87 | const domain = this.serverless.service.custom.domain; 88 | 89 | if (domain) { 90 | const domainName = this.getDomainName(domain); 91 | const basePath = this.getBasePath(domain); 92 | 93 | return this.removeMapping(basePath, domainName); 94 | } 95 | } 96 | 97 | }; 98 | -------------------------------------------------------------------------------- /lib/custom-resource.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const aws = require('aws-sdk'); 4 | const response = require('cfn-response'); 5 | 6 | module.exports.handler = function(event, context) { 7 | Promise.resolve() 8 | .then(() => { 9 | const apiGateway = new aws.APIGateway(); 10 | 11 | const basePath = event.ResourceProperties.BasePath; 12 | const domainName = event.ResourceProperties.DomainName; 13 | const restApiId = event.ResourceProperties.RestApi; 14 | const stage = event.ResourceProperties.Stage; 15 | 16 | switch (event.RequestType) { 17 | case 'Create': 18 | case 'Update': 19 | return apiGateway.getBasePathMapping({ 20 | basePath, 21 | domainName 22 | }) 23 | .promise() 24 | .then(() => { 25 | return apiGateway.updateBasePathMapping({ 26 | basePath, 27 | domainName, 28 | patchOperations: [{ 29 | op: 'replace', 30 | path: '/restapiId', 31 | value: restApiId 32 | }, { 33 | op: 'replace', 34 | path: '/stage', 35 | value: stage 36 | }] 37 | }) 38 | .promise() 39 | .then(() => 'updated') 40 | }) 41 | .catch(e => { 42 | if (e.statusCode === 404 || e.code === 'NotFoundException') { 43 | return apiGateway.createBasePathMapping({ 44 | basePath, 45 | domainName, 46 | restApiId, 47 | stage 48 | }) 49 | .promise() 50 | .then(() => 'created'); 51 | } 52 | throw e; 53 | }); 54 | default: 55 | return Promise.resolve('no action matched') 56 | } 57 | }) 58 | .then((msg) => { 59 | /* eslint-disable no-console */ 60 | console.log('completed: ', msg); 61 | response.send(event, context, response.SUCCESS, {}); 62 | }) 63 | .catch(e => { 64 | /* eslint-disable no-console */ 65 | console.log(e); 66 | response.send(event, context, response.FAILED, {}); 67 | }); 68 | }; 69 | -------------------------------------------------------------------------------- /lib/remove-mapping.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = function removeMapping(basePath, domainName) { 4 | return this.provider.request('APIGateway', 'deleteBasePathMapping', { 5 | basePath, 6 | domainName 7 | }) 8 | .then(null, e => { 9 | if (e.statusCode === 404 || e.code === 'NotFoundException') { 10 | return Promise.resolve(); 11 | } 12 | throw e; 13 | }) 14 | .then(() => { 15 | this.log('Cleaned up BasePathMapping'); 16 | }); 17 | }; 18 | -------------------------------------------------------------------------------- /lib/utils.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = { 4 | 5 | getApiGatewayDeploymentId() { 6 | const template = this.serverless.service.provider.compiledCloudFormationTemplate; 7 | 8 | return Object.keys(template.Resources).find(id => { 9 | return template.Resources[id].Type === 'AWS::ApiGateway::Deployment'; 10 | }); 11 | }, 12 | 13 | getApiGatewayStage(deploymentId) { 14 | const service = this.serverless.service; 15 | const resources = service.resources; 16 | const template = service.provider.compiledCloudFormationTemplate; 17 | const deployment = template.Resources[deploymentId]; 18 | 19 | const stage = { 20 | name: deployment.Properties.StageName 21 | }; 22 | 23 | if (resources && resources.Resources) { 24 | Object.keys(resources.Resources).forEach(key => { 25 | const resource = resources.Resources[key]; 26 | 27 | if (resource.Type === 'AWS::ApiGateway::Stage') { 28 | if (resource.Properties.DeploymentId.Ref === deploymentId) { 29 | stage.name = resource.Properties.StageName; 30 | stage.id = key; 31 | } 32 | } 33 | }); 34 | } 35 | 36 | return stage; 37 | }, 38 | 39 | log(msg) { 40 | this.serverless.cli.log(`[serverless-plugin-custom-domain]: ${msg}`); 41 | }, 42 | 43 | getDomainName(domain) { 44 | if (typeof domain === 'string') { 45 | return domain; 46 | } else if (domain && domain.name && typeof domain.name === 'string') { 47 | return domain.name 48 | } 49 | 50 | throw new Error('custom.domain must either be a string or an object with a name property'); 51 | }, 52 | 53 | getBasePath(domain) { 54 | if (domain && domain.basePath && typeof domain.basePath === 'string') { 55 | return domain.basePath; 56 | } 57 | 58 | return '(none)'; 59 | } 60 | 61 | }; 62 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "serverless-plugin-custom-domain", 3 | "version": "4.0.0", 4 | "description": "Set up and cut over custom domains for API Gateway", 5 | "main": "custom-domain.js", 6 | "scripts": { 7 | "test": "nyc --all ava" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/dougmoscrop/serverless-plugin-custom-domain.git" 12 | }, 13 | "keywords": [ 14 | "serverless", 15 | "plugin", 16 | "api-gateway" 17 | ], 18 | "author": "Doug Moscrop ", 19 | "license": "MIT", 20 | "bugs": { 21 | "url": "https://github.com/dougmoscrop/serverless-plugin-custom-domain/issues" 22 | }, 23 | "homepage": "https://github.com/dougmoscrop/serverless-plugin-custom-domain#readme", 24 | "devDependencies": { 25 | "ava": "^5.1.0", 26 | "eslint": "^8.29.0", 27 | "nyc": "^15.0.0", 28 | "sinon": "^15.0.0" 29 | }, 30 | "dependencies": { 31 | "add-custom-resource": "^5.0.0", 32 | "semver": "^7.1.1" 33 | } 34 | } 35 | --------------------------------------------------------------------------------