AWS Lambda Fast API starter application

Overview

AWS Lambda Fast API

Fast API starter application compatible with API Gateway and Lambda Function.

How to deploy it?

Terraform AWS Lambda API is a reusable module that can be used to deploy this Fast Application and It will provision:

  • The AWS Lambda Function resources
  • The AWS Lambda Function CI/CD resources
  • The AWS API Gateway HTTP API resources

Structure

This Fast Application is using Mangum to adapt AWS API Gateway events to ASGI requests.

When creating the Lambda Function, make sure that the handler is set to the Adapter Object which is in our case app.runtime.lambda.main.handler.

Environment variable

  • FIREBASE_APP_API_KEY: Firebase web application API Key.
  • AWS_API_GW_MAPPING_KEY: The mapping key used in AWS API Gateway to map the API with custom domain.
  • RUNTIME: should be LAMBDA when deploying to LAMBDA
  • AWS_API_GW_STAGE_NAME: should be the same as the one used with API Gateway
  • JWT_AUTHORIZATION_GROUPS_ATTR_NAME: the JWT claim attribute name from where to get RBAC roles.

Blueprints

AWS API Gateway sends Requests HTTP Paths that already contains a stage name to Lambda Function and the Fast application will not be able to match the request with the available target routes.

To make sure all blueprints routes match the path sent from API Gateway, for each request the adapter will strip the API Gateway stage name AWS_API_GW_STAGE_NAME from the original HTTP Path.

The Terraform AWS Lambda API reusable modules will ensure that the same stage name is used for both AWS API Gateway and Fast Application so this logic can work.

Endpoints

To test all use cases we added a public endpoint, a private endpoint and an admin endpoint:

  • Public Endpoint: simple health check endpoint.

  • Auth Endpoint: OAuth Password Authentication Flow.

  • Private Endpoint: whoami endpoint that returns to the calling user his JWT decoded claims.

  • Admin Endpoint: returns to site admins the available Fast routes as a list.

  • Docs Endpoint: Swagger docs.

Authentication & Authorization

Authentication

The public endpoints will be open for all users without prior authentication but how about the private and admin endpoints? They certainly need an authentication system in place, for that we will not reinvent the wheel, and we will leverage an IaaS (Identity as a Service) provider like Firebase.

We have agreed to use an IaaS to authenticate users but how we can to verify the users issued JWT tokens? fortunately, AWS API Gateway can take that burden and it can:

  • Allow only access tokens that passed integrity check.
  • Verify that access tokens not yet expired.
  • Verify that access token is issued for an audience which is in the whitelisted audiences list.
  • Verify that access token has sufficient OAuth scopes to consume the endpoint.

Authorization

Authorization is an important aspect when building APIs, so we want certain functionalities/endpoints to be available to only a subset of our users. to achieve that there are two famous approaches to tackle that Role Based Access Control (RBAC) and OAuth Scopes Authorization.

Role Based Access Control (RBAC)

We have achieved that by implementing a Role Based Access Control (RBAC) model. where we assign each user a role or roles by adding them to groups and then decorate each route with the list of groups that can consume it.

When using an Identity as a Service providers like Auth0, Firebase and Cognito make sure to assign users to groups and during user's authentication, the JWT tokens service will embed the user's groups into the JWT Access/ID tokens claims

After authenticating to Identity Provider, the user can send their JWT access token to API Gateway that will verify the token integrity/expiration and dispatch the request with decoded JWT token to Lambda Function. Finally, the Lambda Function will compare user's groups claim with the whitelisted groups at route level and decide to allow it or forbid it.

This approach comes with many benefits but also with drawbacks:

  • Requests will not be authorized at the API Gateway level, and they need to travel to Lambda Function to run authorization logic.

  • Authorization rules will be writen in code, which will be messy from a DevOps perspective but a backend developers will favour that because they will have better visibility when coding/debugging, and they will know who can call any endpoint without going to infrastructure code.

OAuth Scopes Authorization

The second approach is by using OAuth Scopes Authorization model, and for each functionality/route we have to:

  • Create an OAuth scope.
  • Assign users the list of OAuth scopes that they can claim.
  • At API Gateway level specify the list of OAuth scopes that the user should have at least one of them for the API Gateway to let it reach the Lambda Function API.

The advantages of this approach are:

  • The ability to change permissions scopes at Identity Provider and API Gateway Level without changing/deploying new code.
  • Unauthorized requests will be revoked at API Gateway Level and before reaching the Lambda Function.

The Terraform AWS Lambda API module supports this authorization model and you can customize it using the module's routes_definitions Terraform variable.

