feat(adapter): AWS Lambda Adapter supports requests via Lambda@edge (#1210)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* edge-adaptor * add env * Revert "add env" This reverts commit 9662e574fd8b4a956956b3ce24bea73b6f2e4dbe. * Revert "add env" This reverts commit 9662e574fd8b4a956956b3ce24bea73b6f2e4dbe. * v0.1 * Revert "edge-adaptor" This reverts commit ed6b2566b10bd38b2dff629fdab1dc9c67b50efd. * runtimetest * WIP: runtime-test * lint * build lambda-edge * ci lambda-edge * remove gitpod * test fix * fix of self check
authored by watany · committed by GitHub · parent a8ebb47 · Browse files · 7 files·+808 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+808 added−1 removed
- tests:+630 added−0 removed
- other:+178 added−1 removed
Provenance
- Commit
edca699- Tree
ff787dc- Author
watany <76135106+watany-dev@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
a8ebb47
7 files changed+808 added−1 removed
modified:.github/workflows/ci.yml+12 added
97 unmodified lines989910010110210310410510610710810911011111211397 unmodified lines node-version: 18.x - run: yarn install --frozen-lockfile - run: npm run build - run: npm run test:lambda
lambda-edge: name: 'Lambda@Edge' runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: 18.x - run: yarn install --frozen-lockfile - run: npm run build - run: npm run test:lambda-edgeNo newline at end of fileadded:runtime_tests/lambda-edge/index.test.ts+615 added
1+import { handle } from '../../src/adapter/lambda-edge/handler'2+import { Hono } from '../../src/hono'3+import { basicAuth } from '../../src/middleware/basic-auth'4+5+describe('Lambda@Edge Adapter for Hono', () => {6+ const app = new Hono()7+8+ app.get('/', (c) => {9+ return c.text('Hello Lambda!')10+ })11+12+ app.get('/binary', (c) => {13+ return c.body('Fake Image', 200, {14+ 'Content-Type': 'image/png',15+ })16+ })17+18+ app.post('/post', async (c) => {19+ const body = (await c.req.parseBody()) as { message: string }20+ return c.text(body.message)21+ })22+23+ const username = 'hono-user-a'24+ const password = 'hono-password-a'25+ app.use('/auth/*', basicAuth({ username, password }))26+ app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))27+28+ const handler = handle(app)29+30+ it('Should handle a GET request and return a 200 response (Lambda@Edge viewer request)', async () => {31+ const event = {32+ "Records": [33+ {34+ "cf": {35+ "config": {36+ "distributionDomainName": "d111111abcdef8.cloudfront.net",37+ "distributionId": "EDFDVBD6EXAMPLE",38+ "eventType": "viewer-request",39+ "requestId": "4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ=="40+ },41+ "request": {42+ "clientIp": "203.0.113.178",43+ "headers": {44+ "host": [45+ {46+ "key": "Host",47+ "value": "d111111abcdef8.cloudfront.net"48+ }49+ ],50+ "user-agent": [51+ {52+ "key": "User-Agent",53+ "value": "curl/7.66.0"54+ }55+ ],56+ "accept": [57+ {58+ "key": "accept",59+ "value": "*/*"60+ }61+ ]62+ },63+ "method": "GET",64+ "querystring": "",65+ "uri": "/"66+ }67+ }68+ }69+ ]70+ }71+ const response = await handler(event)72+ expect(response.status).toBe('200');73+ expect(response.body).toBe('Hello Lambda!');74+ expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/);75+ })76+77+ it('Should handle a GET request and return a 200 response (Lambda@Edge origin request)', async () => {78+ const event = {79+ "Records": [80+ {81+ "cf": {82+ "config": {83+ "distributionDomainName": "d111111abcdef8.cloudfront.net",84+ "distributionId": "EDFDVBD6EXAMPLE",85+ "eventType": "origin-request",86+ "requestId": "4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ=="87+ },88+ "request": {89+ "clientIp": "203.0.113.178",90+ "headers": {91+ "x-forwarded-for": [92+ {93+ "key": "X-Forwarded-For",94+ "value": "203.0.113.178"95+ }96+ ],97+ "user-agent": [98+ {99+ "key": "User-Agent",100+ "value": "Amazon CloudFront"101+ }102+ ],103+ "via": [104+ {105+ "key": "Via",106+ "value": "2.0 2afae0d44e2540f472c0635ab62c232b.cloudfront.net (CloudFront)"107+ }108+ ],109+ "host": [110+ {111+ "key": "Host",112+ "value": "example.org"113+ }114+ ],115+ "cache-control": [116+ {117+ "key": "Cache-Control",118+ "value": "no-cache"119+ }120+ ]121+ },122+ "method": "GET",123+ "origin": {124+ "custom": {125+ "customHeaders": {},126+ "domainName": "example.org",127+ "keepaliveTimeout": 5,128+ "path": "",129+ "port": 443,130+ "protocol": "https",131+ "readTimeout": 30,132+ "sslProtocols": [133+ "TLSv1",134+ "TLSv1.1",135+ "TLSv1.2"136+ ]137+ }138+ },139+ "querystring": "",140+ "uri": "/"141+ }142+ }143+ }144+ ]145+ }146+ const response = await handler(event)147+ expect(response.status).toBe('200');148+ expect(response.body).toBe('Hello Lambda!');149+ expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/);150+ })151+152+ it('Should handle a GET request and return a 200 response (Lambda@Edge viewer response)', async () => {153+ const event = {154+ "Records": [155+ {156+ "cf": {157+ "config": {158+ "distributionDomainName": "d111111abcdef8.cloudfront.net",159+ "distributionId": "EDFDVBD6EXAMPLE",160+ "eventType": "viewer-response",161+ "requestId": "4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ=="162+ },163+ "request": {164+ "clientIp": "203.0.113.178",165+ "headers": {166+ "host": [167+ {168+ "key": "Host",169+ "value": "d111111abcdef8.cloudfront.net"170+ }171+ ],172+ "user-agent": [173+ {174+ "key": "User-Agent",175+ "value": "curl/7.66.0"176+ }177+ ],178+ "accept": [179+ {180+ "key": "accept",181+ "value": "*/*"182+ }183+ ]184+ },185+ "method": "GET",186+ "querystring": "",187+ "uri": "/"188+ },189+ "response": {190+ "headers": {191+ "access-control-allow-credentials": [192+ {193+ "key": "Access-Control-Allow-Credentials",194+ "value": "true"195+ }196+ ],197+ "access-control-allow-origin": [198+ {199+ "key": "Access-Control-Allow-Origin",200+ "value": "*"201+ }202+ ],203+ "date": [204+ {205+ "key": "Date",206+ "value": "Mon, 13 Jan 2020 20:14:56 GMT"207+ }208+ ],209+ "referrer-policy": [210+ {211+ "key": "Referrer-Policy",212+ "value": "no-referrer-when-downgrade"213+ }214+ ],215+ "server": [216+ {217+ "key": "Server",218+ "value": "ExampleCustomOriginServer"219+ }220+ ],221+ "x-content-type-options": [222+ {223+ "key": "X-Content-Type-Options",224+ "value": "nosniff"225+ }226+ ],227+ "x-frame-options": [228+ {229+ "key": "X-Frame-Options",230+ "value": "DENY"231+ }232+ ],233+ "x-xss-protection": [234+ {235+ "key": "X-XSS-Protection",236+ "value": "1; mode=block"237+ }238+ ],239+ "age": [240+ {241+ "key": "Age",242+ "value": "2402"243+ }244+ ],245+ "content-type": [246+ {247+ "key": "Content-Type",248+ "value": "text/html; charset=utf-8"249+ }250+ ],251+ "content-length": [252+ {253+ "key": "Content-Length",254+ "value": "9593"255+ }256+ ]257+ },258+ "status": "200", "statusDescription": "OK"259+ }260+ }261+ }262+ ]263+ }264+ const response = await handler(event)265+ expect(response.status).toBe('200');266+ expect(response.body).toBe('Hello Lambda!');267+ expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/);268+ })269+270+ it('Should handle a GET request and return a 200 response (Lambda@Edge origin response)', async () => {271+ const event = {272+ "Records": [273+ {274+ "cf": {275+ "config": {276+ "distributionDomainName": "d111111abcdef8.cloudfront.net",277+ "distributionId": "EDFDVBD6EXAMPLE",278+ "eventType": "origin-response",279+ "requestId": "4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ=="280+ },281+ "request": {282+ "clientIp": "203.0.113.178",283+ "headers": {284+ "x-forwarded-for": [285+ {286+ "key": "X-Forwarded-For",287+ "value": "203.0.113.178"288+ }289+ ],290+ "user-agent": [291+ {292+ "key": "User-Agent",293+ "value": "Amazon CloudFront"294+ }295+ ],296+ "via": [297+ {298+ "key": "Via",299+ "value": "2.0 8f22423015641505b8c857a37450d6c0.cloudfront.net (CloudFront)"300+ }301+ ],302+ "host": [303+ {304+ "key": "Host",305+ "value": "example.org"306+ }307+ ],308+ "cache-control": [309+ {310+ "key": "Cache-Control",311+ "value": "no-cache"312+ }313+ ]314+ },315+ "method": "GET",316+ "origin": {317+ "custom": {318+ "customHeaders": {},319+ "domainName": "example.org",320+ "keepaliveTimeout": 5,321+ "path": "",322+ "port": 443,323+ "protocol": "https",324+ "readTimeout": 30,325+ "sslProtocols": [326+ "TLSv1",327+ "TLSv1.1",328+ "TLSv1.2"329+ ]330+ }331+ },332+ "querystring": "",333+ "uri": "/"334+ },335+ "response": {336+ "headers": {337+ "access-control-allow-credentials": [338+ {339+ "key": "Access-Control-Allow-Credentials",340+ "value": "true"341+ }342+ ],343+ "access-control-allow-origin": [344+ {345+ "key": "Access-Control-Allow-Origin",346+ "value": "*"347+ }348+ ],349+ "date": [350+ {351+ "key": "Date",352+ "value": "Mon, 13 Jan 2020 20:12:38 GMT"353+ }354+ ],355+ "referrer-policy": [356+ {357+ "key": "Referrer-Policy",358+ "value": "no-referrer-when-downgrade"359+ }360+ ],361+ "server": [362+ {363+ "key": "Server",364+ "value": "ExampleCustomOriginServer"365+ }366+ ],367+ "x-content-type-options": [368+ {369+ "key": "X-Content-Type-Options",370+ "value": "nosniff"371+ }372+ ],373+ "x-frame-options": [374+ {375+ "key": "X-Frame-Options",376+ "value": "DENY"377+ }378+ ],379+ "x-xss-protection": [380+ {381+ "key": "X-XSS-Protection",382+ "value": "1; mode=block"383+ }384+ ],385+ "content-type": [386+ {387+ "key": "Content-Type",388+ "value": "text/html; charset=utf-8"389+ }390+ ],391+ "content-length": [392+ {393+ "key": "Content-Length",394+ "value": "9593"395+ }396+ ]397+ },398+ "status": "200",399+ "statusDescription": "OK"400+ }401+ }402+ }403+ ]404+ }405+ const response = await handler(event)406+ expect(response.status).toBe('200');407+ expect(response.body).toBe('Hello Lambda!');408+ expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/);409+ })410+411+ it('Should handle a GET request and return a 200 response with binary', async () => {412+ const event = {413+ Records: [414+ {415+ cf: {416+ config: {417+ distributionDomainName: 'example.com',418+ distributionId: 'EXAMPLE123',419+ eventType: 'viewer-request',420+ requestId: 'exampleRequestId',421+ },422+ request: {423+ clientIp: '123.123.123.123',424+ headers: {425+ 'host': [426+ {427+ key: 'Host',428+ value: 'example.com',429+ },430+ ],431+ },432+ method: 'GET',433+ querystring: '',434+ uri: '/binary',435+ },436+ },437+ },438+ ],439+ };440+ 441+ const response = await handler(event);442+ 443+ expect(response.status).toBe('200');444+ expect(response.body).toBe('RmFrZSBJbWFnZQ=='); // base64 encoded fake image445+ expect(response.headers['content-type'][0].value).toMatch(/^image\/png/);446+ });447+ 448+ it('Should handle a GET request and return a 404 response', async () => {449+ const event = {450+ Records: [451+ {452+ cf: {453+ config: {454+ distributionDomainName: 'example.com',455+ distributionId: 'EXAMPLE123',456+ eventType: 'viewer-request',457+ requestId: 'exampleRequestId',458+ },459+ request: {460+ clientIp: '123.123.123.123',461+ headers: {462+ 'host': [463+ {464+ key: 'Host',465+ value: 'example.com',466+ },467+ ],468+ },469+ method: 'GET',470+ querystring: '',471+ uri: '/nothing',472+ },473+ },474+ },475+ ],476+ };477+ 478+ const response = await handler(event);479+ 480+ expect(response.status).toBe('404');481+ });482+483+ it('Should handle a POST request and return a 200 response', async () => {484+ const searchParam = new URLSearchParams();485+ searchParam.append('message', 'Good Morning Lambda!');486+ 487+ const event = {488+ Records: [489+ {490+ cf: {491+ config: {492+ distributionDomainName: 'example.com',493+ distributionId: 'EXAMPLE123',494+ eventType: 'viewer-request',495+ requestId: 'exampleRequestId',496+ },497+ request: {498+ clientIp: '123.123.123.123',499+ headers: {500+ 'host': [501+ {502+ key: 'Host',503+ value: 'example.com',504+ },505+ ],506+ 'content-type': [507+ {508+ key: 'Content-Type',509+ value: 'application/x-www-form-urlencoded',510+ },511+ ],512+ },513+ method: 'POST',514+ querystring: '',515+ uri: '/post',516+ body: {517+ inputTruncated: false,518+ action: 'read-only',519+ encoding: 'base64',520+ data: btoa(searchParam.toString()),521+ },522+ },523+ },524+ },525+ ],526+ };527+528+ const response = await handler(event);529+ 530+ expect(response.status).toBe('200');531+ expect(response.body).toBe('Good Morning Lambda!');532+ });533+534+ it('Should handle a request and return a 401 response with Basic auth', async () => {535+ const event = {536+ Records: [537+ {538+ cf: {539+ config: {540+ distributionDomainName: 'example.com',541+ distributionId: 'EXAMPLE123',542+ eventType: 'viewer-request',543+ requestId: 'exampleRequestId',544+ },545+ request: {546+ clientIp: '123.123.123.123',547+ headers: {548+ 'host': [549+ {550+ key: 'Host',551+ value: 'example.com',552+ },553+ ],554+ 'content-type': [555+ {556+ key: 'Content-Type',557+ value: 'plain/text',558+ },559+ ],560+ },561+ method: 'GET',562+ querystring: '',563+ uri: '/auth/abc',564+ },565+ },566+ },567+ ],568+ };569+ 570+ const response = await handler(event);571+ 572+ expect(response.status).toBe('401');573+ });574+ 575+ it('Should handle a request and return a 401 response with Basic auth', async () => {576+ const event = {577+ Records: [578+ {579+ cf: {580+ config: {581+ distributionDomainName: 'example.com',582+ distributionId: 'EXAMPLE123',583+ eventType: 'viewer-request',584+ requestId: 'exampleRequestId',585+ },586+ request: {587+ clientIp: '123.123.123.123',588+ headers: {589+ 'host': [590+ {591+ key: 'Host',592+ value: 'example.com',593+ },594+ ],595+ 'content-type': [596+ {597+ key: 'Content-Type',598+ value: 'plain/text',599+ },600+ ],601+ },602+ method: 'GET',603+ querystring: '',604+ uri: '/auth/abc',605+ },606+ },607+ },608+ ],609+ };610+ 611+ const response = await handler(event);612+ 613+ expect(response.status).toBe('401');614+ });615+});added:runtime_tests/lambda-edge/jest.config.js+7 added
1234567export default { testMatch: ['**/runtime_tests/lambda-edge/**/*.+(ts|tsx|js)'], transform: { '^.+\\.(ts|tsx)$': 'ts-jest', }, testPathIgnorePatterns: ['jest.config.js'],}added:src/adapter/lambda-edge/handler.test.ts+15 added
123456789101112131415import { isContentTypeBinary } from './handler'
describe('isContentTypeBinary', () => { it('Should determine whether it is binary', () => { expect(isContentTypeBinary('image/png')).toBe(true) expect(isContentTypeBinary('font/woff2')).toBe(true) expect(isContentTypeBinary('text/plain')).toBe(false) expect(isContentTypeBinary('text/plain; charset=UTF-8')).toBe(false) expect(isContentTypeBinary('text/css')).toBe(false) expect(isContentTypeBinary('text/javascript')).toBe(false) expect(isContentTypeBinary('application/json')).toBe(false) expect(isContentTypeBinary('application/ld+json')).toBe(false) expect(isContentTypeBinary('application/json; charset=UTF-8')).toBe(false) })})added:src/adapter/lambda-edge/handler.ts+147 added
1+// @denoify-ignore2+import crypto from 'crypto'3+import type { Hono } from '../../hono'4+5+import { encodeBase64 } from '../../utils/encode'6+7+// eslint-disable-next-line @typescript-eslint/ban-ts-comment8+// @ts-ignore9+globalThis.crypto ??= crypto10+11+interface CloudFrontHeader {12+ key: string;13+ value: string;14+}15+16+interface CloudFrontHeaders {17+ [name: string]: CloudFrontHeader[];18+}19+20+interface CloudFrontCustomOrigin {21+ customHeaders: CloudFrontHeaders;22+ domainName: string;23+ keepaliveTimeout: number;24+ path: string;25+ port: number;26+ protocol: string;27+ readTimeout: number;28+ sslProtocols: string[];29+}30+31+interface CloudFrontRequest {32+ clientIp: string;33+ headers: CloudFrontHeaders;34+ method: string;35+ querystring: string;36+ uri: string;37+ body?: {38+ inputTruncated: boolean;39+ action: string;40+ encoding: string;41+ data: string;42+ };43+ origin?: {44+ custom: CloudFrontCustomOrigin;45+ };46+}47+48+interface CloudFrontConfig {49+ distributionDomainName: string;50+ distributionId: string;51+ eventType: string;52+ requestId: string;53+}54+55+interface CloudFrontEvent {56+ cf: {57+ config: CloudFrontConfig;58+ request: CloudFrontRequest;59+ };60+}61+62+interface CloudFrontEdgeEvent {63+ Records: CloudFrontEvent[];64+}65+66+interface CloudFrontResult {67+ status: string;68+ statusDescription?: string;69+ headers: {70+ [header: string]: {71+ key?: string;72+ value: string;73+ }[];74+ };75+ body?: string;76+}77+78+/**79+ * Accepts events from 'Lambda@Edge' event80+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html81+ */82+export const handle = (app: Hono) => {83+ return async (84+ event: CloudFrontEdgeEvent85+ ): Promise<CloudFrontResult> => {86+ const req = createRequest(event)87+ const res = await app.fetch(req)88+89+ return createResult(res)90+ }91+}92+93+const createResult = async (res: Response): Promise<CloudFrontResult> => {94+ const isBase64Encoded = isContentTypeBinary(res.headers.get('content-type') || '')95+96+ const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()97+98+ const headers: { [header: string]: { key: string; value: string }[] } = {}99+100+ res.headers.forEach((value, key) => {101+ headers[key.toLowerCase()] = [{ key: key.toLowerCase(), value }]102+ })103+104+ return {105+ status: res.status.toString(),106+ headers,107+ body,108+ }109+}110+111+const createRequest = (112+ event: CloudFrontEdgeEvent113+) => {114+ const queryString = extractQueryString(event)115+ const urlPath = `https://${event.Records[0].cf.config.distributionDomainName}${event.Records[0].cf.request.uri}`116+ const url = queryString ? `${urlPath}?${queryString}` : urlPath117+118+ const headers = new Headers()119+ for (const [k, v] of Object.entries(event.Records[0].cf.request.headers)) {120+ if (Array.isArray(v)) {121+ v.forEach(header => headers.set(k, header.value))122+ }123+ }124+ const method = event.Records[0].cf.request.method 125+ const requestInit: RequestInit = {126+ headers,127+ method,128+ }129+130+ const requestBody = event.Records[0].cf.request.body131+ requestInit.body = requestBody?.encoding === 'base64' && requestBody?.data132+ ? atob(requestBody.data)133+ : requestBody?.data134+ return new Request(url, requestInit)135+}136+137+const extractQueryString = (138+ event: CloudFrontEdgeEvent139+) => {140+ return event.Records[0].cf.request.querystring141+}142+143+export const isContentTypeBinary = (contentType: string) => {144+ return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml)$/.test(145+ contentType146+ )147+}added:src/adapter/lambda-edge/index.ts+2 added
12// @denoify-ignoreexport { handle } from './handler'modified:package.json+10 added-1 removed
16 unmodified lines17 "test:lagon": "start-server-and-test \"lagon dev runtime_tests/lagon/index.ts -e runtime_tests/lagon/.env.lagon\" http://127.0.0.1:1234 \"yarn jest runtime_tests/lagon/index.test.ts --testMatch '**/*.test.ts'\"",18 "test:node": "env NAME=Node jest --config ./runtime_tests/node/jest.config.js",19 "test:wrangler": "jest --config ./runtime_tests/wrangler/jest.config.js",20 "test:lambda": "env NAME=Node jest --config ./runtime_tests/lambda/jest.config.js",21+ "test:lambda-edge": "env NAME=Node jest --config ./runtime_tests/lambda-edge/jest.config.js",21- "test:all": "yarn test && yarn test:deno && yarn test:bun && yarn test:fastly && yarn test:lagon && yarn test:node && yarn test:wrangler && yarn test:lambda",22+ "test:all": "yarn test && yarn test:deno && yarn test:bun && yarn test:fastly && yarn test:lagon && yarn test:node && yarn test:wrangler && yarn test:lambda && yarn test:lambda-edge",23 "lint": "eslint --ext js,ts src .eslintrc.cjs",24 "lint:fix": "eslint --ext js,ts src .eslintrc.cjs --fix",25 "denoify": "rimraf deno_dist && denoify && rimraf 'deno_dist/**/*.test.ts'",26 "copy:package.cjs.json": "cp ./package.cjs.json ./dist/cjs/package.json && cp ./package.cjs.json ./dist/types/package.json ",187 unmodified lines214 "./vercel": {215 "types": "./dist/types/adapter/vercel/index.d.ts",216 "import": "./dist/adapter/vercel/index.js",217 "require": "./dist/cjs/adapter/vercel/index.js"218+ },219+ "./lambda-edge": {220+ "types": "./dist/types/adapter/lambda-edge/index.d.ts",221+ "import": "./dist/adapter/lambda-edge/index.js",222+ "require": "./dist/cjs/adapter/lambda-edge/index.js"223 }224 },225 "typesVersions": {226 "*": {103 unmodified lines330 "./dist/types/adapter/aws-lambda"331 ],332 "vercel": [333 "./dist/types/adapter/vercel"334+ ],335+ "lambda-edge": [336+ "./dist/types/adapter/lambda-edge"337 ]338 }339 },340 "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",72 unmodified lines