Skip to content

Instantly share code, notes, and snippets.

@crunchie84
Created March 9, 2021 08:14
Show Gist options
  • Save crunchie84/6cf5c5d2fa59dd5f4f3bd62ed6e4512c to your computer and use it in GitHub Desktop.
Save crunchie84/6cf5c5d2fa59dd5f4f3bd62ed6e4512c to your computer and use it in GitHub Desktop.
Middy setup
/**
This middleware verifies that the AWS api gateway authorizer lambda has been configured and executed
this middleware is meant to make sure that the seam between IaC and the implementation do not go out of sync
and for whatever reason this lambda is exposed without authorization logic having happened before
in the lambda authorizer
*/
export function assertAuthorizerExecuted() {
return ({
before: (handler, next) => {
const event = handler.event; //unbox middy
// we only verify that the authorizer is put in place (no configuration failures)
const authorizer = event.requestContext.authorizer;
if (!authorizer) {
throw new Error('Authorizer not configured correctly');
}
next();
}
});
}
/**
* Implementation based on https://github.com/middyjs/middy/blob/master/src/middlewares/httpErrorHandler.js
*
* Business rules:
* - Will always return 500 on errors
* - Will log with users emailaddress if possible
*/
export function errorHandler(opts) {
const defaults = {logger: console.error};
const options = Object.assign({}, defaults, opts);
const logger = typeof options.logger === 'function'
? options.logger
: () => {};//fallback: no-op
return ({
onError: (handler, next) => {
let userEmailAddress = 'unknown';
const authorizer = handler.event.requestContext.authorizer;
if (authorizer && authorizer.email) {
userEmailAddress = authorizer.email;
}
logger(
`Error during handling of request: ${handler.error.message}`,
{ user: userEmailAddress },
handler.error
);
// enrich response with at least the explicit error body + status code
handler.response = Object.assign(
{},
handler.response || {},
{
statusCode: 500,
body: JSON.stringify({ error: true }),
}
);
return next();
}
});
}
// lazy loading of the middy stack so we can inject stubs during testing if needed before the whole middyfy has been wired
export function handler(event, context, callback) {
return middy(myLambdaBusinessLogicHandler)
.use(httpHeaderNormalizer()) // middy default
.use(correlationIds()) //https://www.npmjs.com/package/@dazn/lambda-powertools-correlation-ids
.use(assertAuthorizerExecuted())
.use(jsonBodyParser()) // middy default
.use(errorHandler({logger: Log.error }))(event, context, callback);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment