handler.test.ts
This file
Path
src/adapter/lambda-edge/handler.test.ts
367 lines · 10.9 KiB · TypeScript
Last changed by
fix(lambda-edge): base64 encode content-encoded response bodies (#5099)Yusuke Wadabefore adoption6217f4b
History of this fileTake it
The walk stopped after 200 commits: lines older than f774f8d point at it.
4.12.15Yusuke Wadabefore adoptionf774f8d
lines 1–3why, one step back1import { describe } from 'vitest'2import { setCookie } from '../../helper/cookie'3import { Hono } from '../../hono'Merge commit from forkYusuke Wadabefore adoptionfa5f9bf
line 4why, one step back4import { bodyLimit } from '../../middleware/body-limit'fix(lambda-edge): base64 encode content-encoded response bodies (#5099)Yusuke Wadabefore adoption6217f4b
line 5why, one step back5import { decodeBase64, encodeBase64 } from '../../utils/encode'fix(lambda-edge): resolve the handler with the value passed to the callback (#5094)Yusuke Wadabefore adoption24547a6
line 6why, one step back6import type { Callback, CloudFrontEdgeEvent, CloudFrontRequest } from './handler'4.12.15Yusuke Wadabefore adoptionf774f8d
lines 7–92why, one step back7import { createBody, handle, isContentTypeBinary } from './handler'89describe('isContentTypeBinary', () => {10 it('Should determine whether it is binary', () => {11 expect(isContentTypeBinary('image/png')).toBe(true)12 expect(isContentTypeBinary('font/woff2')).toBe(true)13 expect(isContentTypeBinary('image/svg+xml')).toBe(false)14 expect(isContentTypeBinary('image/svg+xml; charset=UTF-8')).toBe(false)15 expect(isContentTypeBinary('text/plain')).toBe(false)16 expect(isContentTypeBinary('text/plain; charset=UTF-8')).toBe(false)17 expect(isContentTypeBinary('text/css')).toBe(false)18 expect(isContentTypeBinary('text/javascript')).toBe(false)19 expect(isContentTypeBinary('application/json')).toBe(false)20 expect(isContentTypeBinary('application/ld+json')).toBe(false)21 expect(isContentTypeBinary('application/json')).toBe(false)22 })23})2425describe('createBody', () => {26 it('Should the request be a GET or HEAD, the Request must not include a Body', () => {27 const encoder = new TextEncoder()28 const data = encoder.encode('test')29 const body = {30 action: 'read-only',31 data: encodeBase64(data.buffer),32 encoding: 'base64',33 inputTruncated: false,34 }3536 expect(createBody('GET', body)).toEqual(undefined)37 expect(createBody('GET', body)).not.toEqual(data)38 expect(createBody('HEAD', body)).toEqual(undefined)39 expect(createBody('HEAD', body)).not.toEqual(data)40 expect(createBody('POST', body)).toEqual(data)41 expect(createBody('POST', body)).not.toEqual(undefined)42 })43})4445describe('handle', () => {46 const cloudFrontEdgeEvent: CloudFrontEdgeEvent = {47 Records: [48 {49 cf: {50 config: {51 distributionDomainName: 'd111111abcdef8.cloudfront.net',52 distributionId: 'EDFDVBD6EXAMPLE',53 eventType: 'viewer-request',54 requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',55 },56 request: {57 clientIp: '1.2.3.4',58 headers: {59 host: [60 {61 key: 'Host',62 value: 'hono.dev',63 },64 ],65 accept: [66 {67 key: 'accept',68 value: '*/*',69 },70 ],71 },72 method: 'GET',73 querystring: '',74 uri: '/test-path',75 },76 },77 },78 ],79 }8081 it('Should support alternate domain names', async () => {82 const app = new Hono()83 app.get('/test-path', (c) => {84 return c.text(c.req.url)85 })86 const handler = handle(app)8788 const res = await handler(cloudFrontEdgeEvent)8990 expect(res.body).toBe('https://hono.dev/test-path')91 })92Merge commit from forkYusuke Wadabefore adoption3892a6c
lines 93–122why, one step back93 it('Should preserve all values of a multi-value request header', async () => {94 const app = new Hono()95 app.get('/test-path', (c) => c.text(c.req.header('x-forwarded-for') ?? ''))96 const handler = handle(app)9798 const event: CloudFrontEdgeEvent = {99 Records: [100 {101 cf: {102 ...cloudFrontEdgeEvent.Records[0].cf,103 request: {104 ...cloudFrontEdgeEvent.Records[0].cf.request,105 headers: {106 host: [{ key: 'Host', value: 'hono.dev' }],107 'x-forwarded-for': [108 { key: 'X-Forwarded-For', value: '10.0.0.1' },109 { key: 'X-Forwarded-For', value: '192.168.1.1' },110 { key: 'X-Forwarded-For', value: '203.0.113.55' },111 ],112 },113 },114 },115 },116 ],117 }118119 const res = await handler(event)120 expect(res.body).toBe('10.0.0.1, 192.168.1.1, 203.0.113.55')121 })1224.12.15Yusuke Wadabefore adoptionf774f8d
lines 123–184why, one step back123 it('Should expose async handler arity compatible with NODEJS_24_X', () => {124 const app = new Hono()125 const handler = handle(app)126127 expect(handler.length).toBeLessThanOrEqual(2)128 })129130 it('Should preserve positional callback compatibility', async () => {131 type Env = { Bindings: { callback: Callback } }132 const app = new Hono<Env>()133 const callback = vi.fn()134135 app.get('/test-path', (c) => {136 c.env.callback?.(null, {137 status: '200',138 headers: {139 'x-test': [{ key: 'x-test', value: 'ok' }],140 },141 })142 return c.text('ok')143 })144145 const handler = handle(app)146 await handler(cloudFrontEdgeEvent, undefined, callback)147148 expect(callback).toHaveBeenCalledWith(null, {149 status: '200',150 headers: {151 'x-test': [{ key: 'x-test', value: 'ok' }],152 },153 })154 })155156 it('Should support multiple cookies', async () => {157 const app = new Hono()158 app.get('/test-path', (c) => {159 setCookie(c, 'cookie1', 'value1')160 setCookie(c, 'cookie2', 'value2')161 return c.text('')162 })163 const handler = handle(app)164165 const res = await handler(cloudFrontEdgeEvent)166167 expect(res.headers).toEqual({168 'content-type': [169 {170 key: 'content-type',171 value: 'text/plain; charset=UTF-8',172 },173 ],174 'set-cookie': [175 {176 key: 'set-cookie',177 value: 'cookie1=value1; Path=/',178 },179 {180 key: 'set-cookie',181 value: 'cookie2=value2; Path=/',182 },183 ],184 })Merge commit from forkYusuke Wadabefore adoptionfa5f9bf
lines 185–222why, one step back185 })186187 it('Should enforce bodyLimit when the client understates Content-Length', async () => {188 const app = new Hono()189 app.post(190 '/upload',191 bodyLimit({ maxSize: 1024, onError: (c) => c.text('too large', 413) }),192 async (c) => c.json({ received: (await c.req.text()).length })193 )194 const handler = handle(app)195196 const event: CloudFrontEdgeEvent = {197 Records: [198 {199 cf: {200 ...cloudFrontEdgeEvent.Records[0].cf,201 request: {202 ...cloudFrontEdgeEvent.Records[0].cf.request,203 method: 'POST',204 uri: '/upload',205 headers: {206 host: [{ key: 'Host', value: 'hono.dev' }],207 'content-type': [{ key: 'Content-Type', value: 'text/plain' }],208 'content-length': [{ key: 'Content-Length', value: '1' }],209 },210 body: {211 inputTruncated: false,212 action: 'read-only',213 encoding: 'text',214 data: 'A'.repeat(10000),215 },216 },217 },218 },219 ],220 }221222 const res = await handler(event)fix(lambda-edge): resolve the handler with the value passed to the callback (#5094)Yusuke Wadabefore adoption24547a6
lines 223–301why, one step back223 expect(res).toMatchObject({ status: '413' })224 })225226 it('Should resolve with the request passed to the callback for origin forwarding', async () => {227 type Env = { Bindings: { callback: Callback; request: CloudFrontRequest } }228 const app = new Hono<Env>()229 const callback = vi.fn()230231 app.get('*', async (c, next) => {232 await next()233 c.env.callback(null, c.env.request)234 })235236 const handler = handle(app)237 const result = await handler(cloudFrontEdgeEvent, undefined, callback)238239 expect(result).toBe(cloudFrontEdgeEvent.Records[0].cf.request)240 expect(callback).toHaveBeenCalledWith(null, cloudFrontEdgeEvent.Records[0].cf.request)241 })242243 it('Should resolve with the result passed to the callback over the app response', async () => {244 type Env = { Bindings: { callback: Callback } }245 const app = new Hono<Env>()246 const customResult = {247 status: '302',248 headers: {249 location: [{ key: 'location', value: 'https://example.com' }],250 },251 }252253 app.get('/test-path', (c) => {254 c.env.callback(null, customResult)255 return c.text('ok')256 })257258 const handler = handle(app)259 const result = await handler(cloudFrontEdgeEvent)260261 expect(result).toBe(customResult)262 })263264 it('Should only honor the first callback invocation', async () => {265 type Env = { Bindings: { callback: Callback; request: CloudFrontRequest } }266 const app = new Hono<Env>()267268 app.get('/test-path', (c) => {269 c.env.callback(null, c.env.request)270 c.env.callback(null, { status: '500' })271 return c.text('ok')272 })273274 const handler = handle(app)275 const result = await handler(cloudFrontEdgeEvent)276277 expect(result).toBe(cloudFrontEdgeEvent.Records[0].cf.request)278 })279280 it('Should reject when the callback is called with an error', async () => {281 type Env = { Bindings: { callback: Callback } }282 const app = new Hono<Env>()283 const error = new Error('edge failure')284285 app.get('/test-path', (c) => {286 c.env.callback(error)287 return c.text('ok')288 })289290 const handler = handle(app)291292 await expect(handler(cloudFrontEdgeEvent)).rejects.toThrow('edge failure')293 })294295 it('Should resolve with the app response when the callback is not used', async () => {296 const app = new Hono()297 app.get('/test-path', (c) => c.text('normal'))298 const handler = handle(app)299300 const res = await handler(cloudFrontEdgeEvent)301 expect(res).toMatchObject({ status: '200', body: 'normal' })fix(lambda-edge): base64 encode content-encoded response bodies (#5099)Yusuke Wadabefore adoption6217f4b
lines 302–365why, one step back302 })303304 it('Should base64 encode a compressed response with a textual content-type', async () => {305 const payload = new TextEncoder().encode('a'.repeat(100))306 const gzipped = await new Response(307 new Blob([payload]).stream().pipeThrough(new CompressionStream('gzip'))308 ).arrayBuffer()309310 const app = new Hono()311 app.get('/test-path', () => {312 return new Response(gzipped, {313 headers: {314 'content-type': 'text/html; charset=UTF-8',315 'content-encoding': 'gzip',316 },317 })318 })319 const handler = handle(app)320321 const body = encodeBase64(gzipped)322 const res = await handler(cloudFrontEdgeEvent)323324 expect(res).toMatchObject({ bodyEncoding: 'base64', body })325326 const decompressed = await new Response(327 new Blob([decodeBase64(body)]).stream().pipeThrough(new DecompressionStream('gzip'))328 ).text()329 expect(decompressed).toBe('a'.repeat(100))330 })331332 it('Should base64 encode a response with an unknown content-encoding', async () => {333 const app = new Hono()334 app.get('/test-path', (c) => {335 return c.text('zstd bytes', {336 headers: {337 'content-encoding': 'zstd',338 },339 })340 })341 const handler = handle(app)342343 const res = await handler(cloudFrontEdgeEvent)344345 expect(res).toMatchObject({346 bodyEncoding: 'base64',347 body: encodeBase64(new TextEncoder().encode('zstd bytes').buffer),348 })349 })350351 it('Should not base64 encode a response with the identity content-encoding', async () => {352 const app = new Hono()353 app.get('/test-path', (c) => {354 return c.text('plain', {355 headers: {356 'content-encoding': 'identity',357 },358 })359 })360 const handler = handle(app)361362 const res = await handler(cloudFrontEdgeEvent)363364 expect(res).toMatchObject({ body: 'plain' })365 expect(res).not.toHaveProperty('bodyEncoding')4.12.15Yusuke Wadabefore adoptionf774f8d
lines 366–367why, one step back366 })367})