feat(adaptor): Lambda@Edge supports response callbacks (#1251)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* change header * fixed * simple test * minify * refactor * fix * binding response * fix * fix * remove fix * remove lowercase
authored by watany · committed by GitHub · parent 14f5536 · Browse files · 2 files·+339 added−28 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+339 added−28 removed
- tests:+310 added−3 removed
- other:+29 added−25 removed
Provenance
- Commit
ba346a4- Tree
fb47c69- Author
watany <76135106+watany-dev@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
14f5536
2 files changed+339 added−28 removed
modified:runtime_tests/lambda-edge/index.test.ts+310 added-3 removed
1 /* eslint-disable quotes */2-import type { Callback, CloudFrontRequest } from '../../src/adapter/lambda-edge/handler'2+import type { Callback, CloudFrontRequest, CloudFrontResponse } from '../../src/adapter/lambda-edge/handler'3 import { handle } from '../../src/adapter/lambda-edge/handler'4 import { Hono } from '../../src/hono'5 import { basicAuth } from '../../src/middleware/basic-auth'6 7 type Bindings = {8 callback: Callback9 request: CloudFrontRequest10+ response: CloudFrontResponse11 }12 13 describe('Lambda@Edge Adapter for Hono', () => {14 const app = new Hono<{ Bindings: Bindings }>()12 unmodified lines27 const body = (await c.req.parseBody()) as { message: string }28 return c.text(body.message)29 })30 30- app.get('/callback', async (c, next) => {31+ app.get('/callback/request', async (c, next) => {32 await next()33 c.env.callback(null, c.env.request)34 })35 36+ app.get('/callback/response', async (c, next) => {37+ await next()38+ c.env.callback(null, c.env.response)39+ })40+41 app.post('/post/binary', async (c) => {42 const body = await c.req.blob()43 return c.text(`${body.size} bytes`)44 })2 unmodified lines47 const password = 'hono-password-a'48 app.use('/auth/*', basicAuth({ username, password }))49 app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))50 51+ app.get('/header/add', async (c, next) => {52+ c.env.response.headers['Strict-Transport-Security'.toLowerCase()] = [{53+ key: 'Strict-Transport-Security',54+ value: 'max-age=63072000; includeSubdomains; preload'55+ }];56+ c.env.response.headers['X-Custom'.toLowerCase()] = [{57+ key: 'X-Custom',58+ value: 'Foo'59+ }];60+ await next()61+ c.env.callback(null, c.env.response)62+ })63+64 const handler = handle(app)65 66 it('Should handle a GET request and return a 200 response (Lambda@Edge viewer request)', async () => {67 const event = {658 unmodified lines726 clientIp: '123.123.123.123',727 headers: {},728 method: 'GET',729 querystring: '',711- uri: '/callback',730+ uri: '/callback/request',731 },732 },733 },734 ],11 unmodified lines746 747 expect(called).toBe(true)748 expect(requestClientIp).toBe('123.123.123.123')749 })750+751+ it('Should call a callback to continue processing the response', async () => {752+ const event = {753+ Records: [754+ {755+ cf: {756+ config: {757+ distributionDomainName: 'example.com',758+ distributionId: 'EDFDVBD6EXAMPLE',759+ eventType: 'viewer-response',760+ requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',761+ },762+ request: {763+ clientIp: '203.0.113.178',764+ headers: {765+ host: [766+ {767+ key: 'Host',768+ value: 'example.com',769+ },770+ ],771+ 'user-agent': [772+ {773+ key: 'User-Agent',774+ value: 'curl/7.66.0',775+ },776+ ],777+ accept: [778+ {779+ key: 'accept',780+ value: '*/*',781+ },782+ ],783+ },784+ method: 'GET',785+ querystring: '',786+ uri: '/callback/response',787+ },788+ response: {789+ headers: {790+ 'access-control-allow-credentials': [791+ {792+ key: 'Access-Control-Allow-Credentials',793+ value: 'true',794+ },795+ ],796+ 'access-control-allow-origin': [797+ {798+ key: 'Access-Control-Allow-Origin',799+ value: '*',800+ },801+ ],802+ date: [803+ {804+ key: 'Date',805+ value: 'Mon, 13 Jan 2020 20:14:56 GMT',806+ },807+ ],808+ 'referrer-policy': [809+ {810+ key: 'Referrer-Policy',811+ value: 'no-referrer-when-downgrade',812+ },813+ ],814+ server: [815+ {816+ key: 'Server',817+ value: 'ExampleCustomOriginServer',818+ },819+ ],820+ 'x-content-type-options': [821+ {822+ key: 'X-Content-Type-Options',823+ value: 'nosniff',824+ },825+ ],826+ 'x-frame-options': [827+ {828+ key: 'X-Frame-Options',829+ value: 'DENY',830+ },831+ ],832+ 'x-xss-protection': [833+ {834+ key: 'X-XSS-Protection',835+ value: '1; mode=block',836+ },837+ ],838+ age: [839+ {840+ key: 'Age',841+ value: '2402',842+ },843+ ],844+ 'content-type': [845+ {846+ key: 'Content-Type',847+ value: 'text/html; charset=utf-8',848+ },849+ ],850+ 'content-length': [851+ {852+ key: 'Content-Length',853+ value: '9593',854+ },855+ ],856+ },857+ status: '200',858+ statusDescription: 'OK',859+ },860+ },861+ },862+ ],863+ }864+865+ interface CloudFrontHeaders {866+ [name: string]: [{867+ key: string868+ value: string869+ }]870+ }871+ let called = false872+ let headers: CloudFrontHeaders = {};873+ await handler(event, {}, (_err, result) => {874+ if (result && result.headers) {875+ headers = result.headers as CloudFrontHeaders;876+ }877+ called = true878+ })879+880+ expect(called).toBe(true)881+ expect(headers["access-control-allow-credentials"]).toEqual([882+ {883+ key: "Access-Control-Allow-Credentials",884+ value: "true"885+ }886+ ]);887+ expect(headers["access-control-allow-origin"]).toEqual([888+ {889+ key: "Access-Control-Allow-Origin",890+ value: "*"891+ }892+ ]);893+ })894+895+ it('Should handle a GET request and add header (Lambda@Edge viewer response)', async () => {896+ const event = {897+ Records: [898+ {899+ cf: {900+ config: {901+ distributionDomainName: 'example.com',902+ distributionId: 'EDFDVBD6EXAMPLE',903+ eventType: 'viewer-response',904+ requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',905+ },906+ request: {907+ clientIp: '203.0.113.178',908+ headers: {909+ host: [910+ {911+ key: 'Host',912+ value: 'example.com',913+ },914+ ],915+ 'user-agent': [916+ {917+ key: 'User-Agent',918+ value: 'curl/7.66.0',919+ },920+ ],921+ accept: [922+ {923+ key: 'accept',924+ value: '*/*',925+ },926+ ],927+ },928+ method: 'GET',929+ querystring: '',930+ uri: '/header/add',931+ },932+ response: {933+ headers: {934+ 'access-control-allow-credentials': [935+ {936+ key: 'Access-Control-Allow-Credentials',937+ value: 'true',938+ },939+ ],940+ 'access-control-allow-origin': [941+ {942+ key: 'Access-Control-Allow-Origin',943+ value: '*',944+ },945+ ],946+ date: [947+ {948+ key: 'Date',949+ value: 'Mon, 13 Jan 2020 20:14:56 GMT',950+ },951+ ],952+ 'referrer-policy': [953+ {954+ key: 'Referrer-Policy',955+ value: 'no-referrer-when-downgrade',956+ },957+ ],958+ server: [959+ {960+ key: 'Server',961+ value: 'ExampleCustomOriginServer',962+ },963+ ],964+ 'x-content-type-options': [965+ {966+ key: 'X-Content-Type-Options',967+ value: 'nosniff',968+ },969+ ],970+ 'x-frame-options': [971+ {972+ key: 'X-Frame-Options',973+ value: 'DENY',974+ },975+ ],976+ 'x-xss-protection': [977+ {978+ key: 'X-XSS-Protection',979+ value: '1; mode=block',980+ },981+ ],982+ age: [983+ {984+ key: 'Age',985+ value: '2402',986+ },987+ ],988+ 'content-type': [989+ {990+ key: 'Content-Type',991+ value: 'text/html; charset=utf-8',992+ },993+ ],994+ 'content-length': [995+ {996+ key: 'Content-Length',997+ value: '9593',998+ },999+ ],1000+ },1001+ status: '200',1002+ statusDescription: 'OK',1003+ },1004+ },1005+ },1006+ ],1007+ }1008+ 1009+ interface CloudFrontHeaders {1010+ [name: string]: [{1011+ key: string1012+ value: string1013+ }]1014+ }1015+ let called = false1016+ let headers: CloudFrontHeaders = {};1017+ await handler(event, {}, (_err, result) => {1018+ if (result && result.headers) {1019+ headers = result.headers as CloudFrontHeaders;1020+ }1021+ called = true1022+ })1023+1024+ expect(called).toBe(true)1025+ expect(headers["strict-transport-security"]).toEqual([1026+ {1027+ key: "Strict-Transport-Security",1028+ value: "max-age=63072000; includeSubdomains; preload"1029+ }1030+ ]);1031+ expect(headers["x-custom"]).toEqual([1032+ {1033+ key: "X-Custom",1034+ value: "Foo"1035+ }1036+ ]);1037+ })1038 })modified:src/adapter/lambda-edge/handler.ts+29 added-25 removed
43 unmodified lines44454647484950515253545556573 unmodified lines61626364656667686923 unmodified lines9394959697989910010110210310410510610710810911011198991121131141021151161171181191201211221231241251261111271281141151161171181191291301221311321331341351361281371381391401411331421431351361371381391401441451461431441471481491471481501501511511521531541551561571581593 unmodified lines43 unmodified lines custom: CloudFrontCustomOrigin }}
export interface CloudFrontResponse { headers: CloudFrontHeaders status: string statusDescription?: string}
interface CloudFrontConfig { distributionDomainName: string distributionId: string eventType: string3 unmodified linesinterface CloudFrontEvent { cf: { config: CloudFrontConfig request: CloudFrontRequest response?: CloudFrontResponse }}
export interface CloudFrontEdgeEvent {23 unmodified lines/** * Accepts events from 'Lambda@Edge' event * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html */const convertHeaders = (headers: Headers): CloudFrontHeaders => { const cfHeaders: CloudFrontHeaders = {} headers.forEach((value, key) => { cfHeaders[key.toLowerCase()] = [{ key: key.toLowerCase(), value }] }) return cfHeaders}
// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const handle = (app: Hono<any>) => { return async ( event: CloudFrontEdgeEvent, context?: CloudFrontContext, callback?: Callback ): Promise<CloudFrontResult> => { const req = createRequest(event) const res = await app.fetch(req, { const res = await app.fetch(createRequest(event), { event, context, callback, callback: (err: Error | null, result?: CloudFrontResult | CloudFrontRequest) => { callback?.(err, result) }, request: event.Records[0].cf.request, response: event.Records[0].cf.response, }) return createResult(res) }}
const createResult = async (res: Response): Promise<CloudFrontResult> => { const isBase64Encoded = isContentTypeBinary(res.headers.get('content-type') || '')
const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()
const headers: { [header: string]: { key: string; value: string }[] } = {}
res.headers.forEach((value, key) => { headers[key.toLowerCase()] = [{ key: key.toLowerCase(), value }] })
return { status: res.status.toString(), headers, headers: convertHeaders(res.headers), body, }}
const createRequest = (event: CloudFrontEdgeEvent) => { const queryString = extractQueryString(event) const queryString = event.Records[0].cf.request.querystring const urlPath = `https://${event.Records[0].cf.config.distributionDomainName}${event.Records[0].cf.request.uri}` const url = queryString ? `${urlPath}?${queryString}` : urlPath
const headers = new Headers() for (const [k, v] of Object.entries(event.Records[0].cf.request.headers)) { Object.entries(event.Records[0].cf.request.headers).forEach(([k, v]) => { v.forEach((header) => headers.set(k, header.value)) } const method = event.Records[0].cf.request.method const requestInit: RequestInit = { headers, method, } })
const requestBody = event.Records[0].cf.request.body requestInit.body = requestBody?.encoding === 'base64' && requestBody?.data const body = requestBody?.encoding === 'base64' && requestBody?.data ? Buffer.from(requestBody.data, 'base64') : requestBody?.data return new Request(url, requestInit)}
const extractQueryString = (event: CloudFrontEdgeEvent) => { return event.Records[0].cf.request.querystring return new Request(url, { headers, method: event.Records[0].cf.request.method, body, })}
export const isContentTypeBinary = (contentType: string) => { return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml)$/.test(3 unmodified lines