Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added proxy config for complex proxy rules #907

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
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
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,12 @@ with the provided Dockerfile.
|`-U` or `--utc` |Use UTC time format in log messages.| |
|`--log-ip` |Enable logging of the client's IP address |`false` |
|`-P` or `--proxy` |Proxies all requests which can't be resolved locally to the given url. e.g.: -P http://someurl.com | |
|`--proxy-options` |Pass proxy [options](https://github.com/http-party/node-http-proxy#options) using nested dotted objects. e.g.: --proxy-options.secure false |
|`--proxy-options` |Pass proxy [options](https://github.com/http-party/node-http-proxy#options) using nested dotted objects. e.g.: --proxy-options.secure false | |
|`--proxy-config` |Pass in `.json` configuration file. e.g.: `./path/to/config.json` | |
|`--username` |Username for basic authentication | |
|`--password` |Password for basic authentication | |
|`-S`, `--tls` or `--ssl` |Enable secure request serving with TLS/SSL (HTTPS)|`false`|
|`-C` or `--cert` |Path to ssl cert file |`cert.pem` |
|`-C` or `--cert` |Path to ssl cert file |`cert.pem` |
|`-K` or `--key` |Path to ssl key file |`key.pem` |
|`-r` or `--robots` | Automatically provide a /robots.txt (The content of which defaults to `User-agent: *\nDisallow: /`) | `false` |
|`--no-dotfiles` |Do not show dotfiles| |
Expand Down
16 changes: 16 additions & 0 deletions bin/http-server
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ if (argv.h || argv.help) {
'',
' -P --proxy Fallback proxy if the request cannot be resolved. e.g.: http://someurl.com',
' --proxy-options Pass options to proxy using nested dotted objects. e.g.: --proxy-options.secure false',
' --proxy-config Pass in .json configuration file. e.g.: ./path/to/config.json',
'',
' --username Username for basic authentication [none]',
' Can also be specified with the env variable NODE_HTTP_SERVER_USERNAME',
Expand All @@ -76,6 +77,7 @@ var port = argv.p || argv.port || parseInt(process.env.PORT, 10),
sslPassphrase = process.env.NODE_HTTP_SERVER_SSL_PASSPHRASE,
proxy = argv.P || argv.proxy,
proxyOptions = argv['proxy-options'],
proxyConfig = argv['proxy-config'],
utc = argv.U || argv.utc,
version = argv.v || argv.version,
baseDir = argv['base-dir'],
Expand Down Expand Up @@ -157,6 +159,7 @@ function listen(port) {
logFn: logger.request,
proxy: proxy,
proxyOptions: proxyOptions,
proxyConfig: proxyConfig,
showDotfiles: argv.dotfiles,
mimetypes: argv.mimetypes,
username: argv.username || process.env.NODE_HTTP_SERVER_USERNAME,
Expand Down Expand Up @@ -199,6 +202,19 @@ function listen(port) {
}
}

if (proxyConfig) {
try {
proxyConfig = JSON.parse(fs.readFileSync(proxyConfig));
}
catch (err) {
logger.info(chalk.red('Error: Invalid proxy config file'));
process.exit(1);
}
// Proxy file overrides cli config
proxy = undefined;
proxyOptions = undefined;
}

if (tls) {
options.https = {
cert: argv.C || argv.cert || 'cert.pem',
Expand Down
4 changes: 4 additions & 0 deletions doc/http-server.1
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ Fallback proxy if the request cannot be resolved.
.BI \-\-proxy\-options
Pass proxy options using nested dotted objects.

.TP
.BI \-\-proxy\-config
Pass in .json configuration file.

.TP
.BI \-\-username " " \fIUSERNAME\fR
Username for basic authentication.
Expand Down
36 changes: 36 additions & 0 deletions lib/http-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,42 @@ function HttpServer(options) {
});
}

if (typeof options.proxyConfig === 'object') {
var proxy = httpProxy.createProxyServer();
before.push(function (req, res) {
var matchOptions = {};

for (var key of Object.keys(options.proxyConfig)) {
// Parse simplified regex to real working regex
// TODO: Add single path element regex (e.g. '/some/$/path' -> '/some/[^/]*/path')
var regexString = key.replaceAll('*', '.*');
var regex = new RegExp(regexString);
if (regex.test(req.url)) {
var matchConfig = options.proxyConfig[key];

if (matchConfig.pathRewrite) {
Object.entries(matchConfig.pathRewrite).forEach(rewrite => {
req.url = req.url.replace(new RegExp(rewrite[0]), rewrite[1]);
});
}

var configEntries = Object.entries(matchConfig).filter(entry => entry[0] !== "pathRewrite");
configEntries.forEach(entry => matchOptions[entry[0]] = entry[1]);
break;
}
}

proxy.web(req, res, matchOptions, function (err, req, res) {
if (options.logFn) {
options.logFn(req, res, {
message: err.message,
status: res.statusCode });
}
res.emit('next');
});
});
}

var serverOptions = {
before: before,
headers: this.headers,
Expand Down
107 changes: 107 additions & 0 deletions test/proxy-config.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
const test = require('tap').test
const path = require('path')
const fs = require('fs')
const request = require('request')
const httpServer = require('../lib/http-server')
const promisify = require('util').promisify

const requestAsync = promisify(request)
const fsReadFile = promisify(fs.readFile)

// Prevent errors from being swallowed
process.on('uncaughtException', console.error)

const root = path.join(__dirname, 'fixtures', 'root')
const httpsOpts = {
key: path.join(__dirname, 'fixtures', 'https', 'agent2-key.pem'),
cert: path.join(__dirname, 'fixtures', 'https', 'agent2-cert.pem')
}

const proxyConfigTest = {
"/rewrite/*": {
"target": "http://localhost:8082",
"pathRewrite": {
"^/rewrite": ""
}
},
"*": {
"target": "http://localhost:8082",
"changeOrigin": true,
"secure": false
}
}

// Tests are grouped into those which can run together. The groups are given
// their own port to run on and live inside a Promise. Tests are done when all
// Promise test groups complete.
test('proxy config', (t) => {
new Promise((resolve) => {
const server = httpServer.createServer({
root,
robots: true,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true'
},
cors: true,
corsHeaders: 'X-Test',
ext: true,
brotli: true,
gzip: true
})
// TODO #723 we should use portfinder
server.listen(8082, async () => {
try {

// Another server proxies 8083 to 8082
const proxyServer = httpServer.createServer({
//tls: true,
//https: httpsOpts,
proxyConfig: proxyConfigTest
})

await new Promise((resolve) => {
proxyServer.listen(8083, async () => {
try {
// Serve files from proxy root
await requestAsync('http://localhost:8083/file', { rejectUnauthorized: false }).then(async (res) => {
t.ok(res)
t.equal(res.statusCode, 200)

// File content matches
const fileData = await fsReadFile(path.join(root, 'file'), 'utf8')
t.equal(res.body.trim(), fileData.trim(), 'proxied file content matches')
}).catch(err => t.fail(err.toString()))

// Serve files from proxy with rewrite
await requestAsync('http://localhost:8083/rewrite/file', { rejectUnauthorized: false }).then(async (res) => {
t.ok(res)
t.equal(res.statusCode, 200)

// File content matches
const fileData = await fsReadFile(path.join(root, 'file'), 'utf8')
t.equal(res.body.trim(), fileData.trim(), 'proxied file content matches')
}).catch(err => t.fail(err.toString()))
} catch (err) {
t.fail(err.toString())
} finally {
proxyServer.close()
resolve()
}
})
})

} catch (err) {
t.fail(err.toString())
} finally {
server.close()
resolve()
}
})
})
.then(() => t.end())
.catch(err => {
t.fail(err.toString())
t.end()
})
})