From df3978421b86991fb45256f1a8694e0590019b13 Mon Sep 17 00:00:00 2001 From: Luca Maraschi Date: Sun, 4 Dec 2016 09:32:51 +0100 Subject: [PATCH] http: verify client method is a string Prior to this commit, it was possible to pass a truthy non-string value as the HTTP method to the HTTP client, resulting in an exception being thrown. This commit adds validation to the method. PR-URL: https://github.com/nodejs/node/pull/10111 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- lib/_http_client.js | 6 ++- .../test-http-client-check-http-token.js | 40 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 test/parallel/test-http-client-check-http-token.js diff --git a/lib/_http_client.js b/lib/_http_client.js index 6837c94df98eea..85e865f565a039 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -68,7 +68,11 @@ function ClientRequest(options, cb) { self.socketPath = options.socketPath; self.timeout = options.timeout; - var method = self.method = (options.method || 'GET').toUpperCase(); + var method = options.method; + if (method != null && typeof method !== 'string') { + throw new TypeError('Method must be a string'); + } + method = self.method = (method || 'GET').toUpperCase(); if (!common._checkIsHttpToken(method)) { throw new TypeError('Method must be a valid HTTP token'); } diff --git a/test/parallel/test-http-client-check-http-token.js b/test/parallel/test-http-client-check-http-token.js new file mode 100644 index 00000000000000..5a2b84a973262c --- /dev/null +++ b/test/parallel/test-http-client-check-http-token.js @@ -0,0 +1,40 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); + +const expectedSuccesses = [undefined, null, 'GET', 'post']; +let requestCount = 0; + +const server = http.createServer((req, res) => { + requestCount++; + res.end(); + + if (expectedSuccesses.length === requestCount) { + server.close(); + } +}).listen(0, test); + +function test() { + function fail(input) { + assert.throws(() => { + http.request({ method: input, path: '/' }, common.fail); + }, /^TypeError: Method must be a string$/); + } + + fail(-1); + fail(1); + fail(0); + fail({}); + fail(true); + fail(false); + fail([]); + + function ok(method) { + http.request({ method: method, port: server.address().port }).end(); + } + + expectedSuccesses.forEach((method) => { + ok(method); + }); +}