Serverless or Bust, Part 2: Handling Events and Securing Lambdas

  • How Serverless manages our services
  • How AWS Lambdas receive parameters, path variables, and query strings
  • How to secure Lambdas from unauthorized use
  • How to get something done within the Lambda

Serverless manages boilerplate and build chores

  • executes a Webpack build to compile our TypeScript into JavaScript
  • assembles a CloudFormation template and the compiled JavaScript code into the deployment’s zipfile
  • uploads the zipfile to an S3 bucket
  • and calls CloudFormation to deploy the AWS stack

Lambdas and the Internet

functions:
shout:
handler: handler.shout
events:
# Installs the HTTP Proxy route to our method
# in API Gateway. A GET of /shout will result
# in a call to handler.shout
- http:
method: get
path: shout

Serverless-generated CloudFormation Templates

.serverless
├── cloudformation-template-create-stack.json
├── cloudformation-template-update-stack.json
├── serverless-state.json
└── shout-it.zip
  • A CloudFormation Stack, named based on the project name plus the stack name (such as shout-it-dev)
  • An AWS S3 Bucket to hold the Stack configuration, along with an S3 Bucket policy to deny any user-based access to the files (since CloudFormation is managing them)
  • A CloudWatch Logs log group for the Lambda at /aws/lambda/shout-it-dev-shout
  • An IAM Role, shared by default for all Lambdas in this project, that allows the Lambda to create the log group and write log events to the stream
  • A deployment script to publish the Lambda function using the standard AWS::Lambda::Function template, along with the location of a pre-configured zipfile (also in the .serverless directory) to upload to the S3 bucket when publishing the Lambda
  • A Lambda version policy which requests to retain prior versions of the Lambda when deploying new ones
  • An AWS API Gateway service to expose our service to the Internet
  • An URI for the /shout path in the API Gateway
  • Proper configuration to point the route to the Lambda
service:
name: shout-it

custom:
webpack:
webpackConfig: ./webpack.config.js
includeModules: true

plugins:
- serverless-webpack

provider:
name: aws
runtime: nodejs12.x
apiGateway:
# Enable gzip compression for responses > 1 KB
minimumCompressionSize: 1024
environment:
AWS_NODEJS_CONNECTION_REUSE_ENABLED: 1

functions:
shout:
handler: handler.shout
events:
- http:
method: get
path: shout

The Lambda Event object

$ curl -X https://.../dev/shout
"resource": "/shout",
"path": "/shout",
"httpMethod": "GET",
"headers": {
"Accept": "text/html,...",
"Accept-Encoding": "gzip, deflate, br",
... many other HTTP headers
},
"multiValueHeaders": {
"Accept": [
"text/html..."
],
... many other multi-value HTTP headers ...
},
"queryStringParameters": null,
"multiValueQueryStringParameters": null,
"pathParameters": null,
"requestContext": {
... lots of info here ...
},
"body": null,
...
}
  • HTTP headers
  • the request body (which is currently null since we aren’t passing anything in)
  • query string and path parameters

Processing Query Strings

curl -X https://.../dev/shout?a=1&b=2&b=3
"queryStringParameters": {
"a": "1",
"b": "2,3"
},
"multiValueQueryStringParameters": {
"a": [
"1"
],
"b": [
"2",
"3"
]
},
...

Processing Path Variables

functions:
shout:
handler: handler.shout
events:
- http:
method: get
path: shout/{key}
export const shout: APIGatewayProxyHandler = 
async (event, context) => {
let message: string;

switch (event.pathParameters.key) {
case 'shk':
message = 'AAAAHH SHARK!';
break;
case 'py':
message = 'AAAAHH PYTHON!';
break;
default:
message = 'AAAAHH LAZY!';
}

return {
statusCode: 200,
body: JSON.stringify({
message: `AAAAHHH ${message}`
})
};
};
CURL -X GET \
https://.../dev/shout/py
{"message":"AAAAHHH AAAAHH PYTHON!"}

Managing responses

Securing Lambdas with IAM

  • Users – These are users who sign in to the AWS Console, or access AWS via the Amazon AWS Command-Line Interface. Console users can be secured with two-factor authentication, whereas CLI users are enabled via assigning a secret and access key pair.
  • Groups – Users can be assembled into Groups for management purposes.
  • Roles – Logical names to attach a series of rights via polices (see below)
  • Permissions – A right to execute a specific action or gain access to a specific resource or resources
  • Policies – Policies attach permissions to Roles
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"logs:CreateLogStream",
"logs:CreateLogGroup"
],
"Resource": [
"arn:aws:logs:us-east-1:xxxxxxxxxxx:log-group:/aws/lambda/shout-it-dev*:*"
],
"Effect": "Allow"
},
{
"Action": [
"logs:PutLogEvents"
],
"Resource": [
"arn:aws:logs:us-east-1:xxxxxxxxxxx:log-group:/aws/lambda/shout-it-dev*:*:*"
],
"Effect": "Allow"
}
]
}

Requiring authentication

functions:
shout:
handler: handler.shout
events:
- http:
method: get
path: shout/{key}
cors: true
authorizer: aws_iam

How to Test our API with Postman

Serverless versus AWS Serverless Application Model

What’s next? Building a client and configuring AWS Cognito for web security

Chariot Solutions is a top IT consulting firm specializing in software and mobile development, and development in the cloud. Visit us at chariotsolutions.com.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Languages for the win — Part 1!

Setting up Scalr with Azure DevOps — Add Azure credentials

Docker Automation using Ansible

A Step-by-Step Guide to Train a Model on Google Cloud’s Vertex AI

Vertex AI logo

A Step by Step Guide to Talking Through Your Code

Future is Declarative (Part 1)

Setup PostgreSQL + pgAdmin + PostGraphile in Docker

How to Print Text in Color Using Python

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Chariot Solutions

Chariot Solutions

Chariot Solutions is a top IT consulting firm specializing in software and mobile development, and development in the cloud. Visit us at chariotsolutions.com.

More from Medium

Node-Canvas in AWS Lambda

Serverless — What? Why? How?

A quick look at serverless systems: AWS Lambda

Testing with DynamoDB Toolbox