Files
Sébastien Stormacq 97b2e6d017 Add support for Lambda functions exposed behind an Application Load Balancer (ALB) (#29)
This PR adds support for exposing Swift OpenAPI Lambda functions behind
an Application Load Balancer (ALB), providing an alternative to API
Gateway for HTTP routing to Lambda functions.

## Changes

### New ALB Support
- **OpenAPILambdaALB Protocol**: New protocol for ALB integration
alongside existing API Gateway support
- **ALB Event Handling**: Added `ALBTargetGroupRequest` and
`ALBTargetGroupResponse` support
- **HTTP Request Conversion**: Extension methods to convert ALB events
to/from HTTP requests/responses

### Core Library Updates
- **ALB-related source files**: New `/Sources/ALB/` directory with
ALB-specific implementations
- **Event Type Support**: Support for `ALBTargetGroupRequest` events
from Elastic Load Balancing
- **Response Mapping**: Proper mapping from OpenAPI responses to ALB
target group responses

### Complete ALB Example
- **QuoteAPI ALB Example**: Full working example in
`Examples/quoteapi-alb/`
- **Infrastructure as Code**: Complete SAM template with VPC, subnets,
security groups, and ALB
- **Build System**: Makefile and Docker build support for ALB deployment
- **Documentation**: Comprehensive README with ALB-specific deployment
instructions

### Key Files Added
```
Sources/ALB/
├── OpenAPILambdaALB.swift
└── ALBTargetGroup+HTTPRequest.swift

Examples/quoteapi-alb/
├── Package.swift
├── template.yaml
├── Makefile
├── README.md
├── Sources/QuoteAPI/QuoteService.swift
├── Sources/QuoteAPI/openapi.yaml
├── Sources/QuoteAPI/openapi-generator-config.yaml
└── events/GetQuote.json
```

## Usage

### Simple ALB Integration
```swift
@main
struct QuoteServiceALBImpl: APIProtocol, OpenAPILambdaALB {
    func register(transport: OpenAPILambdaTransport) throws {
        try self.registerHandlers(on: transport)
    }
    
    static func main() async throws {
        let service = QuoteServiceALBImpl()
        try await service.run()
    }
    
    // Your OpenAPI implementation...
}
```

### Key Differences from API Gateway
- Uses `OpenAPILambdaALB` instead of `OpenAPILambdaHttpApi`
- Handles `ALBTargetGroupRequest` events instead of
`APIGatewayV2Request`
- Returns `ALBTargetGroupResponse` instead of `APIGatewayV2Response`
- Requires VPC infrastructure (included in SAM template)
- No built-in authorization (implement via custom middleware if needed)

## Benefits

- **Cost Optimization**: ALB can be more cost-effective for high-traffic
applications
- **VPC Integration**: Native VPC support for private network access
- **Load Balancing**: Advanced load balancing features and health checks
- **WebSocket Support**: Future WebSocket support through ALB
- **Flexibility**: Choice between API Gateway and ALB based on use case

## Testing

-  ALB example builds successfully with `sam build`
-  Local testing with `sam local invoke`
-  Complete infrastructure deployment via SAM
-  HTTP requests properly routed through ALB to Lambda
-  OpenAPI specification compatibility maintained

## Deployment

Deploy the ALB example:
```bash
cd Examples/quoteapi-alb
sam build && sam deploy --guided
```

Test the deployed endpoint:
```bash
curl http://[alb-dns-name]/stocks/AAPL
```

## Backward Compatibility

This is a purely additive change:
- Existing API Gateway implementations continue to work unchanged
- No breaking changes to existing APIs
- New ALB support is opt-in via protocol conformance
2025-10-26 09:10:09 +01:00

5.0 KiB

QuoteAPI ALB Example

This application illustrates how to deploy a Server-Side Swift workload on AWS using an Application Load Balancer (ALB) with Lambda targets. The workload is a simple REST API that returns stock quotes. Requests to the ALB are forwarded to an AWS Lambda Function written in Swift using the OpenAPI Lambda library.

Prerequisites

To build this sample application, you need:

Build the application

The sam build command uses Docker to compile your Swift Lambda function and package it for deployment to AWS.

sam build

On macOS, you might need to run this command if sam doesn't see docker:

export DOCKER_HOST=unix://$HOME/.docker/run/docker.sock

Deploy the application

The sam deploy command creates the Lambda function, Application Load Balancer, and associated VPC resources in your AWS account.

sam deploy --guided

Use the API

At the end of the deployment, SAM displays the endpoint of your Application Load Balancer:

Outputs
----------------------------------------------------------------------------------------
Key                 QuoteAPILoadBalancerURL
Description         Application Load Balancer URL for QuoteAPI
Value               http://QuoteAPILoadBalancer-123456789.us-east-1.elb.amazonaws.com/stocks/AAPL
----------------------------------------------------------------------------------------

Use cURL or a tool such as Postman to interact with your API. Replace [your-alb-endpoint] with the QuoteAPILoadBalancerURL value from the deployment output.

Invoke the API Endpoint

curl http://[your-alb-endpoint]/stocks/AMZN

Test the API Locally

SAM also allows you to execute your Lambda functions locally on your development computer.

Invoke the Lambda Function Locally

sam local invoke QuoteServiceALB --event events/GetQuote.json

On macOS, you might need to run this command if sam doesn't see docker:

export DOCKER_HOST=unix://$HOME/.docker/run/docker.sock

Architecture

This example demonstrates:

  • Application Load Balancer: Routes HTTP requests to Lambda functions
  • Lambda Target Group: Configures the ALB to forward requests to Lambda
  • VPC Setup: Creates a VPC with public subnets for the ALB
  • Security Groups: Controls inbound traffic to the ALB
  • OpenAPI Integration: Uses Swift OpenAPI Lambda library with ALB events

Cleanup

When finished with your application, use SAM to delete it from your AWS account. Answer Yes (y) to all prompts. This will delete all of the application resources created in your AWS account.

sam delete

⚠️ Security and Reliability Notice

This is an example application for demonstration purposes. When deploying such infrastructure in production environments, we strongly encourage you to follow these best practices for improved security and resiliency:

Note: The openapi.yaml file in this example is not suited for production. In real-world scenarios, you must:

  1. Ensure that the global security field has rules defined
  2. Ensure that security operations is not empty (OpenAPI Security Specification)
  3. Follow proper authentication, authorization, input validation, and error handling practices

As per Checkov CKV_OPENAPI_4 and CKV_OPENAPI_5 security checks.