Skip to content
Myr

handler.test.ts

This file

Path

src/adapter/aws-lambda/handler.test.ts

678 lines · 21.4 KiB · TypeScript

Last changed by

fix(aws-lambda): preserve empty query parameters (#5292)Ersa Oktavian Ramadanbefore adoption28e8572

History of this file

Take it

1import { setCookie } from '../../helper/cookie'2import { Hono } from '../../hono'3import { bodyLimit } from '../../middleware/body-limit'4import type { APIGatewayProxyEventV2, LambdaEvent, LatticeProxyEventV2 } from './handler'5import {6  getProcessor,7  handle,8  isContentEncodingBinary,9  defaultIsContentTypeBinary,10} from './handler'11import type { ApiGatewayRequestContextV2 } from './types'1213// Base event objects to reduce duplication14const baseV1Event: LambdaEvent = {15  version: '1.0',16  resource: '/my/path',17  path: '/my/path',18  httpMethod: 'GET',19  headers: {},20  multiValueHeaders: {},21  queryStringParameters: {},22  requestContext: {23    accountId: '123456789012',24    apiId: 'id',25    authorizer: { claims: null, scopes: null },26    domainName: 'id.execute-api.us-east-1.amazonaws.com',27    domainPrefix: 'id',28    extendedRequestId: 'request-id',29    httpMethod: 'GET',30    identity: {31      sourceIp: '192.0.2.1',32      userAgent: 'user-agent',33      clientCert: {34        clientCertPem: 'CERT_CONTENT',35        subjectDN: 'www.example.com',36        issuerDN: 'Example issuer',37        serialNumber: 'a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1',38        validity: {39          notBefore: 'May 28 12:30:02 2019 GMT',40          notAfter: 'Aug  5 09:36:04 2021 GMT',41        },42      },43    },44    path: '/my/path',45    protocol: 'HTTP/1.1',46    requestId: 'id=',47    requestTime: '04/Mar/2020:19:15:17 +0000',48    requestTimeEpoch: 1583349317135,49    resourcePath: '/my/path',50    stage: '$default',51  },52  pathParameters: {},53  stageVariables: {},54  body: null,55  isBase64Encoded: false,56}5758const baseV2Event: LambdaEvent = {59  version: '2.0',60  routeKey: '$default',61  rawPath: '/my/path',62  rawQueryString: '',63  cookies: [],64  headers: {},65  queryStringParameters: {},66  requestContext: {67    accountId: '123456789012',68    apiId: 'api-id',69    authentication: null,70    authorizer: {},71    domainName: 'id.execute-api.us-east-1.amazonaws.com',72    domainPrefix: 'id',73    http: {74      method: 'POST',75      path: '/my/path',76      protocol: 'HTTP/1.1',77      sourceIp: '192.0.2.1',78      userAgent: 'agent',79    },80    requestId: 'id',81    routeKey: '$default',82    stage: '$default',83    time: '12/Mar/2020:19:03:58 +0000',84    timeEpoch: 1583348638390,85  },86  body: null,87  pathParameters: {},88  isBase64Encoded: false,89  stageVariables: {},90}9192describe('isContentTypeBinary', () => {93  it.each([94    ['image/png', true],95    ['font/woff2', true],96    ['image/svg+xml', false],97    ['image/svg+xml; charset=UTF-8', false],98    ['text/plain', false],99    ['text/plain; charset=UTF-8', false],100    ['text/css', false],101    ['text/javascript', false],102    ['application/json', false],103    ['application/ld+json', false],104    ['application/json', false],105    ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', true],106    ['application/msword', true],107    ['application/epub+zip', true],108    ['application/ld+json', false],109    ['application/vnd.oasis.opendocument.text', true],110    ['application/vnd.apple.installer+xml', true],111    ['application/vnd.apple.installer+xml; charset=UTF-8', true],112    ['application/vnd.mozilla.xul+xml', true],113    ['APPLICATION/VND.APPLE.INSTALLER+XML', true],114    ['APPLICATION/JSON', false],115    ['TEXT/PLAIN', false],116  ])('Should determine whether %s it is binary', (mimeType: string, expected: boolean) => {117    expect(defaultIsContentTypeBinary(mimeType)).toBe(expected)118  })119})120121describe('isContentEncodingBinary', () => {122  it('Should determine whether it is compressed', () => {123    expect(isContentEncodingBinary('gzip')).toBe(true)124    expect(isContentEncodingBinary('compress')).toBe(true)125    expect(isContentEncodingBinary('deflate')).toBe(true)126    expect(isContentEncodingBinary('br')).toBe(true)127    expect(isContentEncodingBinary('deflate, gzip')).toBe(true)128    expect(isContentEncodingBinary('zstd')).toBe(true)129    expect(isContentEncodingBinary('')).toBe(false)130    expect(isContentEncodingBinary('identity')).toBe(false)131    expect(isContentEncodingBinary(null)).toBe(false)132  })133})134135describe('EventProcessor.createResult with contentTypesAsBinary', () => {136  const event = baseV1Event137138  it('Should encode as base64 when content-type is in contentTypesAsBinary array', async () => {139    const processor = getProcessor(event)140    const response = new Response('test content', {141      headers: { 'content-type': 'application/custom' },142    })143144    const result = await processor.createResult(event, response, {145      isContentTypeBinary: (contentType: string) => contentType === 'application/custom',146    })147148    expect(result.isBase64Encoded).toBe(true)149    expect(result.body).toBe('dGVzdCBjb250ZW50')150  })151152  it('Should not encode as base64 when content-type is not in isContentTypeBinary array', async () => {153    const processor = getProcessor(event)154    const response = new Response('test content', {155      headers: { 'content-type': 'application/json' },156    })157158    const result = await processor.createResult(event, response, {159      isContentTypeBinary: (contentType: string) => contentType === 'application/custom',160    })161162    expect(result.isBase64Encoded).toBe(false)163    expect(result.body).toBe('test content')164  })165166  it('Should use defaultIsContentTypeBinary when isContentTypeBinary is undefined with binary content', async () => {167    const processor = getProcessor(event)168    const response = new Response('test image content', {169      headers: { 'content-type': 'image/png' },170    })171172    // Pass undefined for isContentTypeBinary to test default behavior173    const result = await processor.createResult(event, response, {174      isContentTypeBinary: undefined,175    })176177    expect(result.isBase64Encoded).toBe(true)178    expect(result.body).toBe('dGVzdCBpbWFnZSBjb250ZW50')179  })180181  it('Should use defaultIsContentTypeBinary when isContentTypeBinary is undefined with non-binary content', async () => {182    const processor = getProcessor(event)183    const response = new Response('test text content', {184      headers: { 'content-type': 'text/plain' },185    })186187    // Pass undefined for isContentTypeBinary to test default behavior188    const result = await processor.createResult(event, response, {189      isContentTypeBinary: undefined,190    })191192    expect(result.isBase64Encoded).toBe(false)193    expect(result.body).toBe('test text content')194  })195})196197describe('EventProcessor.createRequest', () => {198  it('Should preserve percent-encoded values in query string for version 1.0', () => {199    const event: LambdaEvent = {200      ...baseV1Event,201      // API Gateway provides decoded values202      multiValueQueryStringParameters: {203        path: ['/book/{bookId}/'], // Originally %7BbookId%7D204        name: ['John Doe'], // Originally John%20Doe205        tag: ['日本語'], // Originally %E6%97%A5%E6%9C%AC%E8%AA%9E206      },207    }208209    const processor = getProcessor(event)210    const request = processor.createRequest(event)211212    // URL should contain properly encoded values213    expect(request.url).toEqual(214      'https://id.execute-api.us-east-1.amazonaws.com/my/path?path=%2Fbook%2F%7BbookId%7D%2F&name=John%20Doe&tag=%E6%97%A5%E6%9C%AC%E8%AA%9E'215    )216  })217218  it('Should handle special characters correctly in queryStringParameters for version 1.0', () => {219    const event: LambdaEvent = {220      ...baseV1Event,221      queryStringParameters: {222        'key with spaces': 'value with spaces',223        'special!@#$%^&*()': 'chars!@#$%^&*()',224        equals: 'a=b=c',225        ampersand: 'a&b&c',226      },227    }228229    const processor = getProcessor(event)230    const request = processor.createRequest(event)231232    // Verify the URL is properly encoded233    const url = new URL(request.url)234    expect(url.searchParams.get('key with spaces')).toBe('value with spaces')235    expect(url.searchParams.get('special!@#$%^&*()')).toBe('chars!@#$%^&*()')236    expect(url.searchParams.get('equals')).toBe('a=b=c')237    expect(url.searchParams.get('ampersand')).toBe('a&b&c')238  })239240  it('Should preserve empty query parameters for version 1.0', () => {241    const event: LambdaEvent = {242      ...baseV1Event,243      queryStringParameters: {244        empty: '',245        present: '0',246        omitted: undefined,247      },248    }249250    const request = getProcessor(event).createRequest(event)251252    expect(request.url).toBe(253      'https://id.execute-api.us-east-1.amazonaws.com/my/path?empty=&present=0'254    )255  })256257  it('Should preserve empty query parameters for ALB events', () => {258    const event: LambdaEvent = {259      httpMethod: 'GET',260      path: '/my/path',261      headers: { host: 'example.test' },262      body: null,263      isBase64Encoded: false,264      queryStringParameters: {265        empty: '',266        present: '0',267        omitted: undefined,268      },269      requestContext: {270        elb: { targetGroupArn: 'arn:aws:elasticloadbalancing:...' },271      },272    }273274    const request = getProcessor(event).createRequest(event)275276    expect(request.url).toBe('https://example.test/my/path?empty=&present=0')277  })278279  it('Should return valid Request object from version 1.0 API Gateway event', () => {280    const event: LambdaEvent = {281      ...baseV1Event,282      headers: {283        'content-type': 'application/json',284        header1: 'value1',285        header2: 'value1',286      },287      multiValueHeaders: {288        header1: ['value1'],289        header2: ['value1', 'value2', 'value3'],290      },291      // This value doesn't match multi value's content.292      // We want to assert handler is using the multi value's content when both are available.293      queryStringParameters: {294        parameter2: 'value',295      },296      multiValueQueryStringParameters: {297        parameter1: ['value1', 'value2'],298        parameter2: ['value'],299      },300    }301302    const processor = getProcessor(event)303    const request = processor.createRequest(event)304305    expect(request.method).toEqual('GET')306    // Note: Values are now properly encoded307    expect(request.url).toEqual(308      'https://id.execute-api.us-east-1.amazonaws.com/my/path?parameter1=value1&parameter1=value2&parameter2=value'309    )310    expect(Object.fromEntries(request.headers)).toEqual({311      'content-type': 'application/json',312      header1: 'value1',313      header2: 'value1, value2, value3',314    })315  })316317  it('Should preserve every repeated header value for version 1.0 API Gateway event', () => {318    const event: LambdaEvent = {319      ...baseV1Event,320      headers: {321        'x-forwarded-for': '203.0.113.10',322      },323      multiValueHeaders: {324        'x-forwarded-for': ['203.0.113.1', '203.0.113.10'],325      },326    }327328    const processor = getProcessor(event)329    const request = processor.createRequest(event)330331    expect(request.headers.get('x-forwarded-for')).toEqual('203.0.113.1, 203.0.113.10')332  })333334  it('Should return valid Request object from version 2.0 API Gateway event', () => {335    const event: LambdaEvent = {336      ...baseV2Event,337      rawQueryString: 'parameter1=value1&parameter1=value2&parameter2=value',338      cookies: ['cookie1', 'cookie2'],339      headers: {340        'content-type': 'application/json',341        header1: 'value1',342        header2: 'value1,value2',343      },344      queryStringParameters: {345        parameter1: 'value1,value2',346        parameter2: 'value',347      },348      body: 'Hello from Lambda',349      pathParameters: {350        parameter1: 'value1',351      },352      stageVariables: {353        stageVariable1: 'value1',354        stageVariable2: 'value2',355      },356    }357358    const processor = getProcessor(event)359    const request = processor.createRequest(event)360361    expect(request.method).toEqual('POST')362    expect(request.url).toEqual(363      'https://id.execute-api.us-east-1.amazonaws.com/my/path?parameter1=value1&parameter1=value2&parameter2=value'364    )365    expect(Object.fromEntries(request.headers)).toEqual({366      'content-length': '17',367      'content-type': 'application/json',368      cookie: 'cookie1; cookie2',369      header1: 'value1',370      header2: 'value1,value2',371    })372  })373374  it('Should return valid Request object from version 2.0 Lattice event', async () => {375    const event: LatticeProxyEventV2 = {376      version: '2.0',377      // query string parameters from the path take precedence over the explicit notation below378      path: '/my/path?parameter1=value1&parameter1=value2&parameter2=value',379      method: 'POST',380      headers: {381        cookie: ['cookie1=value1; cookie2=value2'],382        'content-type': ['application/x-www-form-urlencoded'],383        header1: ['value1'],384        header2: ['value1', 'value2'],385        host: ['my-service-a1b2c3.x1y2z3.vpc-lattice-svcs.us-east-1.on.aws'],386      },387      queryStringParameters: {388        parameter1: ['value1', 'value2'],389        parameter2: ['value'],390      },391      body: 'SGVsbG8gZnJvbSBMYW1iZGE=',392      isBase64Encoded: true,393      requestContext: {394        serviceNetworkArn: '',395        serviceArn: '',396        targetGroupArn: '',397        identity: {},398        region: 'us-east-1',399        timeEpoch: '1583348638390123',400      },401    }402403    const processor = getProcessor(event)404    const request = processor.createRequest(event)405406    expect(await request.text()).toEqual('Hello from Lambda')407    expect(request.method).toEqual('POST')408    expect(request.url).toEqual(409      'https://my-service-a1b2c3.x1y2z3.vpc-lattice-svcs.us-east-1.on.aws/my/path?parameter1=value1&parameter1=value2&parameter2=value'410    )411    expect(Object.fromEntries(request.headers)).toEqual({412      'content-length': '17',413      'content-type': 'application/x-www-form-urlencoded',414      cookie: 'cookie1=value1; cookie2=value2',415      header1: 'value1',416      header2: 'value1, value2',417      host: 'my-service-a1b2c3.x1y2z3.vpc-lattice-svcs.us-east-1.on.aws',418    })419  })420421  it('Should preserve every repeated header value for Lattice event', async () => {422    const event: LatticeProxyEventV2 = {423      version: '2.0',424      path: '/my/path',425      method: 'GET',426      headers: {427        host: ['example.test'],428        'x-forwarded-for': ['203.0.113.1', '203.0.113.10'],429      },430      queryStringParameters: {},431      body: null,432      isBase64Encoded: false,433      requestContext: {434        serviceNetworkArn: '',435        serviceArn: '',436        targetGroupArn: '',437        identity: {},438        region: 'us-east-1',439        timeEpoch: '1583348638390123',440      },441    }442443    const processor = getProcessor(event)444    const request = processor.createRequest(event)445446    expect(request.headers.get('x-forwarded-for')).toEqual('203.0.113.1, 203.0.113.10')447  })448449  describe('non-ASCII header value processing', () => {450    it('Should encode non-ASCII header values with encodeURIComponent', async () => {451      const event: LambdaEvent = {452        ...baseV1Event,453        headers: {454          'x-city': '炎', // Non-ASCII character455        },456      }457458      const processor = getProcessor(event)459      const request = processor.createRequest(event)460461      const xCity = request.headers.get('x-city') ?? ''462      expect(decodeURIComponent(xCity)).toBe('炎')463    })464  })465})466467describe('handle', () => {468  it('Should route a V1 REST event by its path even when a base path mapping adds rawPath', async () => {469    const app = new Hono()470    app.get('/my/path', (c) => c.text('Hello'))471    const handler = handle(app)472473    // A custom domain base path mapping makes API Gateway add a `rawPath` to the474    // V1 (REST API) event, holding the path before the mapping was stripped. The475    // event is still V1: it carries `path` and a V1 request context with no `http`.476    const event: LambdaEvent = {477      ...baseV1Event,478      rawPath: '/base/my/path',479    }480481    const result = await handler(event)482    expect(result.statusCode).toBe(200)483    expect(result.body).toBe('Hello')484  })485486  it('Should return 400 when request contains invalid header names (v2)', async () => {487    const app = new Hono()488    app.get('/my/path', (c) => c.text('Hello'))489    const handler = handle(app)490491    const event: LambdaEvent = {492      ...baseV2Event,493      headers: {494        'valid-header': 'value',495        'a"a': 'invalid header name',496      },497      requestContext: {498        ...baseV2Event.requestContext,499        http: {500          method: 'GET',501          path: '/my/path',502          protocol: 'HTTP/1.1',503          sourceIp: '192.0.2.1',504          userAgent: 'agent',505        },506      },507    }508509    const result = await handler(event)510    expect(result.statusCode).toBe(400)511    expect(result.body).toBe('Invalid request')512  })513514  it('ALB single-header: emits the first Set-Cookie intact, never comma-joined', async () => {515    const app = new Hono()516    app.get('/multi-cookie', (c) => {517      setCookie(c, 'session', 'abc123', { expires: new Date('2026-06-09T00:00:00Z') })518      setCookie(c, 'csrf', 'xyz789', { expires: new Date('2026-06-10T00:00:00Z') })519      return c.text('ok')520    })521    const handler = handle(app)522523    const event = {524      httpMethod: 'GET',525      path: '/multi-cookie',526      headers: { host: 'app.example.com' },527      body: null,528      isBase64Encoded: false,529      requestContext: { elb: { targetGroupArn: 'arn:aws:elasticloadbalancing:...' } },530    } as unknown as LambdaEvent531532    const result = await handler(event)533534    expect(result.headers!['set-cookie']).toBe(535      'session=abc123; Path=/; Expires=Tue, 09 Jun 2026 00:00:00 GMT'536    )537  })538539  it('Lattice v2: emits multiple Set-Cookie as an array', async () => {540    const app = new Hono()541    app.get('/multi-cookie', (c) => {542      setCookie(c, 'session', 'abc123')543      setCookie(c, 'csrf', 'xyz789')544      return c.text('ok')545    })546    const handler = handle(app)547548    const event: LatticeProxyEventV2 = {549      version: '2.0',550      path: '/multi-cookie',551      method: 'GET',552      headers: { host: ['app.example.com'] },553      queryStringParameters: {},554      body: null,555      isBase64Encoded: false,556      requestContext: {557        serviceNetworkArn: '',558        serviceArn: 'arn:aws:vpc-lattice:us-east-1:123456789012:service/svc-0a40',559        targetGroupArn: '',560        identity: {},561        region: 'us-east-1',562        timeEpoch: '1583348638390123',563      },564    }565566    const result = await handler(event)567568    expect(result.headers!['set-cookie']).toEqual(['session=abc123; Path=/', 'csrf=xyz789; Path=/'])569  })570571  it('Should return 400 when request contains invalid header names (v1)', async () => {572    const app = new Hono()573    app.get('/my/path', (c) => c.text('Hello'))574    const handler = handle(app)575576    const event: LambdaEvent = {577      ...baseV1Event,578      headers: {579        'a"a': 'invalid header name',580      },581      multiValueHeaders: {582        'a"a': ['invalid header name'],583      },584    }585586    const result = await handler(event)587    expect(result.statusCode).toBe(400)588    expect(result.body).toBe('Invalid request')589  })590591  it('Should enforce bodyLimit when the client understates Content-Length', async () => {592    const app = new Hono()593    app.post(594      '/upload',595      bodyLimit({ maxSize: 1024, onError: (c) => c.text('too large', 413) }),596      async (c) => c.json({ received: (await c.req.text()).length })597    )598    const handler = handle(app)599600    const event: LambdaEvent = {601      ...baseV2Event,602      rawPath: '/upload',603      headers: { 'content-type': 'text/plain', 'content-length': '1' },604      body: 'A'.repeat(10000),605      requestContext: {606        ...baseV2Event.requestContext,607        http: {608          method: 'POST',609          path: '/upload',610          protocol: 'HTTP/1.1',611          sourceIp: '192.0.2.1',612          userAgent: 'agent',613        },614      },615    }616617    const result = await handler(event)618    expect(result.statusCode).toBe(413)619  })620})621622describe('V2 request context authorizer', () => {623  const baseV2RequestContext = baseV2Event.requestContext as ApiGatewayRequestContextV2624625  it('Should expose the context of a Lambda (REQUEST) authorizer', async () => {626    const app = new Hono<{ Bindings: { event: APIGatewayProxyEventV2 } }>()627    app.get('/my/path', (c) => c.json(c.env.event.requestContext.authorizer.lambda))628    const handler = handle(app)629630    const event: LambdaEvent = {631      ...baseV2Event,632      requestContext: {633        ...baseV2RequestContext,634        http: { ...baseV2RequestContext.http, method: 'GET' },635        authorizer: { lambda: { userId: 'user-123', isAdmin: true } },636      },637    }638639    const result = await handler(event)640    expect(result.statusCode).toBe(200)641    expect(JSON.parse(result.body)).toEqual({ userId: 'user-123', isAdmin: true })642  })643644  it('Should expose the claims and scopes of a JWT authorizer', async () => {645    const app = new Hono<{ Bindings: { event: APIGatewayProxyEventV2 } }>()646    app.get('/my/path', (c) => c.json(c.env.event.requestContext.authorizer.jwt))647    const handler = handle(app)648649    const event: LambdaEvent = {650      ...baseV2Event,651      requestContext: {652        ...baseV2RequestContext,653        http: { ...baseV2RequestContext.http, method: 'GET' },654        authorizer: {655          jwt: { claims: { sub: 'user-123', email_verified: true }, scopes: ['read'] },656        },657      },658    }659660    const result = await handler(event)661    expect(result.statusCode).toBe(200)662    expect(JSON.parse(result.body)).toEqual({663      claims: { sub: 'user-123', email_verified: true },664      scopes: ['read'],665    })666  })667668  it('Should type each authorizer variant as optional', () => {669    const authorizer: ApiGatewayRequestContextV2['authorizer'] = {}670    expectTypeOf(authorizer.lambda).toEqualTypeOf<Record<string, unknown> | null | undefined>()671    expectTypeOf(authorizer.jwt).toEqualTypeOf<672      | { claims: Record<string, string | number | boolean | string[]>; scopes: string[] | null }673      | undefined674    >()675    // A JWT authorizer reports no scopes as `null`.676    expectTypeOf<null>().toMatchTypeOf<NonNullable<typeof authorizer.jwt>['scopes']>()677  })678})