Skip to content
Myr

feat(aws-lambda): handle AWS Lattice events (#4451)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* feat(aws-lambda): handle AWS Lattice events * refactor(aws-lambda): consistent naming for Lattice v2 types * chore(aws-lambda): clean up

authored by Andreas H · committed by GitHub · parent 971106d · Browse files · 4 files+256 added−45 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+256 added−45 removed

  • tests:+121 added−33 removed
  • other:+135 added−12 removed

4 files+256 added−45 removed

modified:runtime-tests/lambda/index.test.ts+74 added-32 removed
8 unmodified lines
9} from '../../src/adapter/aws-lambda/handler'10import type {11 ALBProxyEvent,12 APIGatewayProxyEventV2,13 LatticeProxyEventV2,14 LambdaEvent,15} from '../../src/adapter/aws-lambda/handler'16import type {17 ApiGatewayRequestContext,18 ApiGatewayRequestContextV2,19 LatticeRequestContextV2,20 LambdaContext,21} from '../../src/adapter/aws-lambda/types'22import { getCookie, setCookie } from '../../src/helper/cookie'23import { streamSSE } from '../../src/helper/streaming'
38 unmodified lines
62 timeEpoch: 1583348638390,63 customProperty: 'customValue',64}6566const testLatticeRequestContext: LatticeRequestContextV2 = {67 serviceNetworkArn: 'arn:aws:vpc-lattice:us-east-1:111122223333:servicenetwork/sn-a1b2c3',68 serviceArn: 'arn:aws:vpc-lattice:us-east-1:111122223333:service/svc-a1b2c3',69 targetGroupArn: 'arn:aws:vpc-lattice:us-east-1:111122223333:targetgroup/tg-a1b2c3',70 region: 'us-east-1',71 timeEpoch: '1759915938150314',72 identity: {73 sourceVpcArn: 'arn:aws:ec2:us-east-1:111122223333:vpc/vpc-a1b2c3',74 },75}7677describe('AWS Lambda Adapter for Hono', () => {78 const app = new Hono<{ Bindings: Bindings }>()7980 app.get('/', (c) => {
125 unmodified lines
206 stage: '$default',207 customProperty: 'customValue',208 }209197 const testApiGatewayRequestContextV2 = {198 accountId: '123456789012',199 apiId: 'urlid',200 authentication: null,201 authorizer: {202 iam: {203 accessKey: 'AKIA...',204 accountId: '111122223333',205 callerId: 'AIDA...',206 cognitoIdentity: null,207 principalOrgId: null,208 userArn: 'arn:aws:iam::111122223333:user/example-user',209 userId: 'AIDA...',210 },211 },212 domainName: 'example.com',213 domainPrefix: '<url-id>',214 http: {215 method: 'POST',216 path: '/my/path',217 protocol: 'HTTP/1.1',218 sourceIp: '123.123.123.123',219 userAgent: 'agent',220 },221 requestId: 'id',222 routeKey: '$default',223 stage: '$default',224 time: '12/Mar/2020:19:03:58 +0000',225 timeEpoch: 1583348638390,226 customProperty: 'customValue',227 }228210 const testALBRequestContext = {211 elb: {212 targetGroupArn:213 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a',
82 unmodified lines
296 expect(response.multiValueHeaders).toBeUndefined()297 expect(response.isBase64Encoded).toBe(false)298 })299300 it('Should handle a GET request and return a 200 response (LatticeProxyEvent)', async () => {301 const event: LatticeProxyEventV2 = {302 version: '2.0',303 path: '/?query=1234ABCD',304 method: 'GET',305 headers: { 'content-type': ['text/plain'] },306 queryStringParameters: {},307 body: null,308 isBase64Encoded: false,309 requestContext: testLatticeRequestContext,310 }311312 const response = await handler(event)313 expect(response.statusCode).toBe(200)314 expect(response.body).toBe('Hello Lambda!')315 expect(response.headers['content-type']).toMatch(/^text\/plain/)316 expect(response.multiValueHeaders).toBeUndefined()317 expect(response.isBase64Encoded).toBe(false)318 })319320 it('Should handle a GET request and return a 404 response', async () => {321 const event = {322 version: '1.0',323 resource: '/nothing',
199 unmodified lines
523 testCookie2.serialized,524 ])525 })526527 it('Should handle a POST request and return a 200 response with cookies set (LatticeProxyEvent V2)', async () => {528 const latticeProxyEvent: LatticeProxyEventV2 = {529 version: '2.0',530 path: '/cookie',531 method: 'POST',532 headers: { 'content-type': ['text/plain'] },533 queryStringParameters: {},534 body: null,535 isBase64Encoded: false,536 requestContext: testLatticeRequestContext,537 }538539 const latticeResponse = await handler(latticeProxyEvent)540541 expect(latticeResponse.statusCode).toBe(200)542 expect(latticeResponse.headers).toHaveProperty(543 'set-cookie',544 [testCookie1.serialized, testCookie2.serialized].join(', ')545 )546 })547548 describe('headers', () => {549 describe('single-value headers', () => {550 it('Should extract single-value headers and return 200 (ALBProxyEvent)', async () => {551 const event = {
95 unmodified lines
647 }648 const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)649 expect(apiGatewayResponseV2.statusCode).toBe(200)650 })651652 it('Should extract multi-value headers and return 200 (LatticeProxyEvent)', async () => {653 const event: LatticeProxyEventV2 = {654 version: '2.0',655 path: '/headers',656 method: 'POST',657 headers: {658 host: ['localhost'],659 foo: ['bar'],660 },661 queryStringParameters: {},662 body: null,663 isBase64Encoded: false,664 requestContext: testLatticeRequestContext,665 }666667 const response = await handler(event)668669 expect(response.statusCode).toBe(200)670 })671 })672 })673674 it('Should handle a POST request and return a 200 response if cookies match (APIGatewayProxyEvent V1 and V2)', async () => {
413 unmodified lines
modified:src/adapter/aws-lambda/handler.test.ts+47 added-1 removed
1import type { LambdaEvent } from './handler'1import type { LambdaEvent, LatticeProxyEventV2 } from './handler'2import { getProcessor, isContentEncodingBinary, defaultIsContentTypeBinary } from './handler'34// Base event objects to reduce duplication5const baseV1Event: LambdaEvent = {
290 unmodified lines
296 header2: 'value1,value2',297 })298 })299300 it('Should return valid Request object from version 2.0 Lattice event', async () => {301 const event: LatticeProxyEventV2 = {302 version: '2.0',303 // query string parameters from the path take precedence over the explicit notation below304 path: '/my/path?parameter1=value1&parameter1=value2&parameter2=value',305 method: 'POST',306 headers: {307 cookie: ['cookie1=value1; cookie2=value2'],308 'content-type': ['application/x-www-form-urlencoded'],309 header1: ['value1'],310 header2: ['value1', 'value2'],311 host: ['my-service-a1b2c3.x1y2z3.vpc-lattice-svcs.us-east-1.on.aws'],312 },313 queryStringParameters: {314 parameter1: ['value1', 'value2'],315 parameter2: ['value'],316 },317 body: 'SGVsbG8gZnJvbSBMYW1iZGE=',318 isBase64Encoded: true,319 requestContext: {320 serviceNetworkArn: '',321 serviceArn: '',322 targetGroupArn: '',323 identity: {},324 region: 'us-east-1',325 timeEpoch: '1583348638390123',326 },327 }328329 const processor = getProcessor(event)330 const request = processor.createRequest(event)331332 expect(await request.text()).toEqual('Hello from Lambda')333 expect(request.method).toEqual('POST')334 expect(request.url).toEqual(335 'https://my-service-a1b2c3.x1y2z3.vpc-lattice-svcs.us-east-1.on.aws/my/path?parameter1=value1&parameter1=value2&parameter2=value'336 )337 expect(Object.fromEntries(request.headers)).toEqual({338 'content-type': 'application/x-www-form-urlencoded',339 cookie: 'cookie1=value1; cookie2=value2',340 header1: 'value1',341 header2: 'value1, value2',342 host: 'my-service-a1b2c3.x1y2z3.vpc-lattice-svcs.us-east-1.on.aws',343 })344 })345346 describe('non-ASCII header value processing', () => {347 it('Should encode non-ASCII header values with encodeURIComponent', async () => {348 const event: LambdaEvent = {349 ...baseV1Event,
13 unmodified lines
modified:src/adapter/aws-lambda/handler.ts+115 added-12 removed
5 unmodified lines
6 ApiGatewayRequestContext,7 ApiGatewayRequestContextV2,8 Handler,9 LambdaContext,10 LatticeRequestContextV2,11} from './types'1213function sanitizeHeaderValue(value: string): string {14 // Check if the value contains non-ASCII characters (char codes > 127)
4 unmodified lines
19 }20 return encodeURIComponent(value)21}2222export type LambdaEvent = APIGatewayProxyEvent | APIGatewayProxyEventV2 | ALBProxyEvent23export type LambdaEvent =24 | APIGatewayProxyEvent25 | APIGatewayProxyEventV226 | ALBProxyEvent27 | LatticeProxyEventV22829export interface LatticeProxyEventV2 {30 version: string31 path: string32 method: string33 headers: Record<string, string[] | undefined>34 queryStringParameters: Record<string, string[] | undefined>35 body: string | null36 isBase64Encoded: boolean37 requestContext: LatticeRequestContextV238}3940// When calling HTTP API or Lambda directly through function urls41export interface APIGatewayProxyEventV2 {42 version: string43 routeKey: string
70 unmodified lines
114} & (WithHeaders | WithMultiValueHeaders)115116const getRequestContext = (117 event: LambdaEvent102): ApiGatewayRequestContext | ApiGatewayRequestContextV2 | ALBRequestContext => {118):119 | ApiGatewayRequestContext120 | ApiGatewayRequestContextV2121 | ALBRequestContext122 | LatticeRequestContextV2 => {123 return event.requestContext124}125126const streamToNodeStream = async (
150 unmodified lines
277 protected abstract getCookies(event: E, headers: Headers): void278279 protected abstract setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void280281 protected getHeaderValue(headers: E['headers'], key: string): string | undefined {282 const value = headers283 ? Array.isArray(headers[key])284 ? headers[key][0]285 : headers[key]286 : undefined287288 return value289 }290291 protected getDomainName(event: E): string | undefined {292 if (event.requestContext && 'domainName' in event.requestContext) {293 return event.requestContext.domainName294 }295296 const hostFromHeaders = this.getHeaderValue(event.headers, 'host')297298 if (hostFromHeaders) {299 return hostFromHeaders300 }301302 const multiValueHeaders = 'multiValueHeaders' in event ? event.multiValueHeaders : {}303 const hostFromMultiValueHeaders = this.getHeaderValue(multiValueHeaders, 'host')304305 return hostFromMultiValueHeaders306 }307308 createRequest(event: E): Request {309 const queryString = this.getQueryString(event)263 const domainName =264 event.requestContext && 'domainName' in event.requestContext265 ? event.requestContext.domainName266 : event.headers?.['host'] ?? event.multiValueHeaders?.['host']?.[0]310 const domainName = this.getDomainName(event)311 const path = this.getPath(event)312 const urlPath = `https://${domainName}${path}`313 const url = queryString ? `${urlPath}?${queryString}` : urlPath314
32 unmodified lines
347 const result: APIGatewayProxyResult = {348 body: body,349 statusCode: res.status,350 isBase64Encoded,307 ...(event.multiValueHeaders351 ...('multiValueHeaders' in event && event.multiValueHeaders352 ? {353 multiValueHeaders: {},354 }355 : {
69 unmodified lines
425}426427const v2Processor: EventV2Processor = new EventV2Processor()428385export class EventV1Processor extends EventProcessor<Exclude<LambdaEvent, APIGatewayProxyEventV2>> {386 protected getPath(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {429export class EventV1Processor extends EventProcessor<APIGatewayProxyEvent> {430 protected getPath(event: APIGatewayProxyEvent): string {431 return event.path432 }433390 protected getMethod(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {434 protected getMethod(event: APIGatewayProxyEvent): string {435 return event.httpMethod436 }437394 protected getQueryString(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {438 protected getQueryString(event: APIGatewayProxyEvent): string {439 // In the case of gateway Integration either queryStringParameters or multiValueQueryStringParameters can be present not both440 // API Gateway passes decoded values, so we need to re-encode them to preserve the original URL441 if (event.multiValueQueryStringParameters) {442 return Object.entries(event.multiValueQueryStringParameters || {})
11 unmodified lines
454 }455456 protected getCookies(457 // eslint-disable-next-line @typescript-eslint/no-unused-vars414 event: Exclude<LambdaEvent, APIGatewayProxyEventV2>,458 event: APIGatewayProxyEvent,459 // eslint-disable-next-line @typescript-eslint/no-unused-vars460 headers: Headers461 ): void {462 // nop
116 unmodified lines
579}580581const albProcessor: ALBProcessor = new ALBProcessor()582583export class LatticeV2Processor extends EventProcessor<LatticeProxyEventV2> {584 protected getPath(event: LatticeProxyEventV2): string {585 return event.path586 }587588 protected getMethod(event: LatticeProxyEventV2): string {589 return event.method590 }591592 protected getQueryString(): string {593 return ''594 }595596 protected getHeaders(event: LatticeProxyEventV2): Headers {597 const headers = new Headers()598599 if (event.headers) {600 for (const [k, values] of Object.entries(event.headers)) {601 if (values) {602 // avoid duplicating already set headers603 const foundK = headers.get(k)604 values.forEach((v) => {605 const sanitizedValue = sanitizeHeaderValue(v)606 return (607 (!foundK || !foundK.includes(sanitizedValue)) && headers.append(k, sanitizedValue)608 )609 })610 }611 }612 }613614 return headers615 }616617 protected getCookies(): void {618 // nop619 }620621 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {622 result.headers = {623 ...result.headers,624 'set-cookie': cookies.join(', '),625 }626 }627}628629const latticeV2Processor: LatticeV2Processor = new LatticeV2Processor()630631export const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {632 if (isProxyEventALB(event)) {633 return albProcessor634 }635 if (isProxyEventV2(event)) {636 return v2Processor637 }638 if (isLatticeEventV2(event)) {639 return latticeV2Processor640 }641642 return v1Processor643}644645const isProxyEventALB = (event: LambdaEvent): event is ALBProxyEvent => {
6 unmodified lines
652const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {653 return Object.hasOwn(event, 'rawPath')654}655656const isLatticeEventV2 = (event: LambdaEvent): event is LatticeProxyEventV2 => {657 if (event.requestContext) {658 return Object.hasOwn(event.requestContext, 'serviceArn')659 }660 return false661}662663/**664 * Check if the given content type is binary.665 * This is a default function and may be overwritten by the user via `isContentTypeBinary` option in handler().666 * @param contentType The content type to check.
14 unmodified lines
modified:src/adapter/aws-lambda/types.ts+20 added