Skip to content
Myr

handler.test.ts

This file

Path

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

509 lines · 15.8 KiB · TypeScript

Last changed by

Merge commit from forkYusuke Wadabefore adoptionfa5f9bf

History of this file

Take it

The walk stopped after 200 commits: lines older than 3a550d2 point at it.

Merge commit from forkYusuke Wadabefore adoption7ae7cba

line 1why, one step back
1import { setCookie } from '../../helper/cookie'

fix(aws-lambda): handle invalid header names in request processing (#4883)Yusuke Wadabefore adoptionfa2c74f

line 2why, one step back
2import { Hono } from '../../hono'

Merge commit from forkYusuke Wadabefore adoptionfa5f9bf

line 3why, one step back
3import { bodyLimit } from '../../middleware/body-limit'

feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0

line 4why, one step back
4import type { LambdaEvent, LatticeProxyEventV2 } from './handler'

fix(aws-lambda): handle invalid header names in request processing (#4883)Yusuke Wadabefore adoptionfa2c74f

lines 5–10why, one step back
5import {
6 getProcessor,7 handle,8 isContentEncodingBinary,9 defaultIsContentTypeBinary,10} from './handler'

4.10.4Yusuke Wadabefore adoption3a550d2

lines 11–300why, one step back
11
12// Base event objects to reduce duplication13const baseV1Event: LambdaEvent = {14 version: '1.0',15 resource: '/my/path',16 path: '/my/path',17 httpMethod: 'GET',18 headers: {},19 multiValueHeaders: {},20 queryStringParameters: {},21 requestContext: {22 accountId: '123456789012',23 apiId: 'id',24 authorizer: { claims: null, scopes: null },25 domainName: 'id.execute-api.us-east-1.amazonaws.com',26 domainPrefix: 'id',27 extendedRequestId: 'request-id',28 httpMethod: 'GET',29 identity: {30 sourceIp: '192.0.2.1',31 userAgent: 'user-agent',32 clientCert: {33 clientCertPem: 'CERT_CONTENT',34 subjectDN: 'www.example.com',35 issuerDN: 'Example issuer',36 serialNumber: 'a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1',37 validity: {38 notBefore: 'May 28 12:30:02 2019 GMT',39 notAfter: 'Aug 5 09:36:04 2021 GMT',40 },41 },42 },43 path: '/my/path',44 protocol: 'HTTP/1.1',45 requestId: 'id=',46 requestTime: '04/Mar/2020:19:15:17 +0000',47 requestTimeEpoch: 1583349317135,48 resourcePath: '/my/path',49 stage: '$default',50 },51 pathParameters: {},52 stageVariables: {},53 body: null,54 isBase64Encoded: false,55}5657const baseV2Event: LambdaEvent = {58 version: '2.0',59 routeKey: '$default',60 rawPath: '/my/path',61 rawQueryString: '',62 cookies: [],63 headers: {},64 queryStringParameters: {},65 requestContext: {66 accountId: '123456789012',67 apiId: 'api-id',68 authentication: null,69 authorizer: {},70 domainName: 'id.execute-api.us-east-1.amazonaws.com',71 domainPrefix: 'id',72 http: {73 method: 'POST',74 path: '/my/path',75 protocol: 'HTTP/1.1',76 sourceIp: '192.0.2.1',77 userAgent: 'agent',78 },79 requestId: 'id',80 routeKey: '$default',81 stage: '$default',82 time: '12/Mar/2020:19:03:58 +0000',83 timeEpoch: 1583348638390,84 },85 body: null,86 pathParameters: {},87 isBase64Encoded: false,88 stageVariables: {},89}9091describe('isContentTypeBinary', () => {92 it.each([93 ['image/png', true],94 ['font/woff2', true],95 ['image/svg+xml', false],96 ['image/svg+xml; charset=UTF-8', false],97 ['text/plain', false],98 ['text/plain; charset=UTF-8', false],99 ['text/css', false],100 ['text/javascript', false],101 ['application/json', false],102 ['application/ld+json', false],103 ['application/json', false],104 ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', true],105 ['application/msword', true],106 ['application/epub+zip', true],107 ['application/ld+json', false],108 ['application/vnd.oasis.opendocument.text', true],109 ])('Should determine whether %s it is binary', (mimeType: string, expected: boolean) => {110 expect(defaultIsContentTypeBinary(mimeType)).toBe(expected)111 })112})113114describe('isContentEncodingBinary', () => {115 it('Should determine whether it is compressed', () => {116 expect(isContentEncodingBinary('gzip')).toBe(true)117 expect(isContentEncodingBinary('compress')).toBe(true)118 expect(isContentEncodingBinary('deflate')).toBe(true)119 expect(isContentEncodingBinary('br')).toBe(true)120 expect(isContentEncodingBinary('deflate, gzip')).toBe(true)121 expect(isContentEncodingBinary('')).toBe(false)122 expect(isContentEncodingBinary('unknown')).toBe(false)123 })124})125126describe('EventProcessor.createResult with contentTypesAsBinary', () => {127 const event = baseV1Event128129 it('Should encode as base64 when content-type is in contentTypesAsBinary array', async () => {130 const processor = getProcessor(event)131 const response = new Response('test content', {132 headers: { 'content-type': 'application/custom' },133 })134135 const result = await processor.createResult(event, response, {136 isContentTypeBinary: (contentType: string) => contentType === 'application/custom',137 })138139 expect(result.isBase64Encoded).toBe(true)140 expect(result.body).toBe('dGVzdCBjb250ZW50')141 })142143 it('Should not encode as base64 when content-type is not in isContentTypeBinary array', async () => {144 const processor = getProcessor(event)145 const response = new Response('test content', {146 headers: { 'content-type': 'application/json' },147 })148149 const result = await processor.createResult(event, response, {150 isContentTypeBinary: (contentType: string) => contentType === 'application/custom',151 })152153 expect(result.isBase64Encoded).toBe(false)154 expect(result.body).toBe('test content')155 })156157 it('Should use defaultIsContentTypeBinary when isContentTypeBinary is undefined with binary content', async () => {158 const processor = getProcessor(event)159 const response = new Response('test image content', {160 headers: { 'content-type': 'image/png' },161 })162163 // Pass undefined for isContentTypeBinary to test default behavior164 const result = await processor.createResult(event, response, {165 isContentTypeBinary: undefined,166 })167168 expect(result.isBase64Encoded).toBe(true)169 expect(result.body).toBe('dGVzdCBpbWFnZSBjb250ZW50')170 })171172 it('Should use defaultIsContentTypeBinary when isContentTypeBinary is undefined with non-binary content', async () => {173 const processor = getProcessor(event)174 const response = new Response('test text content', {175 headers: { 'content-type': 'text/plain' },176 })177178 // Pass undefined for isContentTypeBinary to test default behavior179 const result = await processor.createResult(event, response, {180 isContentTypeBinary: undefined,181 })182183 expect(result.isBase64Encoded).toBe(false)184 expect(result.body).toBe('test text content')185 })186})187188describe('EventProcessor.createRequest', () => {189 it('Should preserve percent-encoded values in query string for version 1.0', () => {190 const event: LambdaEvent = {191 ...baseV1Event,192 // API Gateway provides decoded values193 multiValueQueryStringParameters: {194 path: ['/book/{bookId}/'], // Originally %7BbookId%7D195 name: ['John Doe'], // Originally John%20Doe196 tag: ['日本語'], // Originally %E6%97%A5%E6%9C%AC%E8%AA%9E197 },198 }199200 const processor = getProcessor(event)201 const request = processor.createRequest(event)202203 // URL should contain properly encoded values204 expect(request.url).toEqual(205 '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'206 )207 })208209 it('Should handle special characters correctly in queryStringParameters for version 1.0', () => {210 const event: LambdaEvent = {211 ...baseV1Event,212 queryStringParameters: {213 'key with spaces': 'value with spaces',214 'special!@#$%^&*()': 'chars!@#$%^&*()',215 equals: 'a=b=c',216 ampersand: 'a&b&c',217 },218 }219220 const processor = getProcessor(event)221 const request = processor.createRequest(event)222223 // Verify the URL is properly encoded224 const url = new URL(request.url)225 expect(url.searchParams.get('key with spaces')).toBe('value with spaces')226 expect(url.searchParams.get('special!@#$%^&*()')).toBe('chars!@#$%^&*()')227 expect(url.searchParams.get('equals')).toBe('a=b=c')228 expect(url.searchParams.get('ampersand')).toBe('a&b&c')229 })230231 it('Should return valid Request object from version 1.0 API Gateway event', () => {232 const event: LambdaEvent = {233 ...baseV1Event,234 headers: {235 'content-type': 'application/json',236 header1: 'value1',237 header2: 'value1',238 },239 multiValueHeaders: {240 header1: ['value1'],241 header2: ['value1', 'value2', 'value3'],242 },243 // This value doesn't match multi value's content.244 // We want to assert handler is using the multi value's content when both are available.245 queryStringParameters: {246 parameter2: 'value',247 },248 multiValueQueryStringParameters: {249 parameter1: ['value1', 'value2'],250 parameter2: ['value'],251 },252 }253254 const processor = getProcessor(event)255 const request = processor.createRequest(event)256257 expect(request.method).toEqual('GET')258 // Note: Values are now properly encoded259 expect(request.url).toEqual(260 'https://id.execute-api.us-east-1.amazonaws.com/my/path?parameter1=value1&parameter1=value2&parameter2=value'261 )262 expect(Object.fromEntries(request.headers)).toEqual({263 'content-type': 'application/json',264 header1: 'value1',265 header2: 'value1, value2, value3',266 })267 })268269 it('Should return valid Request object from version 2.0 API Gateway event', () => {270 const event: LambdaEvent = {271 ...baseV2Event,272 rawQueryString: 'parameter1=value1&parameter1=value2&parameter2=value',273 cookies: ['cookie1', 'cookie2'],274 headers: {275 'content-type': 'application/json',276 header1: 'value1',277 header2: 'value1,value2',278 },279 queryStringParameters: {280 parameter1: 'value1,value2',281 parameter2: 'value',282 },283 body: 'Hello from Lambda',284 pathParameters: {285 parameter1: 'value1',286 },287 stageVariables: {288 stageVariable1: 'value1',289 stageVariable2: 'value2',290 },291 }292293 const processor = getProcessor(event)294 const request = processor.createRequest(event)295296 expect(request.method).toEqual('POST')297 expect(request.url).toEqual(298 'https://id.execute-api.us-east-1.amazonaws.com/my/path?parameter1=value1&parameter1=value2&parameter2=value'299 )300 expect(Object.fromEntries(request.headers)).toEqual({

Merge commit from forkYusuke Wadabefore adoptionfa5f9bf

line 301why, one step back
301 'content-length': '17',

4.10.4Yusuke Wadabefore adoption3a550d2

lines 302–305why, one step back
302 'content-type': 'application/json',
303 cookie: 'cookie1; cookie2',304 header1: 'value1',305 header2: 'value1,value2',

feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0

lines 306–346why, one step back
306 })
307 })308309 it('Should return valid Request object from version 2.0 Lattice event', async () => {310 const event: LatticeProxyEventV2 = {311 version: '2.0',312 // query string parameters from the path take precedence over the explicit notation below313 path: '/my/path?parameter1=value1&parameter1=value2&parameter2=value',314 method: 'POST',315 headers: {316 cookie: ['cookie1=value1; cookie2=value2'],317 'content-type': ['application/x-www-form-urlencoded'],318 header1: ['value1'],319 header2: ['value1', 'value2'],320 host: ['my-service-a1b2c3.x1y2z3.vpc-lattice-svcs.us-east-1.on.aws'],321 },322 queryStringParameters: {323 parameter1: ['value1', 'value2'],324 parameter2: ['value'],325 },326 body: 'SGVsbG8gZnJvbSBMYW1iZGE=',327 isBase64Encoded: true,328 requestContext: {329 serviceNetworkArn: '',330 serviceArn: '',331 targetGroupArn: '',332 identity: {},333 region: 'us-east-1',334 timeEpoch: '1583348638390123',335 },336 }337338 const processor = getProcessor(event)339 const request = processor.createRequest(event)340341 expect(await request.text()).toEqual('Hello from Lambda')342 expect(request.method).toEqual('POST')343 expect(request.url).toEqual(344 'https://my-service-a1b2c3.x1y2z3.vpc-lattice-svcs.us-east-1.on.aws/my/path?parameter1=value1&parameter1=value2&parameter2=value'345 )346 expect(Object.fromEntries(request.headers)).toEqual({

Merge commit from forkYusuke Wadabefore adoptionfa5f9bf

line 347why, one step back
347 'content-length': '17',

feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0

lines 348–352why, one step back
348 'content-type': 'application/x-www-form-urlencoded',
349 cookie: 'cookie1=value1; cookie2=value2',350 header1: 'value1',351 header2: 'value1, value2',352 host: 'my-service-a1b2c3.x1y2z3.vpc-lattice-svcs.us-east-1.on.aws',

4.10.4Yusuke Wadabefore adoption3a550d2

lines 353–370why, one step back
353 })
354 })355356 describe('non-ASCII header value processing', () => {357 it('Should encode non-ASCII header values with encodeURIComponent', async () => {358 const event: LambdaEvent = {359 ...baseV1Event,360 headers: {361 'x-city': '炎', // Non-ASCII character362 },363 }364365 const processor = getProcessor(event)366 const request = processor.createRequest(event)367368 const xCity = request.headers.get('x-city') ?? ''369 expect(decodeURIComponent(xCity)).toBe('炎')370 })

fix(aws-lambda): handle invalid header names in request processing (#4883)Yusuke Wadabefore adoptionfa2c74f

lines 371–400why, one step back
371 })
372})373374describe('handle', () => {375 it('Should return 400 when request contains invalid header names (v2)', async () => {376 const app = new Hono()377 app.get('/my/path', (c) => c.text('Hello'))378 const handler = handle(app)379380 const event: LambdaEvent = {381 ...baseV2Event,382 headers: {383 'valid-header': 'value',384 'a"a': 'invalid header name',385 },386 requestContext: {387 ...baseV2Event.requestContext,388 http: {389 method: 'GET',390 path: '/my/path',391 protocol: 'HTTP/1.1',392 sourceIp: '192.0.2.1',393 userAgent: 'agent',394 },395 },396 }397398 const result = await handler(event)399 expect(result.statusCode).toBe(400)400 expect(result.body).toBe('Invalid request')

Merge commit from forkYusuke Wadabefore adoption7ae7cba

lines 401–457why, one step back
401 })
402403 it('ALB single-header: emits the first Set-Cookie intact, never comma-joined', async () => {404 const app = new Hono()405 app.get('/multi-cookie', (c) => {406 setCookie(c, 'session', 'abc123', { expires: new Date('2026-06-09T00:00:00Z') })407 setCookie(c, 'csrf', 'xyz789', { expires: new Date('2026-06-10T00:00:00Z') })408 return c.text('ok')409 })410 const handler = handle(app)411412 const event = {413 httpMethod: 'GET',414 path: '/multi-cookie',415 headers: { host: 'app.example.com' },416 body: null,417 isBase64Encoded: false,418 requestContext: { elb: { targetGroupArn: 'arn:aws:elasticloadbalancing:...' } },419 } as unknown as LambdaEvent420421 const result = await handler(event)422423 expect(result.headers!['set-cookie']).toBe(424 'session=abc123; Path=/; Expires=Tue, 09 Jun 2026 00:00:00 GMT'425 )426 })427428 it('Lattice v2: emits multiple Set-Cookie as an array', async () => {429 const app = new Hono()430 app.get('/multi-cookie', (c) => {431 setCookie(c, 'session', 'abc123')432 setCookie(c, 'csrf', 'xyz789')433 return c.text('ok')434 })435 const handler = handle(app)436437 const event: LatticeProxyEventV2 = {438 version: '2.0',439 path: '/multi-cookie',440 method: 'GET',441 headers: { host: ['app.example.com'] },442 queryStringParameters: {},443 body: null,444 isBase64Encoded: false,445 requestContext: {446 serviceNetworkArn: '',447 serviceArn: 'arn:aws:vpc-lattice:us-east-1:123456789012:service/svc-0a40',448 targetGroupArn: '',449 identity: {},450 region: 'us-east-1',451 timeEpoch: '1583348638390123',452 },453 }454455 const result = await handler(event)456457 expect(result.headers!['set-cookie']).toEqual(['session=abc123; Path=/', 'csrf=xyz789; Path=/'])

fix(aws-lambda): handle invalid header names in request processing (#4883)Yusuke Wadabefore adoptionfa2c74f

lines 458–477why, one step back
458 })
459460 it('Should return 400 when request contains invalid header names (v1)', async () => {461 const app = new Hono()462 app.get('/my/path', (c) => c.text('Hello'))463 const handler = handle(app)464465 const event: LambdaEvent = {466 ...baseV1Event,467 headers: {468 'a"a': 'invalid header name',469 },470 multiValueHeaders: {471 'a"a': ['invalid header name'],472 },473 }474475 const result = await handler(event)476 expect(result.statusCode).toBe(400)477 expect(result.body).toBe('Invalid request')

Merge commit from forkYusuke Wadabefore adoptionfa5f9bf

lines 478–507why, one step back
478 })
479480 it('Should enforce bodyLimit when the client understates Content-Length', async () => {481 const app = new Hono()482 app.post(483 '/upload',484 bodyLimit({ maxSize: 1024, onError: (c) => c.text('too large', 413) }),485 async (c) => c.json({ received: (await c.req.text()).length })486 )487 const handler = handle(app)488489 const event: LambdaEvent = {490 ...baseV2Event,491 rawPath: '/upload',492 headers: { 'content-type': 'text/plain', 'content-length': '1' },493 body: 'A'.repeat(10000),494 requestContext: {495 ...baseV2Event.requestContext,496 http: {497 method: 'POST',498 path: '/upload',499 protocol: 'HTTP/1.1',500 sourceIp: '192.0.2.1',501 userAgent: 'agent',502 },503 },504 }505506 const result = await handler(event)507 expect(result.statusCode).toBe(413)

4.10.4Yusuke Wadabefore adoption3a550d2

lines 508–509why, one step back
508 })
509})