Skip to content
Myr

fix(adaptor): Access to custom request context on AWS Lambda Adaptor (#1305)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* v0.1 * lint * test lint * pritter * prettier

authored by watany · committed by GitHub · parent b7f12dd · Browse files · 6 files+262 added−101 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+262 added−101 removed

  • tests:+162 added−81 removed
  • other:+100 added−20 removed

6 files+262 added−101 removed

modified:runtime_tests/deno/.vscode/settings.json+2 added-7 removed
modified:runtime_tests/lambda/index.test.ts+104 added-34 removed
1import type {2 ApiGatewayRequestContext,3 LambdaFunctionUrlRequestContext,4} from '../../src/adapter/aws-lambda/custom-context'5import { handle } from '../../src/adapter/aws-lambda/handler'6import { Hono } from '../../src/hono'7import { basicAuth } from '../../src/middleware/basic-auth'89type Bindings = {10 requestContext: ApiGatewayRequestContext | LambdaFunctionUrlRequestContext11}1213describe('AWS Lambda Adapter for Hono', () => {6 const app = new Hono()14 const app = new Hono<{ Bindings: Bindings }>()1516 app.get('/', (c) => {17 return c.text('Hello Lambda!')18 })
18 unmodified lines
37 const password = 'hono-password-a'38 app.use('/auth/*', basicAuth({ username, password }))39 app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))4041 app.get('/custom-context/apigw', (c) => {42 const lambdaContext = c.env.requestContext43 return c.json(lambdaContext)44 })4546 app.get('/custom-context/lambda', (c) => {47 const lambdaContext = c.env.requestContext48 return c.json(lambdaContext)49 })5051 const handler = handle(app)5253 const testApiGatewayRequestContext = {54 accountId: '123456789012',55 apiId: 'id',56 authorizer: {57 claims: null,58 scopes: null,59 },60 domainName: 'example.com',61 domainPrefix: 'id',62 extendedRequestId: 'request-id',63 httpMethod: 'GET',64 identity: {65 sourceIp: 'IP',66 userAgent: 'user-agent',67 },68 path: '/my/path',69 protocol: 'HTTP/1.1',70 requestId: 'id=',71 requestTime: '04/Mar/2020:19:15:17 +0000',72 requestTimeEpoch: 1583349317135,73 resourcePath: '/',74 stage: '$default',75 customProperty: 'customValue',76 }7778 const testLambdaFunctionUrlRequestContext = {79 accountId: '123456789012',80 apiId: 'urlid',81 authentication: null,82 authorizer: {83 iam: {84 accessKey: 'AKIA...',85 accountId: '111122223333',86 callerId: 'AIDA...',87 cognitoIdentity: null,88 principalOrgId: null,89 userArn: 'arn:aws:iam::111122223333:user/example-user',90 userId: 'AIDA...',91 },92 },93 domainName: 'example.com',94 domainPrefix: '<url-id>',95 http: {96 method: 'POST',97 path: '/my/path',98 protocol: 'HTTP/1.1',99 sourceIp: '123.123.123.123',100 userAgent: 'agent',101 },102 requestId: 'id',103 routeKey: '$default',104 stage: '$default',105 time: '12/Mar/2020:19:03:58 +0000',106 timeEpoch: 1583348638390,107 customProperty: 'customValue',108 }109110 it('Should handle a GET request and return a 200 response', async () => {111 const event = {112 httpMethod: 'GET',113 headers: { 'content-type': 'text/plain' },114 path: '/',115 body: null,116 isBase64Encoded: false,42 requestContext: {43 domainName: 'example.com',44 },117 requestContext: testApiGatewayRequestContext,118 }119120 const response = await handler(event)121 expect(response.statusCode).toBe(200)
8 unmodified lines
130 headers: {},131 path: '/binary',132 body: null,133 isBase64Encoded: false,61 requestContext: {62 domainName: 'example.com',63 },134 requestContext: testApiGatewayRequestContext,135 }136137 const response = await handler(event)138 expect(response.statusCode).toBe(200)
8 unmodified lines
147 rawPath: '/',148 rawQueryString: '',149 body: null,150 isBase64Encoded: false,80 requestContext: {81 domainName: 'example.com',82 http: {83 method: 'GET',84 },85 },151 requestContext: testLambdaFunctionUrlRequestContext,152 }153154 testLambdaFunctionUrlRequestContext.http.method = 'GET'155156 const response = await handler(event)157 expect(response.statusCode).toBe(200)158 expect(response.body).toBe('Hello Lambda!')159 expect(response.headers['content-type']).toMatch(/^text\/plain/)
6 unmodified lines
166 headers: { 'content-type': 'text/plain' },167 path: '/nothing',168 body: null,169 isBase64Encoded: false,102 requestContext: {103 domainName: 'example.com',104 },170 requestContext: testApiGatewayRequestContext,171 }172173 const response = await handler(event)174 expect(response.statusCode).toBe(404)
9 unmodified lines
184 },185 path: '/post',186 body: Buffer.from(searchParam.toString()).toString('base64'),187 isBase64Encoded: true,122 requestContext: {123 domainName: 'example.com',124 },188 requestContext: testApiGatewayRequestContext,189 }190191 const response = await handler(event)192 expect(response.statusCode).toBe(200)
10 unmodified lines
203 rawPath: '/post',204 rawQueryString: '',205 body: Buffer.from(searchParam.toString()).toString('base64'),206 isBase64Encoded: true,143 requestContext: {144 domainName: 'example.com',145 http: {146 method: 'POST',147 },148 },207 requestContext: testLambdaFunctionUrlRequestContext,208 }209210 testLambdaFunctionUrlRequestContext.http.method = 'POST'211212 const response = await handler(event)213 expect(response.statusCode).toBe(200)214 expect(response.body).toBe('Good Morning Lambda!')215 })
8 unmodified lines
224 },225 path: '/post/binary',226 body: buffer.toString('base64'),227 isBase64Encoded: true,167 requestContext: {168 domainName: 'example.com',169 },228 requestContext: testApiGatewayRequestContext,229 }230231 const response = await handler(event)232 expect(response.statusCode).toBe(200)
8 unmodified lines
241 },242 path: '/auth/abc',243 body: null,244 isBase64Encoded: true,186 requestContext: {187 domainName: 'example.com',188 },245 requestContext: testApiGatewayRequestContext,246 }247248 const response = await handler(event)249 expect(response.statusCode).toBe(401)
9 unmodified lines
259 },260 path: '/auth/abc',261 body: null,262 isBase64Encoded: true,206 requestContext: {207 domainName: 'example.com',208 },263 requestContext: testApiGatewayRequestContext,264 }265266 const response = await handler(event)267 expect(response.statusCode).toBe(200)268 expect(response.body).toBe('Good Night Lambda!')269 })270271 it('Should handle a GET request and return custom context', async () => {272 const event = {273 httpMethod: 'GET',274 headers: { 'content-type': 'application/json' },275 path: '/custom-context/apigw',276 body: null,277 isBase64Encoded: false,278 requestContext: testApiGatewayRequestContext,279 }280281 const response = await handler(event)282 expect(response.statusCode).toBe(200)283 expect(JSON.parse(response.body).customProperty).toEqual('customValue')284 })285})
modified:runtime_tests/lambda-edge/index.test.ts+58 added-47 removed
1/* eslint-disable quotes */2import type { Callback, CloudFrontConfig, CloudFrontRequest, CloudFrontResponse } from '../../src/adapter/lambda-edge/handler'2import type {3 Callback,4 CloudFrontConfig,5 CloudFrontRequest,6 CloudFrontResponse,7} from '../../src/adapter/lambda-edge/handler'8import { handle } from '../../src/adapter/lambda-edge/handler'9import { Hono } from '../../src/hono'10import { basicAuth } from '../../src/middleware/basic-auth'11
28 unmodified lines
40 })4142 app.get('/config/eventCheck', async (c, next) => {43 await next()39 if(c.env.config.eventType in ['viewer-request', 'origin-request']) {44 if (c.env.config.eventType in ['viewer-request', 'origin-request']) {45 c.env.callback(null, c.env.request)46 } else {47 c.env.callback(null, c.env.response)48 }
14 unmodified lines
63 app.use('/auth/*', basicAuth({ username, password }))64 app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))6566 app.get('/header/add', async (c, next) => {62 c.env.response.headers['Strict-Transport-Security'.toLowerCase()] = [{63 key: 'Strict-Transport-Security',64 value: 'max-age=63072000; includeSubdomains; preload'65 }];66 c.env.response.headers['X-Custom'.toLowerCase()] = [{67 key: 'X-Custom',68 value: 'Foo'69 }];67 c.env.response.headers['Strict-Transport-Security'.toLowerCase()] = [68 {69 key: 'Strict-Transport-Security',70 value: 'max-age=63072000; includeSubdomains; preload',71 },72 ]73 c.env.response.headers['X-Custom'.toLowerCase()] = [74 {75 key: 'X-Custom',76 value: 'Foo',77 },78 ]79 await next()80 c.env.callback(null, c.env.response)81 })82
798 unmodified lines
881 ],882 }883884 interface CloudFrontHeaders {876 [name: string]: [{877 key: string878 value: string879 }]885 [name: string]: [886 {887 key: string888 value: string889 }890 ]891 }892 let called = false882 let headers: CloudFrontHeaders = {};893 let headers: CloudFrontHeaders = {}894 await handler(event, {}, (_err, result) => {895 if (result && result.headers) {885 headers = result.headers as CloudFrontHeaders;896 headers = result.headers as CloudFrontHeaders897 }898 called = true899 })900901 expect(called).toBe(true)891 expect(headers["access-control-allow-credentials"]).toEqual([902 expect(headers['access-control-allow-credentials']).toEqual([903 {893 key: "Access-Control-Allow-Credentials",894 value: "true"895 }896 ]);897 expect(headers["access-control-allow-origin"]).toEqual([904 key: 'Access-Control-Allow-Credentials',905 value: 'true',906 },907 ])908 expect(headers['access-control-allow-origin']).toEqual([909 {899 key: "Access-Control-Allow-Origin",900 value: "*"901 }902 ]);910 key: 'Access-Control-Allow-Origin',911 value: '*',912 },913 ])914 })915916 it('Should handle a GET request and add header (Lambda@Edge viewer response)', async () => {917 const event = {
107 unmodified lines
1025 },1026 },1027 ],1028 }1018 10291030 interface CloudFrontHeaders {1020 [name: string]: [{1021 key: string1022 value: string1023 }]1031 [name: string]: [1032 {1033 key: string1034 value: string1035 }1036 ]1037 }1038 let called = false1026 let headers: CloudFrontHeaders = {};1039 let headers: CloudFrontHeaders = {}1040 await handler(event, {}, (_err, result) => {1041 if (result && result.headers) {1029 headers = result.headers as CloudFrontHeaders;1042 headers = result.headers as CloudFrontHeaders1043 }1044 called = true1045 })10461047 expect(called).toBe(true)1035 expect(headers["strict-transport-security"]).toEqual([1048 expect(headers['strict-transport-security']).toEqual([1049 {1037 key: "Strict-Transport-Security",1038 value: "max-age=63072000; includeSubdomains; preload"1039 }1040 ]);1041 expect(headers["x-custom"]).toEqual([1050 key: 'Strict-Transport-Security',1051 value: 'max-age=63072000; includeSubdomains; preload',1052 },1053 ])1054 expect(headers['x-custom']).toEqual([1055 {1043 key: "X-Custom",1044 value: "Foo"1045 }1046 ]);1056 key: 'X-Custom',1057 value: 'Foo',1058 },1059 ])1060 })10611062 it('Callback Event (Lambda@Edge response)', async () => {1063 const event = {
19 unmodified lines
1083 method: 'GET',1084 querystring: '',1085 uri: '/config/eventCheck',1086 },1074 }1087 },1088 },1089 ],1090 }1078 10911092 let called = false1093 await handler(event, {}, (_err, result) => {1094 called = true1095 })10961097 expect(called).toBe(true)1098 })108610871099})
added:src/adapter/aws-lambda/custom-context.ts+83 added
1// @denoify-ignore23interface ClientCert {4 clientCertPem: string;5 subjectDN: string;6 issuerDN: string;7 serialNumber: string;8 validity: {9 notBefore: string;10 notAfter: string;11 };12}1314interface Identity {15 accessKey?: string;16 accountId?: string;17 caller?: string;18 cognitoAuthenticationProvider?: string;19 cognitoAuthenticationType?: string;20 cognitoIdentityId?: string;21 cognitoIdentityPoolId?: string;22 principalOrgId?: string;23 sourceIp: string;24 user?: string;25 userAgent: string;26 userArn?: string;27 clientCert?: ClientCert;28}2930export interface ApiGatewayRequestContext {31 accountId: string;32 apiId: string;33 authorizer: {34 claims?: unknown;35 scopes?: unknown;36 };37 domainName: string;38 domainPrefix: string;39 extendedRequestId: string;40 httpMethod: string;41 identity: Identity;42 path: string;43 protocol: string;44 requestId: string;45 requestTime: string;46 requestTimeEpoch: number;47 resourceId?: string;48 resourcePath: string;49 stage: string;50}5152interface Authorizer {53 iam?: {54 accessKey: string;55 accountId: string;56 callerId: string;57 cognitoIdentity: null;58 principalOrgId: null;59 userArn: string;60 userId: string;61 };62}6364export interface LambdaFunctionUrlRequestContext {65 accountId: string;66 apiId: string;67 authentication: null;68 authorizer: Authorizer;69 domainName: string;70 domainPrefix: string;71 http: {72 method: string;73 path: string;74 protocol: string;75 sourceIp: string;76 userAgent: string;77 };78 requestId: string;79 routeKey: string;80 stage: string;81 time: string;82 timeEpoch: number;83}
modified:src/adapter/aws-lambda/handler.ts+13 added-13 removed
modified:src/adapter/aws-lambda/index.ts+2 added