Skip to content
Myr

handler.ts

This file

Path

src/adapter/aws-lambda/handler.ts

487 lines 路 14.2 KiB 路 TypeScript

Last changed by

fix(aws-lambda): handle multiple cookies in streaming responses (#2926)Markus Wolfbefore adoptiona2a04a9

History of this file

Take it

1import crypto from 'node:crypto'2import type { Hono } from '../../hono'3import type { Env, Schema } from '../../types'4import { decodeBase64, encodeBase64 } from '../../utils/encode'5import type {6  ALBRequestContext,7  ApiGatewayRequestContext,8  ApiGatewayRequestContextV2,9  Handler,10  LambdaContext,11} from './types'1213// eslint-disable-next-line @typescript-eslint/ban-ts-comment14// @ts-ignore15globalThis.crypto ??= crypto1617export type LambdaEvent = APIGatewayProxyEvent | APIGatewayProxyEventV2 | ALBProxyEvent1819// When calling HTTP API or Lambda directly through function urls20export interface APIGatewayProxyEventV2 {21  version: string22  routeKey: string23  headers: Record<string, string | undefined>24  multiValueHeaders?: undefined25  cookies?: string[]26  rawPath: string27  rawQueryString: string28  body: string | null29  isBase64Encoded: boolean30  requestContext: ApiGatewayRequestContextV231  queryStringParameters?: {32    [name: string]: string | undefined33  }34  pathParameters?: {35    [name: string]: string | undefined36  }37  stageVariables?: {38    [name: string]: string | undefined39  }40}4142// When calling Lambda through an API Gateway43export interface APIGatewayProxyEvent {44  version: string45  httpMethod: string46  headers: Record<string, string | undefined>47  multiValueHeaders?: {48    [headerKey: string]: string[]49  }50  path: string51  body: string | null52  isBase64Encoded: boolean53  queryStringParameters?: Record<string, string | undefined>54  requestContext: ApiGatewayRequestContext55  resource: string56  multiValueQueryStringParameters?: {57    [parameterKey: string]: string[]58  }59  pathParameters?: Record<string, string>60  stageVariables?: Record<string, string>61}6263// When calling Lambda through an Application Load Balancer64export interface ALBProxyEvent {65  httpMethod: string66  headers?: Record<string, string | undefined>67  multiValueHeaders?: Record<string, string[] | undefined>68  path: string69  body: string | null70  isBase64Encoded: boolean71  queryStringParameters?: Record<string, string | undefined>72  multiValueQueryStringParameters?: {73    [parameterKey: string]: string[]74  }75  requestContext: ALBRequestContext76}7778export interface APIGatewayProxyResult {79  statusCode: number80  statusDescription?: string81  body: string82  headers: Record<string, string>83  cookies?: string[]84  multiValueHeaders?: {85    [headerKey: string]: string[]86  }87  isBase64Encoded: boolean88}8990const getRequestContext = (91  event: LambdaEvent92): ApiGatewayRequestContext | ApiGatewayRequestContextV2 | ALBRequestContext => {93  return event.requestContext94}9596const streamToNodeStream = async (97  reader: ReadableStreamDefaultReader<Uint8Array>,98  writer: NodeJS.WritableStream99): Promise<void> => {100  let readResult = await reader.read()101  while (!readResult.done) {102    writer.write(readResult.value)103    readResult = await reader.read()104  }105  writer.end()106}107108export const streamHandle = <109  E extends Env = Env,110  S extends Schema = {},111  BasePath extends string = '/'112>(113  app: Hono<E, S, BasePath>114): Handler => {115  // @ts-expect-error awslambda is not a standard API116  return awslambda.streamifyResponse(117    async (event: LambdaEvent, responseStream: NodeJS.WritableStream, context: LambdaContext) => {118      const processor = getProcessor(event)119      try {120        const req = processor.createRequest(event)121        const requestContext = getRequestContext(event)122123        const res = await app.fetch(req, {124          event,125          requestContext,126          context,127        })128129        const headers: Record<string, string> = {}130        const cookies: string[] = []131        res.headers.forEach((value, name) => {132          if (name === 'set-cookie') {133            cookies.push(value)134          } else {135            headers[name] = value136          }137        })138139        // Check content type140        const httpResponseMetadata = {141          statusCode: res.status,142          headers,143          cookies,144        }145146        // Update response stream147        // @ts-expect-error awslambda is not a standard API148        responseStream = awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata)149150        if (res.body) {151          await streamToNodeStream(res.body.getReader(), responseStream)152        } else {153          responseStream.write('')154        }155      } catch (error) {156        console.error('Error processing request:', error)157        responseStream.write('Internal Server Error')158      } finally {159        responseStream.end()160      }161    }162  )163}164165/**166 * Accepts events from API Gateway/ELB(`APIGatewayProxyEvent`) and directly through Function Url(`APIGatewayProxyEventV2`)167 */168export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(169  app: Hono<E, S, BasePath>170): ((event: LambdaEvent, lambdaContext?: LambdaContext) => Promise<APIGatewayProxyResult>) => {171  return async (event, lambdaContext?) => {172    const processor = getProcessor(event)173174    const req = processor.createRequest(event)175    const requestContext = getRequestContext(event)176177    const res = await app.fetch(req, {178      event,179      requestContext,180      lambdaContext,181    })182183    return processor.createResult(event, res)184  }185}186187abstract class EventProcessor<E extends LambdaEvent> {188  protected abstract getPath(event: E): string189190  protected abstract getMethod(event: E): string191192  protected abstract getQueryString(event: E): string193194  protected abstract getHeaders(event: E): Headers195196  protected abstract getCookies(event: E, headers: Headers): void197198  protected abstract setCookiesToResult(199    event: E,200    result: APIGatewayProxyResult,201    cookies: string[]202  ): void203204  createRequest(event: E): Request {205    const queryString = this.getQueryString(event)206    const domainName =207      event.requestContext && 'domainName' in event.requestContext208        ? event.requestContext.domainName209        : event.headers?.['host'] ?? event.multiValueHeaders?.['host']?.[0]210    const path = this.getPath(event)211    const urlPath = `https://${domainName}${path}`212    const url = queryString ? `${urlPath}?${queryString}` : urlPath213214    const headers = this.getHeaders(event)215216    const method = this.getMethod(event)217    const requestInit: RequestInit = {218      headers,219      method,220    }221222    if (event.body) {223      requestInit.body = event.isBase64Encoded ? decodeBase64(event.body) : event.body224    }225226    return new Request(url, requestInit)227  }228229  async createResult(event: E, res: Response): Promise<APIGatewayProxyResult> {230    const contentType = res.headers.get('content-type')231    let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false232233    if (!isBase64Encoded) {234      const contentEncoding = res.headers.get('content-encoding')235      isBase64Encoded = isContentEncodingBinary(contentEncoding)236    }237238    const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()239240    const result: APIGatewayProxyResult = {241      body: body,242      headers: {},243      multiValueHeaders: event.multiValueHeaders ? {} : undefined,244      statusCode: res.status,245      isBase64Encoded,246    }247248    this.setCookies(event, res, result)249    res.headers.forEach((value, key) => {250      result.headers[key] = value251      if (event.multiValueHeaders && result.multiValueHeaders) {252        result.multiValueHeaders[key] = [value]253      }254    })255256    return result257  }258259  setCookies(event: E, res: Response, result: APIGatewayProxyResult) {260    if (res.headers.has('set-cookie')) {261      const cookies = res.headers.get('set-cookie')?.split(', ')262      if (Array.isArray(cookies)) {263        this.setCookiesToResult(event, result, cookies)264        res.headers.delete('set-cookie')265      }266    }267  }268}269270class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {271  protected getPath(event: APIGatewayProxyEventV2): string {272    return event.rawPath273  }274275  protected getMethod(event: APIGatewayProxyEventV2): string {276    return event.requestContext.http.method277  }278279  protected getQueryString(event: APIGatewayProxyEventV2): string {280    return event.rawQueryString281  }282283  protected getCookies(event: APIGatewayProxyEventV2, headers: Headers): void {284    if (Array.isArray(event.cookies)) {285      headers.set('Cookie', event.cookies.join('; '))286    }287  }288289  protected setCookiesToResult(290    _: APIGatewayProxyEventV2,291    result: APIGatewayProxyResult,292    cookies: string[]293  ): void {294    result.cookies = cookies295  }296297  protected getHeaders(event: APIGatewayProxyEventV2): Headers {298    const headers = new Headers()299    this.getCookies(event, headers)300    if (event.headers) {301      for (const [k, v] of Object.entries(event.headers)) {302        if (v) {303          headers.set(k, v)304        }305      }306    }307    return headers308  }309}310311const v2Processor: EventV2Processor = new EventV2Processor()312313class EventV1Processor extends EventProcessor<Exclude<LambdaEvent, APIGatewayProxyEventV2>> {314  protected getPath(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {315    return event.path316  }317318  protected getMethod(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {319    return event.httpMethod320  }321322  protected getQueryString(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {323    return Object.entries(event.queryStringParameters || {})324      .filter(([, value]) => value)325      .map(([key, value]) => `${key}=${value}`)326      .join('&')327  }328329  protected getCookies(330    // eslint-disable-next-line @typescript-eslint/no-unused-vars331    event: Exclude<LambdaEvent, APIGatewayProxyEventV2>,332    // eslint-disable-next-line @typescript-eslint/no-unused-vars333    headers: Headers334  ): void {335    // nop336  }337338  protected getHeaders(event: APIGatewayProxyEvent): Headers {339    const headers = new Headers()340    this.getCookies(event, headers)341    if (event.headers) {342      for (const [k, v] of Object.entries(event.headers)) {343        if (v) {344          headers.set(k, v)345        }346      }347    }348    if (event.multiValueHeaders) {349      for (const [k, values] of Object.entries(event.multiValueHeaders)) {350        if (values) {351          // avoid duplicating already set headers352          const foundK = headers.get(k)353          values.forEach((v) => (!foundK || !foundK.includes(v)) && headers.append(k, v))354        }355      }356    }357    return headers358  }359360  protected setCookiesToResult(361    _: APIGatewayProxyEvent,362    result: APIGatewayProxyResult,363    cookies: string[]364  ): void {365    result.multiValueHeaders = {366      'set-cookie': cookies,367    }368  }369}370371const v1Processor: EventV1Processor = new EventV1Processor()372373class ALBProcessor extends EventProcessor<ALBProxyEvent> {374  protected getHeaders(event: ALBProxyEvent): Headers {375    const headers = new Headers()376    // if multiValueHeaders is present the ALB will use it instead of the headers field377    // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers378    if (event.multiValueHeaders) {379      for (const [key, values] of Object.entries(event.multiValueHeaders)) {380        if (values && Array.isArray(values)) {381          // https://www.rfc-editor.org/rfc/rfc9110.html#name-common-rules-for-defining-f382          headers.set(key, values.join('; '))383        }384      }385    } else {386      for (const [key, value] of Object.entries(event.headers ?? {})) {387        if (value) {388          headers.set(key, value)389        }390      }391    }392    return headers393  }394395  protected getPath(event: ALBProxyEvent): string {396    return event.path397  }398399  protected getMethod(event: ALBProxyEvent): string {400    return event.httpMethod401  }402403  protected getQueryString(event: ALBProxyEvent): string {404    // In the case of ALB Integration either queryStringParameters or multiValueQueryStringParameters can be present not both405    /* 406      In other cases like when using the serverless framework, the event object does contain both queryStringParameters and multiValueQueryStringParameters:407      Below is an example event object for this URL: /payment/b8c55e69?select=amount&select=currency408      {409        ...410        queryStringParameters: { select: 'currency' },411        multiValueQueryStringParameters: { select: [ 'amount', 'currency' ] },412      }413      The expected results is for select to be an array with two items. However the pre-fix code is only returning one item ('currency') in the array.414      A simple fix would be to invert the if statement and check the multiValueQueryStringParameters first.415    */416    if (event.multiValueQueryStringParameters) {417      return Object.entries(event.multiValueQueryStringParameters || {})418        .filter(([, value]) => value)419        .map(([key, value]) => `${key}=${value.join(`&${key}=`)}`)420        .join('&')421    } else {422      return Object.entries(event.queryStringParameters || {})423        .filter(([, value]) => value)424        .map(([key, value]) => `${key}=${value}`)425        .join('&')426    }427  }428429  protected getCookies(event: ALBProxyEvent, headers: Headers): void {430    let cookie431    if (event.multiValueHeaders) {432      cookie = event.multiValueHeaders['cookie']?.join('; ')433    } else {434      cookie = event.headers ? event.headers['cookie'] : undefined435    }436    if (cookie) {437      headers.append('Cookie', cookie)438    }439  }440441  protected setCookiesToResult(442    event: ALBProxyEvent,443    result: APIGatewayProxyResult,444    cookies: string[]445  ): void {446    // when multi value headers is enabled447    if (event.multiValueHeaders && result.multiValueHeaders) {448      result.multiValueHeaders['set-cookie'] = cookies449    } else {450      // otherwise serialize the set-cookie451      result.headers['set-cookie'] = cookies.join(', ')452    }453  }454}455456const albProcessor: ALBProcessor = new ALBProcessor()457458export const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {459  if (isProxyEventALB(event)) {460    return albProcessor461  }462  if (isProxyEventV2(event)) {463    return v2Processor464  }465  return v1Processor466}467468const isProxyEventALB = (event: LambdaEvent): event is ALBProxyEvent => {469  return Object.hasOwn(event.requestContext, 'elb')470}471472const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {473  return Object.hasOwn(event, 'rawPath')474}475476export const isContentTypeBinary = (contentType: string) => {477  return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml.*)$/.test(478    contentType479  )480}481482export const isContentEncodingBinary = (contentEncoding: string | null) => {483  if (contentEncoding === null) {484    return false485  }486  return /^(gzip|deflate|compress|br)/.test(contentEncoding)487}