diff --git a/index.js b/index.js index 14def08..8a4f7cd 100644 --- a/index.js +++ b/index.js @@ -5,6 +5,7 @@ const lru = require('tiny-lru') const querystring = require('querystring') const Stream = require('stream') const buildRequest = require('./lib/request') + const { filterPseudoHeaders, copyHeaders, @@ -43,6 +44,15 @@ function fastProxy (opts = {}) { const sourceHttp2 = req.httpVersionMajor === 2 let headers = { ...sourceHttp2 ? filterPseudoHeaders(req.headers) : req.headers } + if (!headers.host) { + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Host + // @TODO: Should add performance-aware host header value validation(regex-based) as a further step? + res.statusCode = 400 + res.end() + + return + } + headers['x-forwarded-host'] = headers.host headers.host = url.hostname if (url.port) { diff --git a/test/11.host-header-val.test.js b/test/11.host-header-val.test.js new file mode 100644 index 0000000..4334c83 --- /dev/null +++ b/test/11.host-header-val.test.js @@ -0,0 +1,39 @@ +/* global describe, it */ +'use strict' + +const request = require('supertest') +let gateway, close, proxy, gHttpServer + +describe('Host header validation', () => { + it('init', async () => { + const fastProxy = require('../index')({ + base: 'http://127.0.0.1:3000' + }) + + proxy = fastProxy.proxy + close = fastProxy.close + }) + + it('init & start gateway', async () => { + // init gateway + gateway = require('restana')() + + gateway.all('/service/*', function (req, res) { + delete req.headers.host + proxy(req, res, req.url, {}) + }) + + gHttpServer = await gateway.start(8080) + }) + + it('should fail with Bad Request when Host header is missing', async () => { + await request(gHttpServer) + .get('/service/headers') + .expect(400) + }) + + it('close all', async () => { + close() + await gateway.close() + }) +})