index.test.ts
This file
Path
runtime_tests/lambda/index.test.ts
758 lines · 22.5 KiB · TypeScript
Last changed by
fix(adapter): handle multi value headers in AWS Lambda (#2494)TATSUNO “Taz” Yasuhirobefore adoptionacb56b8
History of this fileTake it
The walk stopped after 200 commits: lines older than 8addfd4 point at it.
chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4
lines 1–135why, one step back1import { Readable } from 'stream'2import type {3 ApiGatewayRequestContext,4 ApiGatewayRequestContextV2,5} from '../../src/adapter/aws-lambda/custom-context'6import { handle, streamHandle } from '../../src/adapter/aws-lambda/handler'7import type { LambdaEvent } from '../../src/adapter/aws-lambda/handler'8import type { LambdaContext } from '../../src/adapter/aws-lambda/types'9import { getCookie, setCookie } from '../../src/helper/cookie'10import { streamSSE } from '../../src/helper/streaming'11import { Hono } from '../../src/hono'12import { basicAuth } from '../../src/middleware/basic-auth'13import './mock'1415type Bindings = {16 event: LambdaEvent17 lambdaContext: LambdaContext18 requestContext: ApiGatewayRequestContext | ApiGatewayRequestContextV219}2021const testApiGatewayRequestContextV2 = {22 accountId: '123456789012',23 apiId: 'urlid',24 authentication: null,25 authorizer: {26 iam: {27 accessKey: 'AKIA...',28 accountId: '111122223333',29 callerId: 'AIDA...',30 cognitoIdentity: null,31 principalOrgId: null,32 userArn: 'arn:aws:iam::111122223333:user/example-user',33 userId: 'AIDA...',34 },35 },36 domainName: 'example.com',37 domainPrefix: '<url-id>',38 http: {39 method: 'POST',40 path: '/my/path',41 protocol: 'HTTP/1.1',42 sourceIp: '123.123.123.123',43 userAgent: 'agent',44 },45 requestId: 'id',46 routeKey: '$default',47 stage: '$default',48 time: '12/Mar/2020:19:03:58 +0000',49 timeEpoch: 1583348638390,50 customProperty: 'customValue',51}5253describe('AWS Lambda Adapter for Hono', () => {54 const app = new Hono<{ Bindings: Bindings }>()5556 app.get('/', (c) => {57 return c.text('Hello Lambda!')58 })5960 app.get('/binary', (c) => {61 return c.body('Fake Image', 200, {62 'Content-Type': 'image/png',63 })64 })6566 app.post('/post', async (c) => {67 const body = (await c.req.parseBody()) as { message: string }68 return c.text(body.message)69 })7071 app.post('/post/binary', async (c) => {72 const body = await c.req.blob()73 return c.text(`${body.size} bytes`)74 })7576 const username = 'hono-user-a'77 const password = 'hono-password-a'78 app.use('/auth/*', basicAuth({ username, password }))79 app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))8081 app.get('/lambda-event', (c) => {82 const event = c.env.event83 return c.json(event)84 })8586 app.get('/lambda-context', (c) => {87 const fnctx = c.env.lambdaContext88 return c.json(fnctx)89 })9091 app.get('/custom-context/v1/apigw', (c) => {92 const lambdaContext = c.env.requestContext93 return c.json(lambdaContext)94 })9596 app.get('/custom-context/apigw', (c) => {97 const lambdaContext = c.env.event.requestContext98 return c.json(lambdaContext)99 })100101 app.get('/custom-context/v1/lambda', (c) => {102 const lambdaContext = c.env.requestContext103 return c.json(lambdaContext)104 })105106 app.get('/custom-context/lambda', (c) => {107 const lambdaContext = c.env.event.requestContext108 return c.json(lambdaContext)109 })110111 const testCookie1 = {112 key: 'id',113 value: crypto.randomUUID(),114 get serialized() {115 return `${this.key}=${this.value}; Path=/`116 },117 }118 const testCookie2 = {119 key: 'secret',120 value: crypto.randomUUID(),121 get serialized() {122 return `${this.key}=${this.value}; Path=/`123 },124 }125126 app.post('/cookie', (c) => {127 setCookie(c, testCookie1.key, testCookie1.value)128 setCookie(c, testCookie2.key, testCookie2.value)129 return c.text('Cookies Set')130 })131132 app.get('/cookie', (c) => {133 const validCookies =134 getCookie(c, testCookie1.key) === testCookie1.value &&135 getCookie(c, testCookie2.key) === testCookie2.valuechore(lint): set `curly` rule as `all` (#2112)Yusuke Wadabefore adoptionf616ed9
lines 136–138why, one step back136 if (!validCookies) {137 return c.text('Invalid Cookies')138 }chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4
lines 139–141why, one step back139 return c.text('Valid Cookies')140 })141fix(adapter): handle multi value headers in AWS Lambda (#2494)TATSUNO “Taz” Yasuhirobefore adoptionacb56b8
lines 142–148why, one step back142 app.post('/headers', (c) => {143 if (c.req.header('foo')?.includes('bar')) {144 return c.json({ message: 'ok' })145 }146 return c.json({ message: 'fail' }, 400)147 })148chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4
lines 149–498why, one step back149 const handler = handle(app)150151 const testApiGatewayRequestContext = {152 accountId: '123456789012',153 apiId: 'id',154 authorizer: {155 claims: null,156 scopes: null,157 },158 domainName: 'example.com',159 domainPrefix: 'id',160 extendedRequestId: 'request-id',161 httpMethod: 'GET',162 identity: {163 sourceIp: 'IP',164 userAgent: 'user-agent',165 },166 path: '/my/path',167 protocol: 'HTTP/1.1',168 requestId: 'id=',169 requestTime: '04/Mar/2020:19:15:17 +0000',170 requestTimeEpoch: 1583349317135,171 resourcePath: '/',172 stage: '$default',173 customProperty: 'customValue',174 }175176 const testApiGatewayRequestContextV2 = {177 accountId: '123456789012',178 apiId: 'urlid',179 authentication: null,180 authorizer: {181 iam: {182 accessKey: 'AKIA...',183 accountId: '111122223333',184 callerId: 'AIDA...',185 cognitoIdentity: null,186 principalOrgId: null,187 userArn: 'arn:aws:iam::111122223333:user/example-user',188 userId: 'AIDA...',189 },190 },191 domainName: 'example.com',192 domainPrefix: '<url-id>',193 http: {194 method: 'POST',195 path: '/my/path',196 protocol: 'HTTP/1.1',197 sourceIp: '123.123.123.123',198 userAgent: 'agent',199 },200 requestId: 'id',201 routeKey: '$default',202 stage: '$default',203 time: '12/Mar/2020:19:03:58 +0000',204 timeEpoch: 1583348638390,205 customProperty: 'customValue',206 }207208 const testALBRequestContext = {209 elb: {210 targetGroupArn:211 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a',212 },213 }214215 it('Should handle a GET request and return a 200 response', async () => {216 const event = {217 version: '1.0',218 resource: '/',219 httpMethod: 'GET',220 headers: { 'content-type': 'text/plain' },221 path: '/',222 body: null,223 isBase64Encoded: false,224 requestContext: testApiGatewayRequestContext,225 }226227 const response = await handler(event)228 expect(response.statusCode).toBe(200)229 expect(response.body).toBe('Hello Lambda!')230 expect(response.headers['content-type']).toMatch(/^text\/plain/)231 expect(response.isBase64Encoded).toBe(false)232 })233234 it('Should handle a GET request and return a 200 response with binary', async () => {235 const event = {236 version: '1.0',237 resource: '/binary',238 httpMethod: 'GET',239 headers: {},240 path: '/binary',241 body: null,242 isBase64Encoded: false,243 requestContext: testApiGatewayRequestContext,244 }245246 const response = await handler(event)247 expect(response.statusCode).toBe(200)248 expect(response.body).toBe('RmFrZSBJbWFnZQ==')249 expect(response.headers['content-type']).toMatch(/^image\/png/)250 expect(response.isBase64Encoded).toBe(true)251 })252253 it('Should handle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {254 const event = {255 version: '2.0',256 routeKey: '$default',257 headers: { 'content-type': 'text/plain' },258 rawPath: '/',259 rawQueryString: '',260 body: null,261 isBase64Encoded: false,262 requestContext: testApiGatewayRequestContextV2,263 }264265 testApiGatewayRequestContextV2.http.method = 'GET'266267 const response = await handler(event)268 expect(response.statusCode).toBe(200)269 expect(response.body).toBe('Hello Lambda!')270 expect(response.headers['content-type']).toMatch(/^text\/plain/)271 expect(response.isBase64Encoded).toBe(false)272 })273274 it('Should handle a GET request and return a 200 response (ALBEvent)', async () => {275 const event = {276 headers: { 'content-type': 'text/plain' },277 httpMethod: 'GET',278 path: '/',279 queryStringParameters: {280 query: '1234ABCD',281 },282 body: null,283 isBase64Encoded: false,284 requestContext: testALBRequestContext,285 }286287 const response = await handler(event)288 expect(response.statusCode).toBe(200)289 expect(response.body).toBe('Hello Lambda!')290 expect(response.headers['content-type']).toMatch(/^text\/plain/)291 expect(response.isBase64Encoded).toBe(false)292 })293294 it('Should handle a GET request and return a 404 response', async () => {295 const event = {296 version: '1.0',297 resource: '/nothing',298 httpMethod: 'GET',299 headers: { 'content-type': 'text/plain' },300 path: '/nothing',301 body: null,302 isBase64Encoded: false,303 requestContext: testApiGatewayRequestContext,304 }305306 const response = await handler(event)307 expect(response.statusCode).toBe(404)308 })309310 it('Should handle a POST request and return a 200 response', async () => {311 const searchParam = new URLSearchParams()312 searchParam.append('message', 'Good Morning Lambda!')313 const event = {314 version: '1.0',315 resource: '/post',316 httpMethod: 'POST',317 headers: {318 'Content-Type': 'application/x-www-form-urlencoded',319 },320 path: '/post',321 body: Buffer.from(searchParam.toString()).toString('base64'),322 isBase64Encoded: true,323 requestContext: testApiGatewayRequestContext,324 }325326 const response = await handler(event)327 expect(response.statusCode).toBe(200)328 expect(response.body).toBe('Good Morning Lambda!')329 })330331 it('Should handle a POST request and return a 200 response (LambdaFunctionUrlEvent)', async () => {332 const searchParam = new URLSearchParams()333 searchParam.append('message', 'Good Morning Lambda!')334 const event = {335 version: '2.0',336 routeKey: '$default',337 headers: {338 'Content-Type': 'application/x-www-form-urlencoded',339 },340 rawPath: '/post',341 rawQueryString: '',342 body: Buffer.from(searchParam.toString()).toString('base64'),343 isBase64Encoded: true,344 requestContext: testApiGatewayRequestContextV2,345 }346347 testApiGatewayRequestContextV2.http.method = 'POST'348349 const response = await handler(event)350 expect(response.statusCode).toBe(200)351 expect(response.body).toBe('Good Morning Lambda!')352 })353354 it('Should handle a POST request with binary and return a 200 response', async () => {355 const array = new Uint8Array([0xc0, 0xff, 0xee])356 const buffer = Buffer.from(array)357 const event = {358 version: '1.0',359 resource: '/post/binary',360 httpMethod: 'POST',361 headers: {362 'Content-Type': 'application/x-www-form-urlencoded',363 },364 path: '/post/binary',365 body: buffer.toString('base64'),366 isBase64Encoded: true,367 requestContext: testApiGatewayRequestContext,368 }369370 const response = await handler(event)371 expect(response.statusCode).toBe(200)372 expect(response.body).toBe('3 bytes')373 })374375 it('Should handle a request and return a 401 response with Basic auth', async () => {376 const event = {377 version: '1.0',378 resource: '/auth/abc',379 httpMethod: 'GET',380 headers: {381 'Content-Type': 'plain/text',382 },383 path: '/auth/abc',384 body: null,385 isBase64Encoded: true,386 requestContext: testApiGatewayRequestContext,387 }388389 const response = await handler(event)390 expect(response.statusCode).toBe(401)391 })392393 it('Should handle a request and return a 200 response with Basic auth', async () => {394 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'395 const event = {396 version: '1.0',397 resource: '/auth/abc',398 httpMethod: 'GET',399 headers: {400 'Content-Type': 'plain/text',401 Authorization: `Basic ${credential}`,402 },403 path: '/auth/abc',404 body: null,405 isBase64Encoded: true,406 requestContext: testApiGatewayRequestContext,407 }408409 const response = await handler(event)410 expect(response.statusCode).toBe(200)411 expect(response.body).toBe('Good Night Lambda!')412 })413414 it('Should handle a GET request and return custom context', async () => {415 const event = {416 version: '1.0',417 resource: '/custom-context/apigw',418 httpMethod: 'GET',419 headers: { 'content-type': 'application/json' },420 path: '/custom-context/apigw',421 body: null,422 isBase64Encoded: false,423 requestContext: testApiGatewayRequestContext,424 }425426 const response = await handler(event)427 expect(response.statusCode).toBe(200)428 expect(JSON.parse(response.body).customProperty).toEqual('customValue')429 })430431 it('Should handle a GET request and context', async () => {432 const event = {433 version: '1.0',434 resource: '/lambda-context',435 httpMethod: 'GET',436 headers: { 'content-type': 'application/json' },437 path: '/lambda-context',438 body: null,439 isBase64Encoded: false,440 requestContext: testApiGatewayRequestContext,441 }442 const context: LambdaContext = {443 callbackWaitsForEmptyEventLoop: false,444 functionName: 'myLambdaFunction',445 functionVersion: '1.0.0',446 invokedFunctionArn: 'arn:aws:lambda:us-west-2:123456789012:function:myLambdaFunction',447 memoryLimitInMB: '128',448 awsRequestId: 'c6af9ac6-a7b0-11e6-80f5-76304dec7eb7',449 logGroupName: '/aws/lambda/myLambdaFunction',450 logStreamName: '2016/11/14/[$LATEST]f2d4b21cfb33490da2e8f8ef79a483s4',451 getRemainingTimeInMillis: () => {452 return 60000 // 60 seconds453 },454 }455 const response = await handler(event, context)456 expect(response.statusCode).toBe(200)457 expect(JSON.parse(response.body).callbackWaitsForEmptyEventLoop).toEqual(false)458 })459460 it('Should handle a POST request and return a 200 response with cookies set (APIGatewayProxyEvent V1 and V2)', async () => {461 const apiGatewayEvent = {462 version: '1.0',463 resource: '/cookie',464 httpMethod: 'POST',465 headers: { 'content-type': 'text/plain' },466 path: '/cookie',467 body: null,468 isBase64Encoded: false,469 requestContext: testApiGatewayRequestContext,470 }471472 const apiGatewayResponse = await handler(apiGatewayEvent)473474 expect(apiGatewayResponse.statusCode).toBe(200)475 expect(apiGatewayResponse.multiValueHeaders).toHaveProperty('set-cookie', [476 testCookie1.serialized,477 testCookie2.serialized,478 ])479480 const apiGatewayEventV2 = {481 version: '2.0',482 routeKey: '$default',483 httpMethod: 'POST',484 headers: { 'content-type': 'text/plain' },485 rawPath: '/cookie',486 rawQueryString: '',487 body: null,488 isBase64Encoded: false,489 requestContext: testApiGatewayRequestContextV2,490 }491492 const apiGatewayResponseV2 = await handler(apiGatewayEventV2)493494 expect(apiGatewayResponseV2.statusCode).toBe(200)495 expect(apiGatewayResponseV2).toHaveProperty('cookies', [496 testCookie1.serialized,497 testCookie2.serialized,498 ])fix(adapter): handle multi value headers in AWS Lambda (#2494)TATSUNO “Taz” Yasuhirobefore adoptionacb56b8
lines 499–592why, one step back499 })500501 describe('headers', () => {502 describe('single-value headers', () => {503 it('Should extract single-value headers and return 200 (ALBProxyEvent)', async () => {504 const event = {505 body: '{}',506 httpMethod: 'POST',507 isBase64Encoded: false,508 path: '/headers',509 headers: {510 host: 'localhost',511 foo: 'bar',512 },513 requestContext: testALBRequestContext,514 }515 const apiGatewayResponseV2 = await handler(event)516 expect(apiGatewayResponseV2.statusCode).toBe(200)517 })518519 it('Should extract single-value headers and return 200 (APIGatewayProxyEvent)', async () => {520 const apigatewayProxyEvent = {521 version: '1.0',522 resource: '/headers',523 httpMethod: 'POST',524 headers: {525 host: 'localhost',526 foo: 'bar',527 },528 path: '/headers',529 body: null,530 isBase64Encoded: false,531 requestContext: testApiGatewayRequestContext,532 }533 const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)534 expect(apiGatewayResponseV2.statusCode).toBe(200)535 })536537 it('Should extract single-value headers and return 200 (APIGatewayProxyEventV2)', async () => {538 const apigatewayProxyV2Event = {539 version: '2.0',540 routeKey: '$default',541 headers: {542 host: 'localhost',543 foo: 'bar',544 },545 rawPath: '/headers',546 rawQueryString: '',547 requestContext: testApiGatewayRequestContextV2,548 resource: '/headers',549 body: null,550 isBase64Encoded: false,551 }552 const apiGatewayResponseV2 = await handler(apigatewayProxyV2Event)553 expect(apiGatewayResponseV2.statusCode).toBe(200)554 })555 })556557 describe('multi-value headers', () => {558 it('Should extract multi-value headers and return 200 (ALBProxyEvent)', async () => {559 const event = {560 body: '{}',561 httpMethod: 'POST',562 isBase64Encoded: false,563 path: '/headers',564 multiValueHeaders: {565 host: ['localhost'],566 foo: ['bar'],567 },568 requestContext: testALBRequestContext,569 }570 const apiGatewayResponseV2 = await handler(event)571 expect(apiGatewayResponseV2.statusCode).toBe(200)572 })573574 it('Should extract multi-value headers and return 200 (APIGatewayProxyEvent)', async () => {575 const apigatewayProxyEvent = {576 version: '1.0',577 resource: '/headers',578 httpMethod: 'POST',579 headers: {},580 multiValueHeaders: {581 host: ['localhost'],582 foo: ['bar'],583 },584 path: '/headers',585 body: null,586 isBase64Encoded: false,587 requestContext: testApiGatewayRequestContext,588 }589 const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)590 expect(apiGatewayResponseV2.statusCode).toBe(200)591 })592 })chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4
lines 593–758why, one step back593 })594595 it('Should handle a POST request and return a 200 response if cookies match (APIGatewayProxyEvent V1 and V2)', async () => {596 const apiGatewayEvent = {597 version: '1.0',598 resource: '/cookie',599 httpMethod: 'GET',600 headers: {601 'content-type': 'text/plain',602 cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),603 },604 path: '/cookie',605 body: null,606 isBase64Encoded: false,607 requestContext: testApiGatewayRequestContext,608 }609610 const apiGatewayResponse = await handler(apiGatewayEvent)611612 expect(apiGatewayResponse.statusCode).toBe(200)613 expect(apiGatewayResponse.body).toBe('Valid Cookies')614 expect(apiGatewayResponse.headers['content-type']).toMatch(/^text\/plain/)615 expect(apiGatewayResponse.isBase64Encoded).toBe(false)616617 const apiGatewayEventV2 = {618 version: '2.0',619 routeKey: '$default',620 headers: { 'content-type': 'text/plain' },621 rawPath: '/cookie',622 cookies: [testCookie1.serialized, testCookie2.serialized],623 rawQueryString: '',624 body: null,625 isBase64Encoded: false,626 requestContext: testApiGatewayRequestContextV2,627 }628 testApiGatewayRequestContextV2.http.method = 'GET'629630 const apiGatewayResponseV2 = await handler(apiGatewayEventV2)631632 expect(apiGatewayResponseV2.statusCode).toBe(200)633 expect(apiGatewayResponseV2.body).toBe('Valid Cookies')634 expect(apiGatewayResponseV2.headers['content-type']).toMatch(/^text\/plain/)635 expect(apiGatewayResponseV2.isBase64Encoded).toBe(false)636 })637})638639describe('streamHandle function', () => {640 const app = new Hono<{ Bindings: Bindings }>()641642 app.get('/', (c) => {643 return c.text('Hello Lambda!')644 })645646 app.get('/stream/text', async (c) => {647 return c.streamText(async (stream) => {648 for (let i = 0; i < 3; i++) {649 await stream.writeln(`${i}`)650 await stream.sleep(1)651 }652 })653 })654655 app.get('/sse', async (c) => {656 return streamSSE(c, async (stream) => {657 let id = 0658 const maxIterations = 2659660 while (id < maxIterations) {661 const message = `Message\nIt is ${id}`662 await stream.writeSSE({ data: message, event: 'time-update', id: String(id++) })663 await stream.sleep(10)664 }665 })666 })667668 const handler = streamHandle(app)669670 it('Should streamHandle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {671 const event = {672 headers: { 'content-type': ' binary/octet-stream' },673 rawPath: '/stream/text',674 rawQueryString: '',675 body: null,676 isBase64Encoded: false,677 requestContext: testApiGatewayRequestContextV2,678 }679680 testApiGatewayRequestContextV2.http.method = 'GET'681682 const mockReadableStream = new Readable({683 // eslint-disable-next-line @typescript-eslint/no-empty-function684 read() {},685 })686687 mockReadableStream.push('0\n')688 mockReadableStream.push('1\n')689 mockReadableStream.push('2\n')690 mockReadableStream.push('3\n')691 mockReadableStream.push(null) // EOF692693 await handler(event, mockReadableStream)694695 const chunks = []696 for await (const chunk of mockReadableStream) {697 chunks.push(chunk)698 }699 expect(chunks.join('')).toContain('0\n1\n2\n3\n')700 })701702 it('Should handle a GET request for an SSE stream and return the correct chunks', async () => {703 const event = {704 headers: { 'content-type': 'text/event-stream' },705 rawPath: '/sse',706 rawQueryString: '',707 body: null,708 isBase64Encoded: false,709 requestContext: testApiGatewayRequestContextV2,710 }711712 testApiGatewayRequestContextV2.http.method = 'GET'713714 const mockReadableStream = new Readable({715 // eslint-disable-next-line @typescript-eslint/no-empty-function716 read() {},717 })718719 const initContentType = {720 'Content-Type': 'application/vnd.awslambda.http-integration-response',721 }722 mockReadableStream.push(JSON.stringify(initContentType))723724 // Send JSON formatted response headers, followed by 8 NULL characters as a separator725 const httpResponseMetadata = {726 statusCode: 200,727 headers: { 'Custom-Header': 'value' },728 cookies: ['session=abcd1234'],729 }730 const jsonResponsePrelude = JSON.stringify(httpResponseMetadata) + Buffer.alloc(8, 0).toString()731 mockReadableStream.push(jsonResponsePrelude)732733 mockReadableStream.push('data: Message\ndata: It is 0\n\n')734 mockReadableStream.push('data: Message\ndata: It is 1\n\n')735 mockReadableStream.push(null) // EOF736737 await handler(event, mockReadableStream)738739 const chunks = []740 for await (const chunk of mockReadableStream) {741 chunks.push(chunk)742 }743744 // If you have chunks, you might want to convert them to strings before checking745 const output = Buffer.concat(chunks).toString()746 expect(output).toContain('data: Message\ndata: It is 0\n\n')747 expect(output).toContain('data: Message\ndata: It is 1\n\n')748749 // Assertions for the newly added header and prelude750 expect(output).toContain('application/vnd.awslambda.http-integration-response')751 expect(output).toContain('Custom-Header')752 expect(output).toContain('session=abcd1234')753754 // Check for JSON prelude and NULL sequence755 const nullSequence = '\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000'756 expect(output).toContain(jsonResponsePrelude.replace(nullSequence, ''))757 })758})