├── .eslintignore ├── .eslintrc.js ├── .gitignore ├── README.md ├── auth.js ├── lib └── secrets.js ├── package-lock.json ├── package.json └── serverless.yml /.eslintignore: -------------------------------------------------------------------------------- 1 | coverage/* 2 | .serverless/* 3 | .nyc_output/* 4 | note_modules/* 5 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | "extends": ["airbnb-base"], 3 | "plugins": [ 4 | "mocha" 5 | ], 6 | "rules": { 7 | "mocha/no-exclusive-tests": "error" 8 | } 9 | }; -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # package directories 2 | node_modules 3 | jspm_packages 4 | 5 | # Serverless directories 6 | .serverless 7 | .nyc_output 8 | .vscode -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # netlify-serverless-oauth2-backend 2 | 3 | This is an AWS Lambda based service to help perform authentication to Github via an OAuth2 authentication process. 4 | 5 | 6 | ## Installation 7 | 8 | ``` 9 | sudo npm -i serverless -g 10 | npm i 11 | ``` 12 | 13 | ## Configuration 14 | 15 | This code can be run either locally (using the serverless-offline plugin) or deployed in AWS. 16 | 17 | ### Offline 18 | 19 | To run it locally: 20 | 21 | ``` 22 | sls offline 23 | ``` 24 | 25 | Before running it, update auth.js to reflect your desired configuration. The settings are defined in the initialization of the Secrets class: 26 | 27 | ``` 28 | // Change this stuff in auth.js to reflect your own dev testing 29 | const secrets = new Secrets({ 30 | GIT_HOSTNAME: 'https://github.com', 31 | OAUTH_TOKEN_PATH: '/login/oauth/access_token', 32 | OAUTH_AUTHORIZE_PATH: '/login/oauth/authorize', 33 | OAUTH_CLIENT_ID: 'foo', 34 | OAUTH_CLIENT_SECRET: 'bar', 35 | REDIRECT_URL: 'http://localhost:3000/callback', 36 | OAUTH_SCOPES: 'repo,user', 37 | }); 38 | ``` 39 | 40 | For this to work you'll also need to have your OAuth2 app setup properly in Github (and redirecting to the same callback url). 41 | 42 | ### AWS Deployment 43 | 44 | To deploy the Lambda function, you'll need to update serverless.yml and set your KMS key for the parameter store. 45 | 46 | To grab the key id: 47 | 48 | ``` 49 | aws kms describe-key --key-id alias/aws/ssm --profile --region 50 | ``` 51 | 52 | ex: 53 | 54 | ``` 55 | aws kms describe-key --key-id alias/aws/ssm --profile ctrl-alt-del --region us-east-1 56 | ``` 57 | 58 | If you're unfamiliar with AWS profiles, see this documentation: https://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html 59 | 60 | Once you've added your key uuid to the serverless.yml configuration (mapping it to the correct region and stage), it's time to deploy the code. 61 | 62 | ``` 63 | sls deploy -s --aws-profile --region 64 | ``` 65 | 66 | Ex: 67 | 68 | ``` 69 | sls deploy -s prod --aws-profile ctrl-alt-del --region us-east-1 70 | ``` 71 | 72 | Finally, once the code is deployed you need to add some parameters to the AWS parameter store. 73 | 74 | Head on over to the AWS console, find the Systems manager, and go to the Parameter store. 75 | 76 | In there, you'll want to create the following parameters/values (as SecureStrings), making sure to replace `STAGE` with your stage (eg: prod): 77 | 78 | * /ctrl-alt-del/oauth/`STAGE`/GIT_HOSTNAME - The github host to use. Ex: https://github.com 79 | * /ctrl-alt-del/oauth/`STAGE`/OAUTH_TOKEN_PATH - The token api uri path. Most probably this: /login/oauth/access_token 80 | * /ctrl-alt-del/oauth/`STAGE`/OAUTH_AUTHORIZE_PATH - The authorize api uri path. Most probably this: /login/oauth/authorize 81 | * /ctrl-alt-del/oauth/`STAGE`/OAUTH_CLIENT_ID - Your Github OAuth client id 82 | * /ctrl-alt-del/oauth/`STAGE`/OAUTH_CLIENT_SECRET - Your Github OAuth client secret 83 | * /ctrl-alt-del/oauth/`STAGE`/REDIRECT_URL - Your callback URL. It will look something like this: https://`RANDOMSTUFF`.execute-api.us-east-1.amazonaws.com/`STAGE`/callback 84 | * /ctrl-alt-del/oauth/`STAGE`/OAUTH_SCOPES - The scopes to grant. Probably this: repo,user 85 | 86 | -------------------------------------------------------------------------------- /auth.js: -------------------------------------------------------------------------------- 1 | const simpleOauthModule = require('simple-oauth2'); 2 | const randomstring = require('randomstring'); 3 | const Secrets = require('./lib/secrets'); 4 | 5 | const secrets = new Secrets({ 6 | GIT_HOSTNAME: 'https://github.com', 7 | OAUTH_TOKEN_PATH: '/login/oauth/access_token', 8 | OAUTH_AUTHORIZE_PATH: '/login/oauth/authorize', 9 | OAUTH_CLIENT_ID: 'foo', 10 | OAUTH_CLIENT_SECRET: 'bar', 11 | REDIRECT_URL: 'http://localhost:3000/callback', 12 | OAUTH_SCOPES: 'repo,user', 13 | }); 14 | 15 | 16 | function getScript(mess, content) { 17 | return ``; 32 | } 33 | 34 | module.exports.auth = (e, ctx, cb) => secrets.init() 35 | .then(() => { 36 | const oauth2 = simpleOauthModule.create({ 37 | client: { 38 | id: secrets.OAUTH_CLIENT_ID, 39 | secret: secrets.OAUTH_CLIENT_SECRET, 40 | }, 41 | auth: { 42 | tokenHost: secrets.GIT_HOSTNAME, 43 | tokenPath: secrets.OAUTH_TOKEN_PATH, 44 | authorizePath: secrets.OAUTH_AUTHORIZE_PATH, 45 | }, 46 | }); 47 | 48 | // Authorization uri definition 49 | const authorizationUri = oauth2.authorizationCode.authorizeURL({ 50 | redirect_uri: secrets.REDIRECT_URL, 51 | scope: secrets.OAUTH_SCOPES, 52 | state: randomstring.generate(32), 53 | }); 54 | 55 | cb(null, { 56 | statusCode: 302, 57 | headers: { 58 | Location: authorizationUri, 59 | }, 60 | }); 61 | }); 62 | 63 | module.exports.callback = (e, ctx, cb) => { 64 | let oauth2; 65 | secrets.init() 66 | .then(() => { 67 | oauth2 = simpleOauthModule.create({ 68 | client: { 69 | id: secrets.OAUTH_CLIENT_ID, 70 | secret: secrets.OAUTH_CLIENT_SECRET, 71 | }, 72 | auth: { 73 | tokenHost: secrets.GIT_HOSTNAME, 74 | tokenPath: secrets.OAUTH_TOKEN_PATH, 75 | authorizePath: secrets.OAUTH_AUTHORIZE_PATH, 76 | }, 77 | }); 78 | 79 | const options = { 80 | code: e.queryStringParameters.code, 81 | }; 82 | return oauth2.authorizationCode.getToken(options); 83 | }) 84 | .then((result) => { 85 | const token = oauth2.accessToken.create(result); 86 | cb( 87 | null, 88 | { 89 | statusCode: 200, 90 | headers: { 91 | 'Content-Type': 'text/html', 92 | }, 93 | body: getScript('success', { 94 | token: token.token.access_token, 95 | provider: 'github', 96 | }), 97 | }, 98 | ); 99 | }) 100 | .catch((err) => { 101 | cb(null, { 102 | statusCode: 200, 103 | headers: { 104 | 'Content-Type': 'text/html', 105 | }, 106 | body: getScript('error', err), 107 | }); 108 | }); 109 | }; 110 | 111 | module.exports.success = (e, ctx, cb) => cb( 112 | null, 113 | { 114 | statusCode: 204, 115 | body: '', 116 | }, 117 | ); 118 | 119 | module.exports.default = (e, ctx, cb) => { 120 | cb(null, { 121 | statusCode: 302, 122 | headers: { 123 | Location: '/auth', 124 | }, 125 | }); 126 | }; 127 | -------------------------------------------------------------------------------- /lib/secrets.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-extraneous-dependencies */ 2 | /* eslint-disable class-methods-use-this */ 3 | const AWS = require('aws-sdk'); 4 | 5 | const MAX_SSM_PARAMETERS_PER_REQUEST = 10; 6 | 7 | class Secrets { 8 | constructor(secretList) { 9 | this.secretList = secretList; 10 | Object.keys(secretList).forEach((secret) => { 11 | this[secret] = secretList[secret]; 12 | }); 13 | } 14 | 15 | flattenParameters(params) { 16 | const flat = {}; 17 | params.forEach((param) => { 18 | flat[param.Name.replace(/^.+\/(.+)$/, '$1')] = param.Value; 19 | }); 20 | return flat; 21 | } 22 | 23 | init() { 24 | if (this.initPromise === undefined) { 25 | this.initPromise = new Promise((resolve, reject) => { 26 | const shouldLoadSecretsFromSsm = !process.env.IS_OFFLINE || process.env.IS_TEST; 27 | if (shouldLoadSecretsFromSsm) { 28 | this.loadSecrets().then(resolve, reject); 29 | } else { 30 | resolve(); 31 | } 32 | }); 33 | } 34 | return this.initPromise; 35 | } 36 | 37 | loadSecrets() { 38 | const ssm = new AWS.SSM(); 39 | const secretNames = Object.keys(this.secretList).map(secret => process.env[secret]); 40 | 41 | // Create an array of promises of SSM getparameters requests. 42 | // Max 10 per call. 43 | const promises = []; 44 | while (secretNames.length > 0) { 45 | const subSet = secretNames.splice(0, MAX_SSM_PARAMETERS_PER_REQUEST); 46 | promises.push(ssm.getParameters({ Names: subSet, WithDecryption: true }).promise()); 47 | } 48 | return Promise.all(promises) 49 | .then((secrets) => { 50 | const settingsArray = []; 51 | secrets.forEach((secretSet) => { 52 | settingsArray.push(...secretSet.Parameters); 53 | }); 54 | const settings = this.flattenParameters(settingsArray); 55 | Object.keys(settings).forEach((setting) => { 56 | this[setting] = settings[setting]; 57 | }); 58 | }); 59 | } 60 | } 61 | 62 | module.exports = Secrets; 63 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "serverless-oauth2", 3 | "version": "1.0.0", 4 | "description": "serverless-oauth2", 5 | "repository": "", 6 | "author": "Mark Steele ", 7 | "license": "MIT", 8 | "private": true, 9 | "dependencies": { 10 | "randomstring": "^1.1.5", 11 | "simple-oauth2": "^1.5.2" 12 | }, 13 | "devDependencies": { 14 | "npm": "^5.7.1", 15 | "aws-sdk": "^2.12.0", 16 | "aws-sdk-mock": "^1.6.1", 17 | "babel-preset-es2015": "^6.24.1", 18 | "chai": "^4.0.2", 19 | "eslint": "^4.17.0", 20 | "eslint-config-airbnb-base": "^12.1.0", 21 | "eslint-plugin-import": "^2.8.0", 22 | "eslint-plugin-mocha": "^4.11.0", 23 | "eslint-plugin-node": "^6.0.0", 24 | "eslint-plugin-promise": "^3.6.0", 25 | "mocha": "^3.2.0", 26 | "nyc": "^11.2.1", 27 | "serverless-offline": "^3.16.0", 28 | "serverless-plugin-optimize": "^1.0.0-rc.15", 29 | "sinon": "^2.1.0" 30 | }, 31 | "scripts": { 32 | "test": "IS_TEST=1 mocha", 33 | "coverage": "IS_TEST=1 nyc --check-coverage --lines 75 --per-file mocha", 34 | "coverage-report": "IS_TEST=1 nyc --check-coverage --report -r html mocha", 35 | "lint": "node node_modules/eslint/bin/eslint.js --color ." 36 | }, 37 | "standard": { 38 | "env": [ 39 | "mocha" 40 | ] 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /serverless.yml: -------------------------------------------------------------------------------- 1 | service: serverless-oauth2 2 | provider: 3 | name: aws 4 | runtime: nodejs14.x 5 | stage: ${opt:stage, self:custom.defaultStage} 6 | environment: 7 | GIT_HOSTNAME: "/ctrl-alt-del/oauth/${opt:stage, self:provider.stage}/GIT_HOSTNAME" 8 | OAUTH_TOKEN_PATH: "/ctrl-alt-del/oauth/${opt:stage, self:provider.stage}/OAUTH_TOKEN_PATH" 9 | OAUTH_AUTHORIZE_PATH: "/ctrl-alt-del/oauth/${opt:stage, self:provider.stage}/OAUTH_AUTHORIZE_PATH" 10 | OAUTH_CLIENT_ID: "/ctrl-alt-del/oauth/${opt:stage, self:provider.stage}/OAUTH_CLIENT_ID" 11 | OAUTH_CLIENT_SECRET: "/ctrl-alt-del/oauth/${opt:stage, self:provider.stage}/OAUTH_CLIENT_SECRET" 12 | REDIRECT_URL: "/ctrl-alt-del/oauth/${opt:stage, self:provider.stage}/REDIRECT_URL" 13 | OAUTH_SCOPES: "/ctrl-alt-del/oauth/${opt:stage, self:provider.stage}/OAUTH_SCOPES" 14 | TZ: "utc" 15 | iamRoleStatements: 16 | - Effect: Allow 17 | Action: 18 | - ssm:DescribeParameters 19 | - ssm:GetParameters 20 | Resource: "arn:aws:ssm:${opt:region, self:provider.region}:*:parameter/ctrl-alt-del/oauth/${opt:stage, self:provider.stage}/*" 21 | - Effect: Allow 22 | Action: 23 | - kms:Decrypt 24 | Resource: "arn:aws:kms:${opt:region, self:provider.region}:*:key/${self:custom.kms_key.${opt:region, self:provider.region}.${self:provider.stage}}" 25 | 26 | custom: 27 | defaultStage: dev 28 | kms_key: 29 | "us-east-1": 30 | prod: "01660d80-64fb-4444-9b21-bb15ac2f97ec" 31 | dev: "foo" 32 | 33 | functions: 34 | auth: 35 | handler: auth.auth 36 | memorySize: 128 37 | timeout: 5 38 | events: 39 | - http: 40 | path: /auth 41 | method: get 42 | cors: true 43 | callback: 44 | handler: auth.callback 45 | memorySize: 128 46 | timeout: 5 47 | events: 48 | - http: 49 | path: /callback 50 | method: get 51 | cors: true 52 | success: 53 | handler: auth.success 54 | memorySize: 128 55 | timeout: 5 56 | events: 57 | - http: 58 | path: /success 59 | method: get 60 | cors: true 61 | default: 62 | handler: auth.default 63 | memorySize: 128 64 | timeout: 5 65 | events: 66 | - http: 67 | path: / 68 | method: get 69 | cors: true 70 | 71 | plugins: 72 | - serverless-plugin-optimize 73 | - serverless-offline 74 | 75 | package: 76 | individually: true 77 | --------------------------------------------------------------------------------