handler.ts
This file
Path
src/adapter/aws-lambda/handler.ts
685 lines 路 20.1 KiB 路 TypeScript
Last changed by
fix(aws-lambda): handle invalid header names in request processing (#4883)Yusuke Wadabefore adoptionfa2c74f
History of this fileTake it
1import type { Hono } from '../../hono'2import type { Env, Schema } from '../../types'3import { decodeBase64, encodeBase64 } from '../../utils/encode'4import type {5 ALBRequestContext,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)15 // eslint-disable-next-line no-control-regex16 const hasNonAscii = /[^\x00-\x7F]/.test(value)17 if (!hasNonAscii) {18 return value19 }20 return encodeURIComponent(value)21}2223export 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: string44 headers: Record<string, string | undefined>45 multiValueHeaders?: undefined46 cookies?: string[]47 rawPath: string48 rawQueryString: string49 body: string | null50 isBase64Encoded: boolean51 requestContext: ApiGatewayRequestContextV252 queryStringParameters?: {53 [name: string]: string | undefined54 }55 pathParameters?: {56 [name: string]: string | undefined57 }58 stageVariables?: {59 [name: string]: string | undefined60 }61}6263// When calling Lambda through an API Gateway64export interface APIGatewayProxyEvent {65 version: string66 httpMethod: string67 headers: Record<string, string | undefined>68 multiValueHeaders?: {69 [headerKey: string]: string[]70 }71 path: string72 body: string | null73 isBase64Encoded: boolean74 queryStringParameters?: Record<string, string | undefined>75 requestContext: ApiGatewayRequestContext76 resource: string77 multiValueQueryStringParameters?: {78 [parameterKey: string]: string[]79 }80 pathParameters?: Record<string, string>81 stageVariables?: Record<string, string>82}8384// When calling Lambda through an Application Load Balancer85export interface ALBProxyEvent {86 httpMethod: string87 headers?: Record<string, string | undefined>88 multiValueHeaders?: Record<string, string[] | undefined>89 path: string90 body: string | null91 isBase64Encoded: boolean92 queryStringParameters?: Record<string, string | undefined>93 multiValueQueryStringParameters?: {94 [parameterKey: string]: string[]95 }96 requestContext: ALBRequestContext97}9899type WithHeaders = {100 headers: Record<string, string>101 multiValueHeaders?: undefined102}103type WithMultiValueHeaders = {104 headers?: undefined105 multiValueHeaders: Record<string, string[]>106}107108export type APIGatewayProxyResult = {109 statusCode: number110 statusDescription?: string111 body: string112 cookies?: string[]113 isBase64Encoded: boolean114} & (WithHeaders | WithMultiValueHeaders)115116const getRequestContext = (117 event: LambdaEvent118):119 | ApiGatewayRequestContext120 | ApiGatewayRequestContextV2121 | ALBRequestContext122 | LatticeRequestContextV2 => {123 return event.requestContext124}125126const streamToNodeStream = async (127 reader: ReadableStreamDefaultReader<Uint8Array>,128 writer: NodeJS.WritableStream129): Promise<void> => {130 let readResult = await reader.read()131 while (!readResult.done) {132 writer.write(readResult.value)133 readResult = await reader.read()134 }135 writer.end()136}137138export const streamHandle = <139 E extends Env = Env,140 S extends Schema = {},141 BasePath extends string = '/',142>(143 app: Hono<E, S, BasePath>144): Handler => {145 // @ts-expect-error awslambda is not a standard API146 return awslambda.streamifyResponse(147 async (event: LambdaEvent, responseStream: NodeJS.WritableStream, context: LambdaContext) => {148 const processor = getProcessor(event)149 try {150 const req = processor.createRequest(event)151 const requestContext = getRequestContext(event)152153 const res = await app.fetch(req, {154 event,155 requestContext,156 context,157 })158159 const headers: Record<string, string> = {}160 const cookies: string[] = []161 res.headers.forEach((value, name) => {162 if (name === 'set-cookie') {163 cookies.push(value)164 } else {165 headers[name] = value166 }167 })168169 // Check content type170 const httpResponseMetadata = {171 statusCode: res.status,172 headers,173 cookies,174 }175176 // Update response stream177 // @ts-expect-error awslambda is not a standard API178 responseStream = awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata)179180 if (res.body) {181 await streamToNodeStream(res.body.getReader(), responseStream)182 } else {183 responseStream.write('')184 }185 } catch (error) {186 console.error('Error processing request:', error)187 responseStream.write('Internal Server Error')188 } finally {189 responseStream.end()190 }191 }192 )193}194195type HandleOptions = {196 isContentTypeBinary: ((contentType: string) => boolean) | undefined197}198199/**200 * Converts a Hono application to an AWS Lambda handler.201 *202 * Accepts events from API Gateway (v1 and v2), Application Load Balancer (ALB),203 * and Lambda Function URLs.204 *205 * @param app - The Hono application instance206 * @param options - Optional configuration207 * @param options.isContentTypeBinary - A function to determine if the content type is binary.208 * If not provided, the default function will be used.209 * @returns Lambda handler function210 *211 * @example212 * ```js213 * import { Hono } from 'hono'214 * import { handle } from 'hono/aws-lambda'215 *216 * const app = new Hono()217 *218 * app.get('/', (c) => c.text('Hello from Lambda'))219 * app.get('/json', (c) => c.json({ message: 'Hello JSON' }))220 *221 * export const handler = handle(app)222 * ```223 *224 * @example225 * ```js226 * // With custom binary content type detection227 * import { handle, defaultIsContentTypeBinary } from 'hono/aws-lambda'228 * export const handler = handle(app, {229 * isContentTypeBinary: (contentType) => {230 * if (defaultIsContentTypeBinary(contentType)) {231 * // default logic same as prior to v4.8.4232 * return true233 * }234 * return contentType.startsWith('image/') || contentType === 'application/pdf'235 * }236 * })237 * ```238 */239export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(240 app: Hono<E, S, BasePath>,241 { isContentTypeBinary }: HandleOptions = { isContentTypeBinary: undefined }242): (<L extends LambdaEvent>(243 event: L,244 lambdaContext?: LambdaContext245) => Promise<246 APIGatewayProxyResult &247 (L extends { multiValueHeaders: Record<string, string[]> }248 ? WithMultiValueHeaders249 : WithHeaders)250>) => {251 // @ts-expect-error FIXME: Fix return typing252 return async (event, lambdaContext?) => {253 const processor = getProcessor(event)254255 let req, requestContext256 try {257 req = processor.createRequest(event)258 requestContext = getRequestContext(event)259 } catch (error) {260 console.error('Error processing request:', error)261 const errorResponse =262 error instanceof TypeError263 ? new Response('Invalid request', { status: 400 })264 : new Response('Internal Server Error', { status: 500 })265 return processor.createResult(event, errorResponse, { isContentTypeBinary })266 }267268 const res = await app.fetch(req, {269 event,270 requestContext,271 lambdaContext,272 })273274 return processor.createResult(event, res, { isContentTypeBinary })275 }276}277278export abstract class EventProcessor<E extends LambdaEvent> {279 protected abstract getPath(event: E): string280281 protected abstract getMethod(event: E): string282283 protected abstract getQueryString(event: E): string284285 protected abstract getHeaders(event: E): Headers286287 protected abstract getCookies(event: E, headers: Headers): void288289 protected abstract setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void290291 protected getHeaderValue(headers: E['headers'], key: string): string | undefined {292 const value = headers293 ? Array.isArray(headers[key])294 ? headers[key][0]295 : headers[key]296 : undefined297298 return value299 }300301 protected getDomainName(event: E): string | undefined {302 if (event.requestContext && 'domainName' in event.requestContext) {303 return event.requestContext.domainName304 }305306 const hostFromHeaders = this.getHeaderValue(event.headers, 'host')307308 if (hostFromHeaders) {309 return hostFromHeaders310 }311312 const multiValueHeaders = 'multiValueHeaders' in event ? event.multiValueHeaders : {}313 const hostFromMultiValueHeaders = this.getHeaderValue(multiValueHeaders, 'host')314315 return hostFromMultiValueHeaders316 }317318 createRequest(event: E): Request {319 const queryString = this.getQueryString(event)320 const domainName = this.getDomainName(event)321 const path = this.getPath(event)322 const urlPath = `https://${domainName}${path}`323 const url = queryString ? `${urlPath}?${queryString}` : urlPath324325 const headers = this.getHeaders(event)326327 const method = this.getMethod(event)328 const requestInit: RequestInit = {329 headers,330 method,331 }332333 if (event.body) {334 requestInit.body = event.isBase64Encoded ? decodeBase64(event.body) : event.body335 }336337 return new Request(url, requestInit)338 }339340 async createResult(341 event: E,342 res: Response,343 options: Pick<HandleOptions, 'isContentTypeBinary'>344 ): Promise<APIGatewayProxyResult> {345 // determine whether the response body should be base64 encoded346 const contentType = res.headers.get('content-type')347 const isContentTypeBinary = options.isContentTypeBinary ?? defaultIsContentTypeBinary // overwrite default function if provided348 let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false349350 if (!isBase64Encoded) {351 const contentEncoding = res.headers.get('content-encoding')352 isBase64Encoded = isContentEncodingBinary(contentEncoding)353 }354355 const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()356357 const result: APIGatewayProxyResult = {358 body: body,359 statusCode: res.status,360 isBase64Encoded,361 ...('multiValueHeaders' in event && event.multiValueHeaders362 ? {363 multiValueHeaders: {},364 }365 : {366 headers: {},367 }),368 }369370 this.setCookies(event, res, result)371 if (result.multiValueHeaders) {372 res.headers.forEach((value, key) => {373 result.multiValueHeaders[key] = [value]374 })375 } else {376 res.headers.forEach((value, key) => {377 result.headers[key] = value378 })379 }380381 return result382 }383384 setCookies(_event: E, res: Response, result: APIGatewayProxyResult) {385 if (res.headers.has('set-cookie')) {386 const cookies = res.headers.getSetCookie387 ? res.headers.getSetCookie()388 : Array.from(res.headers.entries())389 .filter(([k]) => k === 'set-cookie')390 .map(([, v]) => v)391392 if (Array.isArray(cookies)) {393 this.setCookiesToResult(result, cookies)394 res.headers.delete('set-cookie')395 }396 }397 }398}399400export class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {401 protected getPath(event: APIGatewayProxyEventV2): string {402 return event.rawPath403 }404405 protected getMethod(event: APIGatewayProxyEventV2): string {406 return event.requestContext.http.method407 }408409 protected getQueryString(event: APIGatewayProxyEventV2): string {410 return event.rawQueryString411 }412413 protected getCookies(event: APIGatewayProxyEventV2, headers: Headers): void {414 if (Array.isArray(event.cookies)) {415 headers.set('Cookie', event.cookies.join('; '))416 }417 }418419 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {420 result.cookies = cookies421 }422423 protected getHeaders(event: APIGatewayProxyEventV2): Headers {424 const headers = new Headers()425 this.getCookies(event, headers)426 if (event.headers) {427 for (const [k, v] of Object.entries(event.headers)) {428 if (v) {429 headers.set(k, v)430 }431 }432 }433 return headers434 }435}436437const v2Processor: EventV2Processor = new EventV2Processor()438439export class EventV1Processor extends EventProcessor<APIGatewayProxyEvent> {440 protected getPath(event: APIGatewayProxyEvent): string {441 return event.path442 }443444 protected getMethod(event: APIGatewayProxyEvent): string {445 return event.httpMethod446 }447448 protected getQueryString(event: APIGatewayProxyEvent): string {449 // In the case of gateway Integration either queryStringParameters or multiValueQueryStringParameters can be present not both450 // API Gateway passes decoded values, so we need to re-encode them to preserve the original URL451 if (event.multiValueQueryStringParameters) {452 return Object.entries(event.multiValueQueryStringParameters || {})453 .filter(([, value]) => value)454 .map(([key, values]) =>455 values.map((value) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join('&')456 )457 .join('&')458 } else {459 return Object.entries(event.queryStringParameters || {})460 .filter(([, value]) => value)461 .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value || '')}`)462 .join('&')463 }464 }465466 protected getCookies(_event: APIGatewayProxyEvent, _headers: Headers): void {467 // nop468 }469470 protected getHeaders(event: APIGatewayProxyEvent): Headers {471 const headers = new Headers()472 this.getCookies(event, headers)473 if (event.headers) {474 for (const [k, v] of Object.entries(event.headers)) {475 if (v) {476 headers.set(k, sanitizeHeaderValue(v))477 }478 }479 }480 if (event.multiValueHeaders) {481 for (const [k, values] of Object.entries(event.multiValueHeaders)) {482 if (values) {483 // avoid duplicating already set headers484 const foundK = headers.get(k)485 values.forEach((v) => {486 const sanitizedValue = sanitizeHeaderValue(v)487 return (488 (!foundK || !foundK.includes(sanitizedValue)) && headers.append(k, sanitizedValue)489 )490 })491 }492 }493 }494 return headers495 }496497 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {498 result.multiValueHeaders = {499 'set-cookie': cookies,500 }501 }502}503504const v1Processor: EventV1Processor = new EventV1Processor()505506export class ALBProcessor extends EventProcessor<ALBProxyEvent> {507 protected getHeaders(event: ALBProxyEvent): Headers {508 const headers = new Headers()509 // if multiValueHeaders is present the ALB will use it instead of the headers field510 // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers511 if (event.multiValueHeaders) {512 for (const [key, values] of Object.entries(event.multiValueHeaders)) {513 if (values && Array.isArray(values)) {514 // https://www.rfc-editor.org/rfc/rfc9110.html#name-common-rules-for-defining-f515 const sanitizedValue = sanitizeHeaderValue(values.join('; '))516 headers.set(key, sanitizedValue)517 }518 }519 } else {520 for (const [key, value] of Object.entries(event.headers ?? {})) {521 if (value) {522 headers.set(key, sanitizeHeaderValue(value))523 }524 }525 }526 return headers527 }528529 protected getPath(event: ALBProxyEvent): string {530 return event.path531 }532533 protected getMethod(event: ALBProxyEvent): string {534 return event.httpMethod535 }536537 protected getQueryString(event: ALBProxyEvent): string {538 // In the case of ALB Integration either queryStringParameters or multiValueQueryStringParameters can be present not both539 /*540 In other cases like when using the serverless framework, the event object does contain both queryStringParameters and multiValueQueryStringParameters:541 Below is an example event object for this URL: /payment/b8c55e69?select=amount&select=currency542 {543 ...544 queryStringParameters: { select: 'currency' },545 multiValueQueryStringParameters: { select: [ 'amount', 'currency' ] },546 }547 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.548 A simple fix would be to invert the if statement and check the multiValueQueryStringParameters first.549 */550 if (event.multiValueQueryStringParameters) {551 return Object.entries(event.multiValueQueryStringParameters || {})552 .filter(([, value]) => value)553 .map(([key, value]) => `${key}=${value.join(`&${key}=`)}`)554 .join('&')555 } else {556 return Object.entries(event.queryStringParameters || {})557 .filter(([, value]) => value)558 .map(([key, value]) => `${key}=${value}`)559 .join('&')560 }561 }562563 protected getCookies(event: ALBProxyEvent, headers: Headers): void {564 let cookie565 if (event.multiValueHeaders) {566 cookie = event.multiValueHeaders['cookie']?.join('; ')567 } else {568 cookie = event.headers ? event.headers['cookie'] : undefined569 }570 if (cookie) {571 headers.append('Cookie', cookie)572 }573 }574575 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {576 // when multi value headers is enabled577 if (result.multiValueHeaders) {578 result.multiValueHeaders['set-cookie'] = cookies579 } else {580 // otherwise serialize the set-cookie581 result.headers['set-cookie'] = cookies.join(', ')582 }583 }584}585586const albProcessor: ALBProcessor = new ALBProcessor()587588export class LatticeV2Processor extends EventProcessor<LatticeProxyEventV2> {589 protected getPath(event: LatticeProxyEventV2): string {590 return event.path591 }592593 protected getMethod(event: LatticeProxyEventV2): string {594 return event.method595 }596597 protected getQueryString(): string {598 return ''599 }600601 protected getHeaders(event: LatticeProxyEventV2): Headers {602 const headers = new Headers()603604 if (event.headers) {605 for (const [k, values] of Object.entries(event.headers)) {606 if (values) {607 // avoid duplicating already set headers608 const foundK = headers.get(k)609 values.forEach((v) => {610 const sanitizedValue = sanitizeHeaderValue(v)611 return (612 (!foundK || !foundK.includes(sanitizedValue)) && headers.append(k, sanitizedValue)613 )614 })615 }616 }617 }618619 return headers620 }621622 protected getCookies(): void {623 // nop624 }625626 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {627 result.headers = {628 ...result.headers,629 'set-cookie': cookies.join(', '),630 }631 }632}633634const latticeV2Processor: LatticeV2Processor = new LatticeV2Processor()635636export const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {637 if (isProxyEventALB(event)) {638 return albProcessor639 }640 if (isProxyEventV2(event)) {641 return v2Processor642 }643 if (isLatticeEventV2(event)) {644 return latticeV2Processor645 }646647 return v1Processor648}649650const isProxyEventALB = (event: LambdaEvent): event is ALBProxyEvent => {651 if (event.requestContext) {652 return Object.hasOwn(event.requestContext, 'elb')653 }654 return false655}656657const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {658 return Object.hasOwn(event, 'rawPath')659}660661const isLatticeEventV2 = (event: LambdaEvent): event is LatticeProxyEventV2 => {662 if (event.requestContext) {663 return Object.hasOwn(event.requestContext, 'serviceArn')664 }665 return false666}667668/**669 * Check if the given content type is binary.670 * This is a default function and may be overwritten by the user via `isContentTypeBinary` option in handler().671 * @param contentType The content type to check.672 * @returns True if the content type is binary, false otherwise.673 */674export const defaultIsContentTypeBinary = (contentType: string): boolean => {675 return !/^text\/(?:plain|html|css|javascript|csv)|(?:\/|\+)(?:json|xml)\s*(?:;|$)/.test(676 contentType677 )678}679680export const isContentEncodingBinary = (contentEncoding: string | null) => {681 if (contentEncoding === null) {682 return false683 }684 return /^(gzip|deflate|compress|br)/.test(contentEncoding)685}