mirror of
https://github.com/swift-server/swift-openapi-lambda.git
synced 2026-06-02 07:27:32 +00:00
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
97 lines
3.8 KiB
Swift
97 lines
3.8 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the Swift OpenAPI Lambda open source project
|
|
//
|
|
// Copyright Swift OpenAPI Lambda project authors
|
|
// Copyright (c) 2023 Amazon.com, Inc. or its affiliates.
|
|
// Licensed under Apache License v2.0
|
|
//
|
|
// See LICENSE.txt for license information
|
|
// See CONTRIBUTORS.txt for the list of Swift OpenAPI Lambda project authors
|
|
//
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
import AWSLambdaEvents
|
|
import AWSLambdaRuntime
|
|
|
|
//
|
|
// This is an example of a simple authorizer that always authorizes the request.
|
|
// A simple authorizer returns a yes/no decision and optional context key-value pairs
|
|
//
|
|
// Warning: this is an overly simplified authentication strategy, checking
|
|
// for the presence of a token.
|
|
//
|
|
// In your project, here you would likely call out to a library that performs
|
|
// a cryptographic validation, or similar.
|
|
//
|
|
// The code is for illustrative purposes only and should not be used directly.
|
|
let simpleAuthorizerHandler:
|
|
(APIGatewayLambdaAuthorizerRequest, LambdaContext) async throws -> APIGatewayLambdaAuthorizerSimpleResponse = {
|
|
(request: APIGatewayLambdaAuthorizerRequest, context: LambdaContext) in
|
|
|
|
context.logger.debug("+++ Simple Authorizer called +++")
|
|
|
|
guard let authToken = request.headers["authorization"]
|
|
else {
|
|
context.logger.warning("Missing Authorization header")
|
|
return .init(isAuthorized: false, context: [:])
|
|
}
|
|
|
|
// do not take an authorization decision here.
|
|
// bring the token to the OpenAPI service and let the developer
|
|
// verify authorization there.
|
|
|
|
return APIGatewayLambdaAuthorizerSimpleResponse(
|
|
// this is the authorization decision: yes or no
|
|
isAuthorized: true,
|
|
|
|
// this is additional context we want to return to the caller
|
|
// these values can be retrieved in requestContext.authorizer of the APIGatewayv2 request
|
|
context: ["token": authToken]
|
|
)
|
|
}
|
|
|
|
// create the runtime and start polling for new events.
|
|
// in this demo we use the simple authorizer handler
|
|
let runtime = LambdaRuntime(body: simpleAuthorizerHandler)
|
|
try await runtime.run()
|
|
|
|
// Another, more complex, example
|
|
//
|
|
// This is an example of a policy authorizer that always authorizes the request.
|
|
// The policy authorizer returns an IAM policy document that defines what the Lambda function caller can do and optional context key-value pairs
|
|
//
|
|
// This code is shown for the example only and is not used in this demo.
|
|
// This code doesn't perform any type of token validation. It should be used as a reference only.
|
|
// let policyAuthorizerHandler:
|
|
// (APIGatewayLambdaAuthorizerRequest, LambdaContext) async throws -> APIGatewayLambdaAuthorizerPolicyResponse = {
|
|
// (request: APIGatewayLambdaAuthorizerRequest, context: LambdaContext) in
|
|
|
|
// context.logger.debug("+++ Policy Authorizer called +++")
|
|
|
|
// // typically, this function will check the validity of the incoming token received in the request
|
|
|
|
// // then it creates and returns a response
|
|
// return APIGatewayLambdaAuthorizerPolicyResponse(
|
|
// principalId: "John Appleseed",
|
|
|
|
// // this policy allows the caller to invoke any API Gateway endpoint
|
|
// policyDocument: .init(statement: [
|
|
// .init(
|
|
// action: "execute-api:Invoke",
|
|
// effect: .allow,
|
|
// resource: "*"
|
|
// )
|
|
|
|
// ]),
|
|
|
|
// // this is additional context we want to return to the caller
|
|
// context: [
|
|
// "abc1": "xyz1",
|
|
// "abc2": "xyz2",
|
|
// ]
|
|
// )
|
|
// }
|