feat(lambda-edge): pass the `context` and `callback` as env (#1229)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parent f37de25 · Browse files · 3 files·+141 added−80 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+141 added−80 removed
- tests:+60 added−11 removed
- other:+81 added−69 removed
Provenance
- Commit
d48c160- Tree
22f9a86- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
f37de25
3 files changed+141 added−80 removed
modified:runtime_tests/lambda-edge/index.test.ts+60 added-11 removed
1+/* eslint-disable quotes */2+import type { Callback, CloudFrontRequest } 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+}11+12 describe('Lambda@Edge Adapter for Hono', () => {6- const app = new Hono()13+ const app = new Hono<{ Bindings: Bindings }>()14 15 app.get('/', (c) => {16 return c.text('Hello Lambda!')17 })8 unmodified lines26 const body = (await c.req.parseBody()) as { message: string }27 return c.text(body.message)28 })29 30+ app.get('/callback', async (c, next) => {31+ await next()32+ c.env.callback(null, c.env.request)33+ })34+35 const username = 'hono-user-a'36 const password = 'hono-password-a'37 app.use('/auth/*', basicAuth({ username, password }))38 app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))43 unmodified lines82 }83 const response = await handler(event)84 expect(response.status).toBe('200')85 expect(response.body).toBe('Hello Lambda!')74- if(response.headers && response.headers['content-type']){86+ if (response.headers && response.headers['content-type']) {87 expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)88 } else {77- throw new Error("'content-type' header is missing in the response");89+ throw new Error("'content-type' header is missing in the response")90 }91 })92 93 it('Should handle a GET request and return a 200 response (Lambda@Edge origin request)', async () => {63 unmodified lines157 }158 const response = await handler(event)159 expect(response.status).toBe('200')160 expect(response.body).toBe('Hello Lambda!')149- if(response.headers && response.headers['content-type']){161+ if (response.headers && response.headers['content-type']) {162 expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)163 } else {152- throw new Error("'content-type' header is missing in the response");164+ throw new Error("'content-type' header is missing in the response")165 }166 })167 168 it('Should handle a GET request and return a 200 response (Lambda@Edge viewer response)', async () => {111 unmodified lines280 }281 const response = await handler(event)282 expect(response.status).toBe('200')283 expect(response.body).toBe('Hello Lambda!')272- if(response.headers && response.headers['content-type']){284+ if (response.headers && response.headers['content-type']) {285 expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)286 } else {275- throw new Error("'content-type' header is missing in the response");287+ throw new Error("'content-type' header is missing in the response")288 }289 })290 291 it('Should handle a GET request and return a 200 response (Lambda@Edge origin response)', async () => {129 unmodified lines421 }422 const response = await handler(event)423 expect(response.status).toBe('200')424 expect(response.body).toBe('Hello Lambda!')413- if(response.headers && response.headers['content-type']){425+ if (response.headers && response.headers['content-type']) {426 expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)427 } else {416- throw new Error("'content-type' header is missing in the response");428+ throw new Error("'content-type' header is missing in the response")429 }430 })431 432 it('Should handle a GET request and return a 200 response with binary', async () => {29 unmodified lines462 const response = await handler(event)463 464 expect(response.status).toBe('200')465 expect(response.body).toBe('RmFrZSBJbWFnZQ==') // base64 encoded fake image454- if(response.headers && response.headers['content-type']){466+ if (response.headers && response.headers['content-type']) {467 expect(response.headers['content-type'][0].value).toMatch(/^image\/png/)468 } else {457- throw new Error("'content-type' header is missing in the response");469+ throw new Error("'content-type' header is missing in the response")470 }471 })472 473 it('Should handle a GET request and return a 404 response', async () => {162 unmodified lines636 const response = await handler(event)637 638 expect(response.status).toBe('401')639 })640+641+ it('Should call a callback to continue processing the request', async () => {642+ const event = {643+ Records: [644+ {645+ cf: {646+ config: {647+ distributionDomainName: 'example.com',648+ distributionId: 'EXAMPLE123',649+ eventType: 'viewer-request',650+ requestId: 'exampleRequestId',651+ },652+ request: {653+ clientIp: '123.123.123.123',654+ headers: {},655+ method: 'GET',656+ querystring: '',657+ uri: '/callback',658+ },659+ },660+ },661+ ],662+ }663+664+ let called = false665+ let requestClientIp = ''666+667+ await handler(event, {}, (_err, result) => {668+ if (result && 'clientIp' in result) {669+ requestClientIp = result.clientIp670+ }671+ called = true672+ })673+674+ expect(called).toBe(true)675+ expect(requestClientIp).toBe('123.123.123.123')676+ })677 })modified:src/adapter/lambda-edge/handler.ts+80 added-69 removed
7 unmodified lines891011121312131415161717181920212223242526272821222324252627282930313233343536313233343536373839404142383940414243444544454647484950515249505152535455565758595758596061626362636465666768697071727368697475767172737475767777787980818283848586878889909184929386949596979889909910010110210310410510610710810996110111981121131001141151021031041161171181191061071081091101201211221231241251261131141151271281291301311321331221341351241361371381391401411421431311321331441451461471481491371381391501511521531541551561571471587 unmodified lines// @ts-ignoreglobalThis.crypto ??= crypto
interface CloudFrontHeader { key: string; value: string; key: string value: string}
interface CloudFrontHeaders { [name: string]: CloudFrontHeader[]; [name: string]: CloudFrontHeader[]}
interface CloudFrontCustomOrigin { customHeaders: CloudFrontHeaders; domainName: string; keepaliveTimeout: number; path: string; port: number; protocol: string; readTimeout: number; sslProtocols: string[]; customHeaders: CloudFrontHeaders domainName: string keepaliveTimeout: number path: string port: number protocol: string readTimeout: number sslProtocols: string[]}
interface CloudFrontRequest { clientIp: string; headers: CloudFrontHeaders; method: string; querystring: string; uri: string;export interface CloudFrontRequest { clientIp: string headers: CloudFrontHeaders method: string querystring: string uri: string body?: { inputTruncated: boolean; action: string; encoding: string; data: string; }; inputTruncated: boolean action: string encoding: string data: string } origin?: { custom: CloudFrontCustomOrigin; }; custom: CloudFrontCustomOrigin }}
interface CloudFrontConfig { distributionDomainName: string; distributionId: string; eventType: string; requestId: string; distributionDomainName: string distributionId: string eventType: string requestId: string}
interface CloudFrontEvent { cf: { config: CloudFrontConfig; request: CloudFrontRequest; }; config: CloudFrontConfig request: CloudFrontRequest }}
interface CloudFrontEdgeEvent { Records: CloudFrontEvent[];export interface CloudFrontEdgeEvent { Records: CloudFrontEvent[]}
type CloudFrontContext = {}
export interface Callback { (err: Error | null, result?: CloudFrontRequest | CloudFrontResult): void}
// https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-generating-http-responses-in-requests.html#lambda-generating-http-responses-programming-modelinterface CloudFrontResult { status: string; statusDescription?: string; status: string statusDescription?: string headers?: { [header: string]: { key: string; value: string; }[]; }; body?: string; bodyEncoding?: 'text' | 'base64'; [header: string]: { key: string value: string }[] } body?: string bodyEncoding?: 'text' | 'base64'}
/** * Accepts events from 'Lambda@Edge' event * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html */
// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const handle = (app: Hono) => {export const handle = (app: Hono<any>) => { return async ( event: CloudFrontEdgeEvent event: CloudFrontEdgeEvent, context?: CloudFrontContext, callback?: Callback ): Promise<CloudFrontResult> => { const req = createRequest(event) const res = await app.fetch(req)
const res = await app.fetch(req, { event, context, callback, request: event.Records[0].cf.request, }) return createResult(res) }}
const createResult = async (res: Response): Promise<CloudFrontResult> => { const isBase64Encoded = isContentTypeBinary(res.headers.get('content-type') || '') const isBase64Encoded = isContentTypeBinary(res.headers.get('content-type') || '')
const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text() const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()
const headers: { [header: string]: { key: string; value: string }[] } = {} const headers: { [header: string]: { key: string; value: string }[] } = {}
res.headers.forEach((value, key) => { headers[key.toLowerCase()] = [{ key: key.toLowerCase(), value }] }) res.headers.forEach((value, key) => { headers[key.toLowerCase()] = [{ key: key.toLowerCase(), value }] })
return { status: res.status.toString(), headers, body, } return { status: res.status.toString(), headers, body, }}
const createRequest = ( event: CloudFrontEdgeEvent) => {const createRequest = (event: CloudFrontEdgeEvent) => { const queryString = extractQueryString(event) 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)) { v.forEach(header => headers.set(k, header.value)) v.forEach((header) => headers.set(k, header.value)) } const method = event.Records[0].cf.request.method const method = event.Records[0].cf.request.method const requestInit: RequestInit = { headers, method, }
const requestBody = event.Records[0].cf.request.body requestInit.body = requestInit.body = requestBody?.encoding === 'base64' && requestBody?.data ? atob(requestBody.data) : requestBody?.data requestBody?.encoding === 'base64' && requestBody?.data ? atob(requestBody.data) : requestBody?.data return new Request(url, requestInit)}
const extractQueryString = ( event: CloudFrontEdgeEvent) => {const extractQueryString = (event: CloudFrontEdgeEvent) => { return event.Records[0].cf.request.querystring}
export const isContentTypeBinary = (contentType: string) => { return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml)$/.test( contentType )}No newline at end of file}modified:src/adapter/lambda-edge/index.ts+1 added
123// @denoify-ignoreexport { handle } from './handler'export type { Callback, CloudFrontRequest, CloudFrontEdgeEvent } from './handler'