From 9ec4133642f368c84ef7ac9650d2bd43a78b757a Mon Sep 17 00:00:00 2001 From: James M Snell Date: Tue, 18 Apr 2017 13:33:51 -0700 Subject: [PATCH] http: add type checking for hostname Add type checking for options.hostname / options.host Maintains the use of `undefined` and `null` for default `localhost`, but other falsy values (like `false`, `0` and `NaN`) are rejected. --- lib/_http_client.js | 11 +++++++- .../test-http-hostname-typechecking.js | 27 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 test/parallel/test-http-hostname-typechecking.js diff --git a/lib/_http_client.js b/lib/_http_client.js index 2205e89d2ae3d6..42387d0930b583 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -65,6 +65,14 @@ function isInvalidPath(s) { return false; } +function validateHost(host, name) { + if (host != null && typeof host !== 'string') { + throw new TypeError( + `"options.${name}" must either be a string, undefined or null`); + } + return host; +} + function ClientRequest(options, cb) { OutgoingMessage.call(this); @@ -123,7 +131,8 @@ function ClientRequest(options, cb) { this.agent && this.agent.defaultPort; var port = options.port = options.port || defaultPort || 80; - var host = options.host = options.hostname || options.host || 'localhost'; + var host = options.host = validateHost(options.hostname, 'hostname') || + validateHost(options.host, 'host') || 'localhost'; var setHost = (options.setHost === undefined); diff --git a/test/parallel/test-http-hostname-typechecking.js b/test/parallel/test-http-hostname-typechecking.js new file mode 100644 index 00000000000000..89254f485bd962 --- /dev/null +++ b/test/parallel/test-http-hostname-typechecking.js @@ -0,0 +1,27 @@ +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); + +// All of these values should cause http.request() to throw synchronously +// when passed as the value of either options.hostname or options.host +const vals = [{}, [], NaN, Infinity, -Infinity, true, false, 1, 0, new Date()]; + +function errCheck(name) { + return new RegExp(`^TypeError: "options\\.${name}" must either be a ` + + 'string, undefined or null$'); +} + +vals.forEach((v) => { + assert.throws(() => http.request({hostname: v}), errCheck('hostname')); + assert.throws(() => http.request({host: v}), errCheck('host')); +}); + +// These values are OK and should not throw synchronously +['', undefined, null].forEach((v) => { + assert.doesNotThrow(() => { + http.request({hostname: v}).on('error', common.noop); + http.request({host: v}).on('error', common.noop); + }); +});