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
Provenance
- Commit
eefdb27- Tree
a59e443- Author
watany <76135106+watany-dev@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
b7f12dd
6 files changed+262 added−101 removed
modified:runtime_tests/deno/.vscode/settings.json+2 added-7 removed
123456723456127{ "eslint.validate": [ "javascript", "javascriptreact", "typescript", "typescriptreact" ], "eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"], "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, "deno.enable": true}No newline at end of file}modified:runtime_tests/lambda/index.test.ts+104 added-34 removed
1+import type {2+ ApiGatewayRequestContext,3+ LambdaFunctionUrlRequestContext,4+} from '../../src/adapter/aws-lambda/custom-context'5 import { handle } from '../../src/adapter/aws-lambda/handler'6 import { Hono } from '../../src/hono'7 import { basicAuth } from '../../src/middleware/basic-auth'8 9+type Bindings = {10+ requestContext: ApiGatewayRequestContext | LambdaFunctionUrlRequestContext11+}12+13 describe('AWS Lambda Adapter for Hono', () => {6- const app = new Hono()14+ const app = new Hono<{ Bindings: Bindings }>()15 16 app.get('/', (c) => {17 return c.text('Hello Lambda!')18 })18 unmodified lines37 const password = 'hono-password-a'38 app.use('/auth/*', basicAuth({ username, password }))39 app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))40 41+ app.get('/custom-context/apigw', (c) => {42+ const lambdaContext = c.env.requestContext43+ return c.json(lambdaContext)44+ })45+46+ app.get('/custom-context/lambda', (c) => {47+ const lambdaContext = c.env.requestContext48+ return c.json(lambdaContext)49+ })50+51 const handler = handle(app)52 53+ 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+ }77+78+ 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+ }109+110 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 }119 120 const response = await handler(event)121 expect(response.statusCode).toBe(200)8 unmodified lines130 headers: {},131 path: '/binary',132 body: null,133 isBase64Encoded: false,61- requestContext: {62- domainName: 'example.com',63- },134+ requestContext: testApiGatewayRequestContext,135 }136 137 const response = await handler(event)138 expect(response.statusCode).toBe(200)8 unmodified lines147 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 }153 154+ testLambdaFunctionUrlRequestContext.http.method = 'GET'155+156 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 lines166 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 }172 173 const response = await handler(event)174 expect(response.statusCode).toBe(404)9 unmodified lines184 },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 }190 191 const response = await handler(event)192 expect(response.statusCode).toBe(200)10 unmodified lines203 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 }209 210+ testLambdaFunctionUrlRequestContext.http.method = 'POST'211+212 const response = await handler(event)213 expect(response.statusCode).toBe(200)214 expect(response.body).toBe('Good Morning Lambda!')215 })8 unmodified lines224 },225 path: '/post/binary',226 body: buffer.toString('base64'),227 isBase64Encoded: true,167- requestContext: {168- domainName: 'example.com',169- },228+ requestContext: testApiGatewayRequestContext,229 }230 231 const response = await handler(event)232 expect(response.statusCode).toBe(200)8 unmodified lines241 },242 path: '/auth/abc',243 body: null,244 isBase64Encoded: true,186- requestContext: {187- domainName: 'example.com',188- },245+ requestContext: testApiGatewayRequestContext,246 }247 248 const response = await handler(event)249 expect(response.statusCode).toBe(401)9 unmodified lines259 },260 path: '/auth/abc',261 body: null,262 isBase64Encoded: true,206- requestContext: {207- domainName: 'example.com',208- },263+ requestContext: testApiGatewayRequestContext,264 }265 266 const response = await handler(event)267 expect(response.statusCode).toBe(200)268 expect(response.body).toBe('Good Night Lambda!')269 })270+271+ 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+ }280+281+ 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 */2-import type { Callback, CloudFrontConfig, CloudFrontRequest, CloudFrontResponse } from '../../src/adapter/lambda-edge/handler'2+import type {3+ Callback,4+ CloudFrontConfig,5+ CloudFrontRequest,6+ CloudFrontResponse,7+} from '../../src/adapter/lambda-edge/handler'8 import { handle } from '../../src/adapter/lambda-edge/handler'9 import { Hono } from '../../src/hono'10 import { basicAuth } from '../../src/middleware/basic-auth'11 28 unmodified lines40 })41 42 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 lines63 app.use('/auth/*', basicAuth({ username, password }))64 app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))65 66 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 lines881 ],882 }883 884 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 })900 901 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 })915 916 it('Should handle a GET request and add header (Lambda@Edge viewer response)', async () => {917 const event = {107 unmodified lines1025 },1026 },1027 ],1028 }1018- 1029+1030 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 })1046 1047 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 })1061 1062 it('Callback Event (Lambda@Edge response)', async () => {1063 const event = {19 unmodified lines1083 method: 'GET',1084 querystring: '',1085 uri: '/config/eventCheck',1086 },1074- }1087+ },1088 },1089 ],1090 }1078- 1091+1092 let called = false1093 await handler(event, {}, (_err, result) => {1094 called = true1095 })1096 1097 expect(called).toBe(true)1098 })1086-1087-1099 })added:src/adapter/aws-lambda/custom-context.ts+83 added
1+// @denoify-ignore2+3+interface ClientCert {4+ clientCertPem: string;5+ subjectDN: string;6+ issuerDN: string;7+ serialNumber: string;8+ validity: {9+ notBefore: string;10+ notAfter: string;11+ };12+}13+14+interface 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+}29+30+export 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+}51+52+interface 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+}63+64+export 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
2 unmodified lines345678910115 unmodified lines1718192020212221222324252 unmodified lines282930313334353233343536373839404145464748495042434445464748495051525354555657585960612 unmodified lines6465666770686970717273747594 unmodified lines2 unmodified linesimport type { Hono } from '../../hono'import type { Env } from '../../types'
import { encodeBase64 } from '../../utils/encode'import type { ApiGatewayRequestContext, LambdaFunctionUrlRequestContext } from './custom-context'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment// @ts-ignoreglobalThis.crypto ??= crypto5 unmodified lines rawPath: string rawQueryString: string body: string | null isBase64Encoded: boolean requestContext: { domainName: string } requestContext: ApiGatewayRequestContext}
// When calling Lambda through an API Gateway or an ELBinterface APIGatewayProxyEvent {2 unmodified lines path: string body: string | null isBase64Encoded: boolean queryStringParameters?: Record<string, string | undefined> requestContext: { domainName: string } requestContext: ApiGatewayRequestContext}
// When calling Lambda through an Lambda Function URLsinterface LambdaFunctionUrlEvent { headers: Record<string, string | undefined> rawPath: string rawQueryString: string body: string | null isBase64Encoded: boolean requestContext: { domainName: string http: { method: string } } requestContext: LambdaFunctionUrlRequestContext}
interface APIGatewayProxyResult { statusCode: number body: string headers: Record<string, string> isBase64Encoded: boolean}
const getRequestContext = ( event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent): ApiGatewayRequestContext | LambdaFunctionUrlRequestContext => { return event.requestContext}
/** * Accepts events from API Gateway/ELB(`APIGatewayProxyEvent`) and directly through Function Url(`APIGatewayProxyEventV2`) */export const handle = <E extends Env = Env, S = {}, BasePath extends string = '/'>(2 unmodified lines return async ( event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent ): Promise<APIGatewayProxyResult> => { const req = createRequest(event) const res = await app.fetch(req) const requestContext = getRequestContext(event)
const res = await app.fetch(req, { requestContext })
return createResult(res) }}
94 unmodified linesmodified:src/adapter/aws-lambda/index.ts+2 added
1234// @denoify-ignoreexport { handle } from './handler'export type { ApiGatewayRequestContext, LambdaFunctionUrlRequestContext } from './custom-context'