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
Provenance
- Commit
cea3fb0- Tree
7b5a610- Author
Andreas H <863612+anho@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
971106d
4 files changed+256 added−45 removed
modified:runtime-tests/lambda/index.test.ts+74 added-32 removed
8 unmodified lines9 } from '../../src/adapter/aws-lambda/handler'10 import type {11 ALBProxyEvent,12 APIGatewayProxyEventV2,13+ LatticeProxyEventV2,14 LambdaEvent,15 } from '../../src/adapter/aws-lambda/handler'16 import type {17 ApiGatewayRequestContext,18 ApiGatewayRequestContextV2,19+ LatticeRequestContextV2,20 LambdaContext,21 } from '../../src/adapter/aws-lambda/types'22 import { getCookie, setCookie } from '../../src/helper/cookie'23 import { streamSSE } from '../../src/helper/streaming'38 unmodified lines62 timeEpoch: 1583348638390,63 customProperty: 'customValue',64 }65 66+const 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+}76+77 describe('AWS Lambda Adapter for Hono', () => {78 const app = new Hono<{ Bindings: Bindings }>()79 80 app.get('/', (c) => {125 unmodified lines206 stage: '$default',207 customProperty: 'customValue',208 }209 197- 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- }228-210 const testALBRequestContext = {211 elb: {212 targetGroupArn:213 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a',82 unmodified lines296 expect(response.multiValueHeaders).toBeUndefined()297 expect(response.isBase64Encoded).toBe(false)298 })299 300+ 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+ }311+312+ 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+ })319+320 it('Should handle a GET request and return a 404 response', async () => {321 const event = {322 version: '1.0',323 resource: '/nothing',199 unmodified lines523 testCookie2.serialized,524 ])525 })526 527+ 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+ }538+539+ const latticeResponse = await handler(latticeProxyEvent)540+541+ expect(latticeResponse.statusCode).toBe(200)542+ expect(latticeResponse.headers).toHaveProperty(543+ 'set-cookie',544+ [testCookie1.serialized, testCookie2.serialized].join(', ')545+ )546+ })547+548 describe('headers', () => {549 describe('single-value headers', () => {550 it('Should extract single-value headers and return 200 (ALBProxyEvent)', async () => {551 const event = {95 unmodified lines647 }648 const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)649 expect(apiGatewayResponseV2.statusCode).toBe(200)650 })651+652+ 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+ }666+667+ const response = await handler(event)668+669+ expect(response.statusCode).toBe(200)670+ })671 })672 })673 674 it('Should handle a POST request and return a 200 response if cookies match (APIGatewayProxyEvent V1 and V2)', async () => {413 unmodified linesmodified:src/adapter/aws-lambda/handler.test.ts+47 added-1 removed
1-import type { LambdaEvent } from './handler'1+import type { LambdaEvent, LatticeProxyEventV2 } from './handler'2 import { getProcessor, isContentEncodingBinary, defaultIsContentTypeBinary } from './handler'3 4 // Base event objects to reduce duplication5 const baseV1Event: LambdaEvent = {290 unmodified lines296 header2: 'value1,value2',297 })298 })299 300+ 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¶meter1=value2¶meter2=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+ }328+329+ const processor = getProcessor(event)330+ const request = processor.createRequest(event)331+332+ 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¶meter1=value2¶meter2=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+ })345+346 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 linesmodified:src/adapter/aws-lambda/handler.ts+115 added-12 removed
5 unmodified lines6 ApiGatewayRequestContext,7 ApiGatewayRequestContextV2,8 Handler,9 LambdaContext,10+ LatticeRequestContextV2,11 } from './types'12 13 function sanitizeHeaderValue(value: string): string {14 // Check if the value contains non-ASCII characters (char codes > 127)4 unmodified lines19 }20 return encodeURIComponent(value)21 }22 22-export type LambdaEvent = APIGatewayProxyEvent | APIGatewayProxyEventV2 | ALBProxyEvent23+export type LambdaEvent =24+ | APIGatewayProxyEvent25+ | APIGatewayProxyEventV226+ | ALBProxyEvent27+ | LatticeProxyEventV228 29+export 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+}39+40 // When calling HTTP API or Lambda directly through function urls41 export interface APIGatewayProxyEventV2 {42 version: string43 routeKey: string70 unmodified lines114 } & (WithHeaders | WithMultiValueHeaders)115 116 const getRequestContext = (117 event: LambdaEvent102-): ApiGatewayRequestContext | ApiGatewayRequestContextV2 | ALBRequestContext => {118+):119+ | ApiGatewayRequestContext120+ | ApiGatewayRequestContextV2121+ | ALBRequestContext122+ | LatticeRequestContextV2 => {123 return event.requestContext124 }125 126 const streamToNodeStream = async (150 unmodified lines277 protected abstract getCookies(event: E, headers: Headers): void278 279 protected abstract setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void280 281+ 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+ : undefined287+288+ return value289+ }290+291+ protected getDomainName(event: E): string | undefined {292+ if (event.requestContext && 'domainName' in event.requestContext) {293+ return event.requestContext.domainName294+ }295+296+ const hostFromHeaders = this.getHeaderValue(event.headers, 'host')297+298+ if (hostFromHeaders) {299+ return hostFromHeaders300+ }301+302+ const multiValueHeaders = 'multiValueHeaders' in event ? event.multiValueHeaders : {}303+ const hostFromMultiValueHeaders = this.getHeaderValue(multiValueHeaders, 'host')304+305+ return hostFromMultiValueHeaders306+ }307+308 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 lines347 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 lines425 }426 427 const v2Processor: EventV2Processor = new EventV2Processor()428 385-export class EventV1Processor extends EventProcessor<Exclude<LambdaEvent, APIGatewayProxyEventV2>> {386- protected getPath(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {429+export class EventV1Processor extends EventProcessor<APIGatewayProxyEvent> {430+ protected getPath(event: APIGatewayProxyEvent): string {431 return event.path432 }433 390- protected getMethod(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {434+ protected getMethod(event: APIGatewayProxyEvent): string {435 return event.httpMethod436 }437 394- 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 lines454 }455 456 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 // nop116 unmodified lines579 }580 581 const albProcessor: ALBProcessor = new ALBProcessor()582 583+export class LatticeV2Processor extends EventProcessor<LatticeProxyEventV2> {584+ protected getPath(event: LatticeProxyEventV2): string {585+ return event.path586+ }587+588+ protected getMethod(event: LatticeProxyEventV2): string {589+ return event.method590+ }591+592+ protected getQueryString(): string {593+ return ''594+ }595+596+ protected getHeaders(event: LatticeProxyEventV2): Headers {597+ const headers = new Headers()598+599+ 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+ }613+614+ return headers615+ }616+617+ protected getCookies(): void {618+ // nop619+ }620+621+ protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {622+ result.headers = {623+ ...result.headers,624+ 'set-cookie': cookies.join(', '),625+ }626+ }627+}628+629+const latticeV2Processor: LatticeV2Processor = new LatticeV2Processor()630+631 export 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+ }641+642 return v1Processor643 }644 645 const isProxyEventALB = (event: LambdaEvent): event is ALBProxyEvent => {6 unmodified lines652 const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {653 return Object.hasOwn(event, 'rawPath')654 }655 656+const isLatticeEventV2 = (event: LambdaEvent): event is LatticeProxyEventV2 => {657+ if (event.requestContext) {658+ return Object.hasOwn(event.requestContext, 'serviceArn')659+ }660+ return false661+}662+663 /**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 linesmodified:src/adapter/aws-lambda/types.ts+20 added
140 unmodified linesExpand all141142143144145146147148149150151152153154155156157158159160161162163164140 unmodified linesExpand all elb: { targetGroupArn: string }}
export interface LatticeRequestContextV2 { serviceNetworkArn: string serviceArn: string targetGroupArn: string region: string timeEpoch: string identity: { sourceVpcArn?: string type?: string principal?: string principalOrgID?: string sessionName?: string x509IssuerOu?: string x509SanDns?: string x509SanNameCn?: string x509SanUri?: string x509SubjectCn?: string }}