Skip to content
Myr

handler.test.ts

This file

Path

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

450 lines 路 13.4 KiB 路 TypeScript

Last changed by

fix(lambda-edge): fail with a descriptive error on a malformed event (#5358)Md. Kawsar Ahmedbefore adoption6cadf75

History of this file

Take it

1import { describe } from 'vitest'2import { setCookie } from '../../helper/cookie'3import { Hono } from '../../hono'4import { bodyLimit } from '../../middleware/body-limit'5import { decodeBase64, encodeBase64 } from '../../utils/encode'6import type { Callback, CloudFrontEdgeEvent, CloudFrontRequest } from './handler'7import { createBody, handle, isContentTypeBinary } from './handler'89describe('isContentTypeBinary', () => {10  it.each([11    ['image/png', true],12    ['font/woff2', true],13    ['image/svg+xml', false],14    ['image/svg+xml; charset=UTF-8', false],15    ['text/plain', false],16    ['text/plain; charset=UTF-8', false],17    ['text/css', false],18    ['text/javascript', false],19    ['application/json', false],20    ['application/ld+json', false],21    ['application/json', false],22    ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', true],23    ['application/msword', true],24    ['application/epub+zip', true],25    ['application/ld+json', false],26    ['application/vnd.oasis.opendocument.text', true],27    ['application/vnd.apple.installer+xml', true],28    ['application/vnd.apple.installer+xml; charset=UTF-8', true],29    ['application/vnd.mozilla.xul+xml', true],30    ['APPLICATION/VND.APPLE.INSTALLER+XML', true],31    ['APPLICATION/JSON', false],32    ['TEXT/PLAIN', false],33  ])('Should determine whether %s it is binary', (mimeType: string, expected: boolean) => {34    expect(isContentTypeBinary(mimeType)).toBe(expected)35  })36})3738describe('createBody', () => {39  it('Should the request be a GET or HEAD, the Request must not include a Body', () => {40    const encoder = new TextEncoder()41    const data = encoder.encode('test')42    const body = {43      action: 'read-only',44      data: encodeBase64(data.buffer),45      encoding: 'base64',46      inputTruncated: false,47    }4849    expect(createBody('GET', body)).toEqual(undefined)50    expect(createBody('GET', body)).not.toEqual(data)51    expect(createBody('HEAD', body)).toEqual(undefined)52    expect(createBody('HEAD', body)).not.toEqual(data)53    expect(createBody('POST', body)).toEqual(data)54    expect(createBody('POST', body)).not.toEqual(undefined)55  })56})5758describe('handle', () => {59  const cloudFrontEdgeEvent: CloudFrontEdgeEvent = {60    Records: [61      {62        cf: {63          config: {64            distributionDomainName: 'd111111abcdef8.cloudfront.net',65            distributionId: 'EDFDVBD6EXAMPLE',66            eventType: 'viewer-request',67            requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',68          },69          request: {70            clientIp: '1.2.3.4',71            headers: {72              host: [73                {74                  key: 'Host',75                  value: 'hono.dev',76                },77              ],78              accept: [79                {80                  key: 'accept',81                  value: '*/*',82                },83              ],84            },85            method: 'GET',86            querystring: '',87            uri: '/test-path',88          },89        },90      },91    ],92  }9394  it('Should support alternate domain names', async () => {95    const app = new Hono()96    app.get('/test-path', (c) => {97      return c.text(c.req.url)98    })99    const handler = handle(app)100101    const res = await handler(cloudFrontEdgeEvent)102103    expect(res.body).toBe('https://hono.dev/test-path')104  })105106  it('Should preserve all values of a multi-value request header', async () => {107    const app = new Hono()108    app.get('/test-path', (c) => c.text(c.req.header('x-forwarded-for') ?? ''))109    const handler = handle(app)110111    const event: CloudFrontEdgeEvent = {112      Records: [113        {114          cf: {115            ...cloudFrontEdgeEvent.Records[0].cf,116            request: {117              ...cloudFrontEdgeEvent.Records[0].cf.request,118              headers: {119                host: [{ key: 'Host', value: 'hono.dev' }],120                'x-forwarded-for': [121                  { key: 'X-Forwarded-For', value: '10.0.0.1' },122                  { key: 'X-Forwarded-For', value: '192.168.1.1' },123                  { key: 'X-Forwarded-For', value: '203.0.113.55' },124                ],125              },126            },127          },128        },129      ],130    }131132    const res = await handler(event)133    expect(res.body).toBe('10.0.0.1, 192.168.1.1, 203.0.113.55')134  })135136  it('Should expose async handler arity compatible with NODEJS_24_X', () => {137    const app = new Hono()138    const handler = handle(app)139140    expect(handler.length).toBeLessThanOrEqual(2)141  })142143  it('Should preserve positional callback compatibility', async () => {144    type Env = { Bindings: { callback: Callback } }145    const app = new Hono<Env>()146    const callback = vi.fn()147148    app.get('/test-path', (c) => {149      c.env.callback?.(null, {150        status: '200',151        headers: {152          'x-test': [{ key: 'x-test', value: 'ok' }],153        },154      })155      return c.text('ok')156    })157158    const handler = handle(app)159    await handler(cloudFrontEdgeEvent, undefined, callback)160161    expect(callback).toHaveBeenCalledWith(null, {162      status: '200',163      headers: {164        'x-test': [{ key: 'x-test', value: 'ok' }],165      },166    })167  })168169  it('Should support multiple cookies', async () => {170    const app = new Hono()171    app.get('/test-path', (c) => {172      setCookie(c, 'cookie1', 'value1')173      setCookie(c, 'cookie2', 'value2')174      return c.text('')175    })176    const handler = handle(app)177178    const res = await handler(cloudFrontEdgeEvent)179180    expect(res.headers).toEqual({181      'content-type': [182        {183          key: 'content-type',184          value: 'text/plain; charset=UTF-8',185        },186      ],187      'set-cookie': [188        {189          key: 'set-cookie',190          value: 'cookie1=value1; Path=/',191        },192        {193          key: 'set-cookie',194          value: 'cookie2=value2; Path=/',195        },196      ],197    })198  })199200  it('Should enforce bodyLimit when the client understates Content-Length', async () => {201    const app = new Hono()202    app.post(203      '/upload',204      bodyLimit({ maxSize: 1024, onError: (c) => c.text('too large', 413) }),205      async (c) => c.json({ received: (await c.req.text()).length })206    )207    const handler = handle(app)208209    const event: CloudFrontEdgeEvent = {210      Records: [211        {212          cf: {213            ...cloudFrontEdgeEvent.Records[0].cf,214            request: {215              ...cloudFrontEdgeEvent.Records[0].cf.request,216              method: 'POST',217              uri: '/upload',218              headers: {219                host: [{ key: 'Host', value: 'hono.dev' }],220                'content-type': [{ key: 'Content-Type', value: 'text/plain' }],221                'content-length': [{ key: 'Content-Length', value: '1' }],222              },223              body: {224                inputTruncated: false,225                action: 'read-only',226                encoding: 'text',227                data: 'A'.repeat(10000),228              },229            },230          },231        },232      ],233    }234235    const res = await handler(event)236    expect(res).toMatchObject({ status: '413' })237  })238239  it('Should resolve with the request passed to the callback for origin forwarding', async () => {240    type Env = { Bindings: { callback: Callback; request: CloudFrontRequest } }241    const app = new Hono<Env>()242    const callback = vi.fn()243244    app.get('*', async (c, next) => {245      await next()246      c.env.callback(null, c.env.request)247    })248249    const handler = handle(app)250    const result = await handler(cloudFrontEdgeEvent, undefined, callback)251252    expect(result).toBe(cloudFrontEdgeEvent.Records[0].cf.request)253    expect(callback).toHaveBeenCalledWith(null, cloudFrontEdgeEvent.Records[0].cf.request)254  })255256  it('Should resolve with the result passed to the callback over the app response', async () => {257    type Env = { Bindings: { callback: Callback } }258    const app = new Hono<Env>()259    const customResult = {260      status: '302',261      headers: {262        location: [{ key: 'location', value: 'https://example.com' }],263      },264    }265266    app.get('/test-path', (c) => {267      c.env.callback(null, customResult)268      return c.text('ok')269    })270271    const handler = handle(app)272    const result = await handler(cloudFrontEdgeEvent)273274    expect(result).toBe(customResult)275  })276277  it('Should only honor the first callback invocation', async () => {278    type Env = { Bindings: { callback: Callback; request: CloudFrontRequest } }279    const app = new Hono<Env>()280281    app.get('/test-path', (c) => {282      c.env.callback(null, c.env.request)283      c.env.callback(null, { status: '500' })284      return c.text('ok')285    })286287    const handler = handle(app)288    const result = await handler(cloudFrontEdgeEvent)289290    expect(result).toBe(cloudFrontEdgeEvent.Records[0].cf.request)291  })292293  it('Should reject when the callback is called with an error', async () => {294    type Env = { Bindings: { callback: Callback } }295    const app = new Hono<Env>()296    const error = new Error('edge failure')297298    app.get('/test-path', (c) => {299      c.env.callback(error)300      return c.text('ok')301    })302303    const handler = handle(app)304305    await expect(handler(cloudFrontEdgeEvent)).rejects.toThrow('edge failure')306  })307308  it('Should resolve with the app response when the callback is not used', async () => {309    const app = new Hono()310    app.get('/test-path', (c) => c.text('normal'))311    const handler = handle(app)312313    const res = await handler(cloudFrontEdgeEvent)314    expect(res).toMatchObject({ status: '200', body: 'normal' })315  })316317  it('Should base64 encode a compressed response with a textual content-type', async () => {318    const payload = new TextEncoder().encode('a'.repeat(100))319    const gzipped = await new Response(320      new Blob([payload]).stream().pipeThrough(new CompressionStream('gzip'))321    ).arrayBuffer()322323    const app = new Hono()324    app.get('/test-path', () => {325      return new Response(gzipped, {326        headers: {327          'content-type': 'text/html; charset=UTF-8',328          'content-encoding': 'gzip',329        },330      })331    })332    const handler = handle(app)333334    const body = encodeBase64(gzipped)335    const res = await handler(cloudFrontEdgeEvent)336337    expect(res).toMatchObject({ bodyEncoding: 'base64', body })338339    const decompressed = await new Response(340      new Blob([decodeBase64(body)]).stream().pipeThrough(new DecompressionStream('gzip'))341    ).text()342    expect(decompressed).toBe('a'.repeat(100))343  })344345  it('Should base64 encode a response with an unknown content-encoding', async () => {346    const app = new Hono()347    app.get('/test-path', (c) => {348      return c.text('zstd bytes', {349        headers: {350          'content-encoding': 'zstd',351        },352      })353    })354    const handler = handle(app)355356    const res = await handler(cloudFrontEdgeEvent)357358    expect(res).toMatchObject({359      bodyEncoding: 'base64',360      body: encodeBase64(new TextEncoder().encode('zstd bytes').buffer),361    })362  })363364  it('Should not base64 encode a response with the identity content-encoding', async () => {365    const app = new Hono()366    app.get('/test-path', (c) => {367      return c.text('plain', {368        headers: {369          'content-encoding': 'identity',370        },371      })372    })373    const handler = handle(app)374375    const res = await handler(cloudFrontEdgeEvent)376377    expect(res).toMatchObject({ body: 'plain' })378    expect(res).not.toHaveProperty('bodyEncoding')379  })380})381382describe('handle with a malformed event', () => {383  const invalidEventMessage =384    'Unable to map the CloudFront event to a Request: expected `Records[0].cf.request` in the Lambda@Edge event.'385386  it('Should reject with a descriptive error when Records holds no CloudFront record', async () => {387    const app = new Hono()388    const handler = handle(app)389390    // The payload the AWS Lambda console prefills is an array of dummy ids.391    const event = { Records: ['foo', 'bar'] } as unknown as CloudFrontEdgeEvent392393    await expect(handler(event)).rejects.toThrow(TypeError)394    await expect(handler(event)).rejects.toThrow(invalidEventMessage)395  })396397  it('Should reject with a descriptive error when Records is empty or absent', async () => {398    const app = new Hono()399    const handler = handle(app)400401    for (const event of [{ Records: [] }, {}] as unknown as CloudFrontEdgeEvent[]) {402      await expect(handler(event)).rejects.toThrow(invalidEventMessage)403    }404  })405406  it('Should reject with a descriptive error when cf carries no request', async () => {407    const app = new Hono()408    const handler = handle(app)409410    const event = {411      Records: [{ cf: { config: { distributionDomainName: 'd111111abcdef8.cloudfront.net' } } }],412    } as unknown as CloudFrontEdgeEvent413414    await expect(handler(event)).rejects.toThrow(invalidEventMessage)415  })416417  it('Should fall back to the distribution domain name when the request has no headers', async () => {418    const app = new Hono()419    app.get('/test-path', (c) => c.text(c.req.url))420    const handler = handle(app)421422    const event = {423      Records: [424        {425          cf: {426            config: {427              distributionDomainName: 'd111111abcdef8.cloudfront.net',428              distributionId: 'EDFDVBD6EXAMPLE',429              eventType: 'viewer-request',430              requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',431            },432            request: {433              clientIp: '1.2.3.4',434              method: 'GET',435              querystring: '',436              uri: '/test-path',437            },438          },439        },440      ],441    } as unknown as CloudFrontEdgeEvent442443    const res = await handler(event)444445    expect(res).toMatchObject({446      status: '200',447      body: 'https://d111111abcdef8.cloudfront.net/test-path',448    })449  })450})