You might also like...
Implement backup and recovery with AWS Backup across your AWS Organizations using a CI/CD pipeline (AWS CodePipeline).
Implement backup and recovery with AWS Backup across your AWS Organizations using a CI/CD pipeline (AWS CodePipeline).

Backup and Recovery with AWS Backup This repository provides you with a management and deployment solution for implementing Backup and Recovery with A

Criando Lambda Functions para Ingerir Dados de APIs com AWS CDK

LIVE001 - AWS Lambda para Ingerir Dados de APIs Fazer o deploy de uma função lambda com infraestrutura como código Lambda vai numa API externa e extra

A python library for creating Slack slash commands using AWS Lambda Functions

slashbot Slashbot makes it easy to create slash commands using AWS Lambda functions. These can be handy for creating a secure way to execute automated

AWS SQS event redrive Lambda With Python

AWS SQS event redrive Lambda This repository contains one simple AWS Lambda function in Python to redrive AWS SQS events from source queue to destinat

AWS SQS event redrive Lambda

This repository contains the Lambda function to redrive sqs events from source to destination queue while controlling maxRetry per event.

Building and deploying AWS Lambda Shared Layers

AWS Lambda Shared Layers This repository is hosting the code from the following blog post: AWS Lambda & Shared layers for Python. The goal of this rep

A Python AWS Lambda Webhook listener that generates a permanent URL when an asset is created in Contentstack.

Webhook Listener A Python Lambda Webhook Listener - Generates a permanent URL on created assets. See doc on Generating a Permanent URL: https://www.co

AWS Lambda - Parsing Cloudwatch Data and sending the response via email.

AWS Lambda - Parsing Cloudwatch Data and sending the response via email. Author: Evan Erickson Language: Python Backend: AWS / Serverless / AWS Lambda

JAWS Pankration 2021 - DDD on AWS Lambda sample
JAWS Pankration 2021 - DDD on AWS Lambda sample

JAWS Pankration 2021 - DDD on AWS Lambda sample What is this project? This project contains sample code for AWS Lambda with domain models. I presented

Owner
OBytes
We're a team of dreamers and makers who create products that your users will love
OBytes
Aws-lambda-requests-wrapper - Request/Response wrapper for AWS Lambda with API Gateway

AWS Lambda Requests Wrapper Request/Response wrapper for AWS Lambda with API Gat

null 1 May 20, 2022
AWS-serverless-starter - AWS Lambda serverless stack via Serverless framework

Serverless app via AWS Lambda, ApiGateway and Serverless framework Configuration

 Bəxtiyar 3 Feb 2, 2022
aws-lambda-scheduler lets you call any existing AWS Lambda Function you have in a future time.

aws-lambda-scheduler aws-lambda-scheduler lets you call any existing AWS Lambda Function you have in the future. This functionality is achieved by dyn

Oğuzhan Yılmaz 57 Dec 17, 2022
Python + AWS Lambda Hands OnPython + AWS Lambda Hands On

Python + AWS Lambda Hands On Python Criada em 1990, por Guido Van Rossum. "Bala de prata" (quase). Muito utilizado em: Automatizações - Selenium, Beau

Marcelo Ortiz de Santana 8 Sep 9, 2022
Lambda-function - Python codes that allow notification of changes made to some services using the AWS Lambda Function

AWS Lambda Function This repository contains python codes that allow notificatio

Elif Apaydın 3 Feb 11, 2022
SSH-Restricted deploys an SSH compliance rule (AWS Config) with auto-remediation via AWS Lambda if SSH access is public.

SSH-Restricted SSH-Restricted deploys an SSH compliance rule with auto-remediation via AWS Lambda if SSH access is public. SSH-Auto-Restricted checks

Adrian Hornsby 30 Nov 8, 2022
A suite of utilities for AWS Lambda Functions that makes tracing with AWS X-Ray, structured logging and creating custom metrics asynchronously easier

A suite of utilities for AWS Lambda Functions that makes tracing with AWS X-Ray, structured logging and creating custom metrics asynchronously easier

Amazon Web Services - Labs 1.9k Jan 7, 2023
POC de uma AWS lambda que executa a consulta de preços de criptomoedas, e é implantada na AWS usando Github actions.

Cryptocurrency Prices Overview Instalação Repositório Configuração CI/CD Roadmap Testes Overview A ideia deste projeto é aplicar o conteúdo estudado s

Gustavo Santos 3 Aug 31, 2022
Automated AWS account hardening with AWS Control Tower and AWS Step Functions

Automate activities in Control Tower provisioned AWS accounts Table of contents Introduction Architecture Prerequisites Tools and services Usage Clean

AWS Samples 20 Dec 7, 2022