Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const URL = require('url');

const Request = require('../../request');
const Request = require('../../../request');

function requestMethod(event) {
if (event.version === '2.0') {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
'use strict';

const isBinary = require('./is-binary');
const Response = require('../../response');
const Response = require('../../../response');
const sanitizeHeaders = require('./sanitize-headers');

module.exports = (event, response, options) => {
const { statusCode } = response;
const {headers, multiValueHeaders } = sanitizeHeaders(Response.headers(response));
const { headers, multiValueHeaders } = sanitizeHeaders(Response.headers(response));

if (headers['transfer-encoding'] === 'chunked' || response.chunkedEncoding) {
throw new Error('chunked encoding not supported');
Expand Down
15 changes: 15 additions & 0 deletions lib/provider/aws/api-gw/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const cleanUpEvent = require('./clean-up-event');

const createRequest = require('./create-request');
const formatResponse = require('./format-response');

module.exports = options => {
return getResponse => async (event_, context = {}) => {
const event = cleanUpEvent(event_, options);

const request = createRequest(event, context, options);
const response = await getResponse(request, event, context);

return formatResponse(event, response, options);
};
};
File renamed without changes.
20 changes: 8 additions & 12 deletions lib/provider/aws/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
const cleanUpEvent = require('./clean-up-event');

const createRequest = require('./create-request');
const formatResponse = require('./format-response');
const apiGw = require('./api-gw');
const lambdaEdgeOriginRequest = require('./lambda-edge-origin-request');

module.exports = options => {
return getResponse => async (event_, context = {}) => {
const event = cleanUpEvent(event_, options);

const request = createRequest(event, context, options);
const response = await getResponse(request, event, context);

return formatResponse(event, response, options);
};
switch (options.type) {
case 'lambda-edge-origin-request':
return lambdaEdgeOriginRequest(options)
default:
return apiGw(options)
}
};
28 changes: 28 additions & 0 deletions lib/provider/aws/lambda-edge-origin-request/clean-up-event.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict';

function removeBasePath(path = '/', basePath) {
if (basePath) {
const basePathIndex = path.indexOf(basePath);

if (basePathIndex > -1) {
return path.substr(basePathIndex + basePath.length) || '/';
}
}

return path;
}

module.exports = function cleanupEvent(evt, options) {
const event = evt || {};

event.config = event.config || {};

event.request = event.request || {};
event.request.body = event.request.body || {};
event.request.headers = event.request.headers || {};
event.request.method = event.request.method || 'GET';
console.debug(`url is ${event.request.uri} basePath is ${options.basePath}`);
event.request.uri = removeBasePath(event.uri, options.basePath);

return event;
};
64 changes: 64 additions & 0 deletions lib/provider/aws/lambda-edge-origin-request/create-request.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
'use strict';

const crypto = require('crypto');
const Request = require('../../../request');

function requestHeaders(event) {
let headers = Object.keys(event.request.headers).reduce((headers, key) => {
headers[event.request.headers[key][0].key.toLowerCase()] = event.request.headers[key][0].value;
return headers;
}, {});

headers['x-request-id'] = crypto.randomBytes(30).toString('base64')

return headers;
}

function requestBody(event) {
const body = event && event.request && event.request.body && event.request.body.data;
const type = typeof body;

console.debug('hello world');
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be here?

if (!body) return '';

if (Buffer.isBuffer(body)) return body;

switch (type) {
case 'string':
return Buffer.from(body, event.request.body.encoding === 'base64' ? 'base64' : 'utf8');
case 'object':
return Buffer.from(JSON.stringify(body));
default:
throw new Error(`Unexpected event.body type: ${typeof event.request.body.data}`);
}
}

function getUrl(path, queryString) {
if (queryString) {
return `${path}?${queryString}`
}

return path;
}

module.exports = (event, options) => {
const method = event.request.method;
const remoteAddress = event.request.clientIp;
const headers = requestHeaders(event);
const body = requestBody(event);

if (typeof options.requestId === 'string' && options.requestId.length > 0) {
const header = options.requestId.toLowerCase();
headers[header] = headers[header] || event.config.requestId;
}

const req = new Request({
method,
headers,
body,
remoteAddress,
url: getUrl(event.request.uri, event.request.querystring)
});

return req;
};
25 changes: 25 additions & 0 deletions lib/provider/aws/lambda-edge-origin-request/format-response.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
'use strict';

const isBinary = require('./is-binary');
const Response = require('../../../response');
const sanitizeHeaders = require('./sanitize-headers');

module.exports = (response, options) => {
const { statusCode } = response;
const headers = Response.headers(response);

if (headers['transfer-encoding'] === 'chunked' || response.chunkedEncoding) {
throw new Error('chunked encoding not supported');
}

const isBase64Encoded = isBinary(headers, options);
const encoding = isBase64Encoded ? 'base64' : 'utf8';
let body = Response.body(response).toString(encoding);

return {
statusCode,
headers: sanitizeHeaders(headers),
body,
bodyEncoding: isBase64Encoded ? 'base64' : 'text'
};
};
16 changes: 16 additions & 0 deletions lib/provider/aws/lambda-edge-origin-request/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const cleanUpEvent = require('./clean-up-event');

const createRequest = require('./create-request');
const formatResponse = require('./format-response');

module.exports = options => {
return getResponse => async (event_, context = {}) => {
const event = cleanUpEvent(event_, options);
console.debug(event);
const request = createRequest(event, options);
const response = await getResponse(request, event, context);
const formattedResponse = formatResponse(response, options);

return formattedResponse;
};
};
38 changes: 38 additions & 0 deletions lib/provider/aws/lambda-edge-origin-request/is-binary.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
'use strict';

const BINARY_ENCODINGS = ['gzip', 'deflate', 'br'];
const BINARY_CONTENT_TYPES = (process.env.BINARY_CONTENT_TYPES || '').split(',');

function isBinaryEncoding(headers) {
const contentEncoding = headers['content-encoding'];

if (typeof contentEncoding === 'string') {
return contentEncoding.split(',').some(value =>
BINARY_ENCODINGS.some(binaryEncoding => value.indexOf(binaryEncoding) !== -1)
);
}
}

function isBinaryContent(headers, options) {
const contentTypes = [].concat(options.binary
? options.binary
: BINARY_CONTENT_TYPES
).map(candidate =>
new RegExp(`^${candidate.replace(/\*/g, '.*')}$`)
);

const contentType = (headers['content-type'] || '').split(';')[0];
return !!contentType && contentTypes.some(candidate => candidate.test(contentType));
}

module.exports = function isBinary(headers, options) {
if (options.binary === false) {
return false;
}

if (typeof options.binary === 'function') {
return options.binary(headers);
}

return isBinaryEncoding(headers) || isBinaryContent(headers, options);
};
61 changes: 61 additions & 0 deletions lib/provider/aws/lambda-edge-origin-request/sanitize-headers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
'use strict';

// See: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-requirements-limits.html#lambda-read-only-headers
const readOnlyHeaders = [
'accept-encoding',
'content-length',
'if-modified-since',
'if-none-Match',
'if-range',
'if-unmodified-since',
'range',
'transfer-encoding',
'via'
];

// See: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-requirements-limits.html#lambda-blacklisted-headers
const blacklistedHeaders = [
'connection',
'expect',
'keep-alive',
'proxy-authenticate',
'proxy-authorization',
'proxy-connection',
'trailer',
'upgrade',
'x-accel-buffering',
'x-accel-charset',
'x-accel-limit-rate',
'x-accel-redirect',
'x-cache',
'x-forwarded-proto',
'x-real-ip',
]

const omittedHeaders = [...readOnlyHeaders, ...blacklistedHeaders]

module.exports = function sanitizeHeaders(headers) {
return Object.keys(headers).reduce((memo, key) => {
const value = headers[key];
const normalizedKey = key.toLowerCase();

if (omittedHeaders.includes(normalizedKey)) {
return memo;
}

if (memo[normalizedKey] === undefined) {
memo[normalizedKey] = []
}

const valueArray = Array.isArray(value) ? value : [value]

valueArray.forEach(valueElement => {
memo[normalizedKey].push({
key: key,
value: valueElement
});
});

return memo;
}, {});
};
11 changes: 11 additions & 0 deletions test/base-path.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,17 @@ describe('base path', () => {
expect(response.body).to.equal(expectedFooResponse)
});
});

it(`should work with a lambda-edge-origin-request (${testCase})`, () => {
return request(fooApp, {
method: 'GET',
uri: testCase,
}, { basePath: '/foo', provider: 'aws', type: 'lambda-edge-origin-request' })
.then(response => {
expect(response.statusCode).to.equal(200);
expect(response.body).to.equal(expectedFooResponse);
});
});
});

[
Expand Down
10 changes: 9 additions & 1 deletion test/clean-up-event.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
'use strict';

const cleanUpEvent = require('../lib/provider/aws/clean-up-event.js');
const cleanUpEvent = require('../lib/provider/aws/api-gw/clean-up-event');
const cleanUpEventLambdaEdge = require('../lib/provider/aws/lambda-edge-origin-request/clean-up-event');

const edgeOriginRequest = require('./fixtures/origin-request.json');

const expect = require('chai').expect;

describe('clean up event', () => {
Expand Down Expand Up @@ -341,4 +345,8 @@ describe('clean up event', () => {
});

});

it('should clean up lambda edge origin payload format correctly', () => {
cleanUpEventLambdaEdge(edgeOriginRequest, { basePath: '/my' });
});
});
Loading