handler.test.ts
This file
Path
src/adapter/aws-lambda/handler.test.ts
418 lines · 13.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
The walk stopped after 200 commits: lines older than 82bdc4d point at it.
fix(aws-lambda): handle invalid header names in request processing (#4883)Yusuke Wadabefore adoptionfa2c74f
line 1why, one step back1import { Hono } from '../../hono'feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0
line 2why, one step back2import type { LambdaEvent, LatticeProxyEventV2 } from './handler'fix(aws-lambda): handle invalid header names in request processing (#4883)Yusuke Wadabefore adoptionfa2c74f
lines 3–8why, one step back3import {4 getProcessor,5 handle,6 isContentEncodingBinary,7 defaultIsContentTypeBinary,8} from './handler'4.9.0Yusuke Wadabefore adoption82bdc4d
line 9why, one step back9fix(aws-lambda): preserve percent-encoded values in query strings (#4372)Yusuke Wadabefore adoptiona268569
lines 10–88why, one step back10// Base event objects to reduce duplication11const baseV1Event: LambdaEvent = {12 version: '1.0',13 resource: '/my/path',14 path: '/my/path',15 httpMethod: 'GET',16 headers: {},17 multiValueHeaders: {},18 queryStringParameters: {},19 requestContext: {20 accountId: '123456789012',21 apiId: 'id',22 authorizer: { claims: null, scopes: null },23 domainName: 'id.execute-api.us-east-1.amazonaws.com',24 domainPrefix: 'id',25 extendedRequestId: 'request-id',26 httpMethod: 'GET',27 identity: {28 sourceIp: '192.0.2.1',29 userAgent: 'user-agent',30 clientCert: {31 clientCertPem: 'CERT_CONTENT',32 subjectDN: 'www.example.com',33 issuerDN: 'Example issuer',34 serialNumber: 'a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1',35 validity: {36 notBefore: 'May 28 12:30:02 2019 GMT',37 notAfter: 'Aug 5 09:36:04 2021 GMT',38 },39 },40 },41 path: '/my/path',42 protocol: 'HTTP/1.1',43 requestId: 'id=',44 requestTime: '04/Mar/2020:19:15:17 +0000',45 requestTimeEpoch: 1583349317135,46 resourcePath: '/my/path',47 stage: '$default',48 },49 pathParameters: {},50 stageVariables: {},51 body: null,52 isBase64Encoded: false,53}5455const baseV2Event: LambdaEvent = {56 version: '2.0',57 routeKey: '$default',58 rawPath: '/my/path',59 rawQueryString: '',60 cookies: [],61 headers: {},62 queryStringParameters: {},63 requestContext: {64 accountId: '123456789012',65 apiId: 'api-id',66 authentication: null,67 authorizer: {},68 domainName: 'id.execute-api.us-east-1.amazonaws.com',69 domainPrefix: 'id',70 http: {71 method: 'POST',72 path: '/my/path',73 protocol: 'HTTP/1.1',74 sourceIp: '192.0.2.1',75 userAgent: 'agent',76 },77 requestId: 'id',78 routeKey: '$default',79 stage: '$default',80 time: '12/Mar/2020:19:03:58 +0000',81 timeEpoch: 1583348638390,82 },83 body: null,84 pathParameters: {},85 isBase64Encoded: false,86 stageVariables: {},87}884.9.0Yusuke Wadabefore adoption82bdc4d
line 89why, one step back89describe('isContentTypeBinary', () => {fix(aws-lambda): serve microsoft office files as binary in lambda handler (#4469)Matthias Feistbefore adoption253ec28
lines 90–108why, one step back90 it.each([91 ['image/png', true],92 ['font/woff2', true],93 ['image/svg+xml', false],94 ['image/svg+xml; charset=UTF-8', false],95 ['text/plain', false],96 ['text/plain; charset=UTF-8', false],97 ['text/css', false],98 ['text/javascript', false],99 ['application/json', false],100 ['application/ld+json', false],101 ['application/json', false],102 ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', true],103 ['application/msword', true],104 ['application/epub+zip', true],105 ['application/ld+json', false],106 ['application/vnd.oasis.opendocument.text', true],107 ])('Should determine whether %s it is binary', (mimeType: string, expected: boolean) => {108 expect(defaultIsContentTypeBinary(mimeType)).toBe(expected)4.9.0Yusuke Wadabefore adoption82bdc4d
lines 109–123why, one step back109 })110})111112describe('isContentEncodingBinary', () => {113 it('Should determine whether it is compressed', () => {114 expect(isContentEncodingBinary('gzip')).toBe(true)115 expect(isContentEncodingBinary('compress')).toBe(true)116 expect(isContentEncodingBinary('deflate')).toBe(true)117 expect(isContentEncodingBinary('br')).toBe(true)118 expect(isContentEncodingBinary('deflate, gzip')).toBe(true)119 expect(isContentEncodingBinary('')).toBe(false)120 expect(isContentEncodingBinary('unknown')).toBe(false)121 })122})123fix(aws-lambda): preserve percent-encoded values in query strings (#4372)Yusuke Wadabefore adoptiona268569
lines 124–125why, one step back124describe('EventProcessor.createResult with contentTypesAsBinary', () => {125 const event = baseV1Event4.9.0Yusuke Wadabefore adoption82bdc4d
lines 126–186why, one step back126127 it('Should encode as base64 when content-type is in contentTypesAsBinary array', async () => {128 const processor = getProcessor(event)129 const response = new Response('test content', {130 headers: { 'content-type': 'application/custom' },131 })132133 const result = await processor.createResult(event, response, {134 isContentTypeBinary: (contentType: string) => contentType === 'application/custom',135 })136137 expect(result.isBase64Encoded).toBe(true)138 expect(result.body).toBe('dGVzdCBjb250ZW50')139 })140141 it('Should not encode as base64 when content-type is not in isContentTypeBinary array', async () => {142 const processor = getProcessor(event)143 const response = new Response('test content', {144 headers: { 'content-type': 'application/json' },145 })146147 const result = await processor.createResult(event, response, {148 isContentTypeBinary: (contentType: string) => contentType === 'application/custom',149 })150151 expect(result.isBase64Encoded).toBe(false)152 expect(result.body).toBe('test content')153 })154155 it('Should use defaultIsContentTypeBinary when isContentTypeBinary is undefined with binary content', async () => {156 const processor = getProcessor(event)157 const response = new Response('test image content', {158 headers: { 'content-type': 'image/png' },159 })160161 // Pass undefined for isContentTypeBinary to test default behavior162 const result = await processor.createResult(event, response, {163 isContentTypeBinary: undefined,164 })165166 expect(result.isBase64Encoded).toBe(true)167 expect(result.body).toBe('dGVzdCBpbWFnZSBjb250ZW50')168 })169170 it('Should use defaultIsContentTypeBinary when isContentTypeBinary is undefined with non-binary content', async () => {171 const processor = getProcessor(event)172 const response = new Response('test text content', {173 headers: { 'content-type': 'text/plain' },174 })175176 // Pass undefined for isContentTypeBinary to test default behavior177 const result = await processor.createResult(event, response, {178 isContentTypeBinary: undefined,179 })180181 expect(result.isBase64Encoded).toBe(false)182 expect(result.body).toBe('test text content')183 })184})185186describe('EventProcessor.createRequest', () => {fix(aws-lambda): preserve percent-encoded values in query strings (#4372)Yusuke Wadabefore adoptiona268569
lines 187–228why, one step back187 it('Should preserve percent-encoded values in query string for version 1.0', () => {188 const event: LambdaEvent = {189 ...baseV1Event,190 // API Gateway provides decoded values191 multiValueQueryStringParameters: {192 path: ['/book/{bookId}/'], // Originally %7BbookId%7D193 name: ['John Doe'], // Originally John%20Doe194 tag: ['日本語'], // Originally %E6%97%A5%E6%9C%AC%E8%AA%9E195 },196 }197198 const processor = getProcessor(event)199 const request = processor.createRequest(event)200201 // URL should contain properly encoded values202 expect(request.url).toEqual(203 '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'204 )205 })206207 it('Should handle special characters correctly in queryStringParameters for version 1.0', () => {208 const event: LambdaEvent = {209 ...baseV1Event,210 queryStringParameters: {211 'key with spaces': 'value with spaces',212 'special!@#$%^&*()': 'chars!@#$%^&*()',213 equals: 'a=b=c',214 ampersand: 'a&b&c',215 },216 }217218 const processor = getProcessor(event)219 const request = processor.createRequest(event)220221 // Verify the URL is properly encoded222 const url = new URL(request.url)223 expect(url.searchParams.get('key with spaces')).toBe('value with spaces')224 expect(url.searchParams.get('special!@#$%^&*()')).toBe('chars!@#$%^&*()')225 expect(url.searchParams.get('equals')).toBe('a=b=c')226 expect(url.searchParams.get('ampersand')).toBe('a&b&c')227 })2284.9.0Yusuke Wadabefore adoption82bdc4d
lines 229–230why, one step back229 it('Should return valid Request object from version 1.0 API Gateway event', () => {230 const event: LambdaEvent = {fix(aws-lambda): preserve percent-encoded values in query strings (#4372)Yusuke Wadabefore adoptiona268569
line 231why, one step back231 ...baseV1Event,4.9.0Yusuke Wadabefore adoption82bdc4d
lines 232–255why, one step back232 headers: {233 'content-type': 'application/json',234 header1: 'value1',235 header2: 'value1',236 },237 multiValueHeaders: {238 header1: ['value1'],239 header2: ['value1', 'value2', 'value3'],240 },241 // This value doesn't match multi value's content.242 // We want to assert handler is using the multi value's content when both are available.243 queryStringParameters: {244 parameter2: 'value',245 },246 multiValueQueryStringParameters: {247 parameter1: ['value1', 'value2'],248 parameter2: ['value'],249 },250 }251252 const processor = getProcessor(event)253 const request = processor.createRequest(event)254255 expect(request.method).toEqual('GET')fix(aws-lambda): preserve percent-encoded values in query strings (#4372)Yusuke Wadabefore adoptiona268569
line 256why, one step back256 // Note: Values are now properly encoded4.9.0Yusuke Wadabefore adoption82bdc4d
lines 257–268why, one step back257 expect(request.url).toEqual(258 'https://id.execute-api.us-east-1.amazonaws.com/my/path?parameter1=value1¶meter1=value2¶meter2=value'259 )260 expect(Object.fromEntries(request.headers)).toEqual({261 'content-type': 'application/json',262 header1: 'value1',263 header2: 'value1, value2, value3',264 })265 })266267 it('Should return valid Request object from version 2.0 API Gateway event', () => {268 const event: LambdaEvent = {fix(aws-lambda): preserve percent-encoded values in query strings (#4372)Yusuke Wadabefore adoptiona268569
line 269why, one step back269 ...baseV2Event,4.9.0Yusuke Wadabefore adoption82bdc4d
lines 270–302why, one step back270 rawQueryString: 'parameter1=value1¶meter1=value2¶meter2=value',271 cookies: ['cookie1', 'cookie2'],272 headers: {273 'content-type': 'application/json',274 header1: 'value1',275 header2: 'value1,value2',276 },277 queryStringParameters: {278 parameter1: 'value1,value2',279 parameter2: 'value',280 },281 body: 'Hello from Lambda',282 pathParameters: {283 parameter1: 'value1',284 },285 stageVariables: {286 stageVariable1: 'value1',287 stageVariable2: 'value2',288 },289 }290291 const processor = getProcessor(event)292 const request = processor.createRequest(event)293294 expect(request.method).toEqual('POST')295 expect(request.url).toEqual(296 'https://id.execute-api.us-east-1.amazonaws.com/my/path?parameter1=value1¶meter1=value2¶meter2=value'297 )298 expect(Object.fromEntries(request.headers)).toEqual({299 'content-type': 'application/json',300 cookie: 'cookie1; cookie2',301 header1: 'value1',302 header2: 'value1,value2',feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0
lines 303–348why, one step back303 })304 })305306 it('Should return valid Request object from version 2.0 Lattice event', async () => {307 const event: LatticeProxyEventV2 = {308 version: '2.0',309 // query string parameters from the path take precedence over the explicit notation below310 path: '/my/path?parameter1=value1¶meter1=value2¶meter2=value',311 method: 'POST',312 headers: {313 cookie: ['cookie1=value1; cookie2=value2'],314 'content-type': ['application/x-www-form-urlencoded'],315 header1: ['value1'],316 header2: ['value1', 'value2'],317 host: ['my-service-a1b2c3.x1y2z3.vpc-lattice-svcs.us-east-1.on.aws'],318 },319 queryStringParameters: {320 parameter1: ['value1', 'value2'],321 parameter2: ['value'],322 },323 body: 'SGVsbG8gZnJvbSBMYW1iZGE=',324 isBase64Encoded: true,325 requestContext: {326 serviceNetworkArn: '',327 serviceArn: '',328 targetGroupArn: '',329 identity: {},330 region: 'us-east-1',331 timeEpoch: '1583348638390123',332 },333 }334335 const processor = getProcessor(event)336 const request = processor.createRequest(event)337338 expect(await request.text()).toEqual('Hello from Lambda')339 expect(request.method).toEqual('POST')340 expect(request.url).toEqual(341 'https://my-service-a1b2c3.x1y2z3.vpc-lattice-svcs.us-east-1.on.aws/my/path?parameter1=value1¶meter1=value2¶meter2=value'342 )343 expect(Object.fromEntries(request.headers)).toEqual({344 'content-type': 'application/x-www-form-urlencoded',345 cookie: 'cookie1=value1; cookie2=value2',346 header1: 'value1',347 header2: 'value1, value2',348 host: 'my-service-a1b2c3.x1y2z3.vpc-lattice-svcs.us-east-1.on.aws',4.9.0Yusuke Wadabefore adoption82bdc4d
lines 349–350why, one step back349 })350 })fix(aws-lambda): sanitize non-ASCII header values to prevent ByteString errors (#4437)Yusuke Wadabefore adoption38f756d
lines 351–366why, one step back351352 describe('non-ASCII header value processing', () => {353 it('Should encode non-ASCII header values with encodeURIComponent', async () => {354 const event: LambdaEvent = {355 ...baseV1Event,356 headers: {357 'x-city': '炎', // Non-ASCII character358 },359 }360361 const processor = getProcessor(event)362 const request = processor.createRequest(event)363364 const xCity = request.headers.get('x-city') ?? ''365 expect(decodeURIComponent(xCity)).toBe('炎')366 })fix(aws-lambda): handle invalid header names in request processing (#4883)Yusuke Wadabefore adoptionfa2c74f
lines 367–416why, one step back367 })368})369370describe('handle', () => {371 it('Should return 400 when request contains invalid header names (v2)', async () => {372 const app = new Hono()373 app.get('/my/path', (c) => c.text('Hello'))374 const handler = handle(app)375376 const event: LambdaEvent = {377 ...baseV2Event,378 headers: {379 'valid-header': 'value',380 'a"a': 'invalid header name',381 },382 requestContext: {383 ...baseV2Event.requestContext,384 http: {385 method: 'GET',386 path: '/my/path',387 protocol: 'HTTP/1.1',388 sourceIp: '192.0.2.1',389 userAgent: 'agent',390 },391 },392 }393394 const result = await handler(event)395 expect(result.statusCode).toBe(400)396 expect(result.body).toBe('Invalid request')397 })398399 it('Should return 400 when request contains invalid header names (v1)', async () => {400 const app = new Hono()401 app.get('/my/path', (c) => c.text('Hello'))402 const handler = handle(app)403404 const event: LambdaEvent = {405 ...baseV1Event,406 headers: {407 'a"a': 'invalid header name',408 },409 multiValueHeaders: {410 'a"a': ['invalid header name'],411 },412 }413414 const result = await handler(event)415 expect(result.statusCode).toBe(400)416 expect(result.body).toBe('Invalid request')fix(aws-lambda): sanitize non-ASCII header values to prevent ByteString errors (#4437)Yusuke Wadabefore adoption38f756d
line 417why, one step back417 })4.9.0Yusuke Wadabefore adoption82bdc4d
line 418why, one step back418})