diff --git a/lib/internal/dns/utils.js b/lib/internal/dns/utils.js index 43b65418848f85..f6bace7528fc3a 100644 --- a/lib/internal/dns/utils.js +++ b/lib/internal/dns/utils.js @@ -12,6 +12,7 @@ const IPv6RE = /^\[([^[\]]*)\]/; const addrSplitRE = /(^.+?)(?::(\d+))?$/; const { ERR_DNS_SET_SERVERS_FAILED, + ERR_INVALID_ARG_TYPE, ERR_INVALID_IP_ADDRESS, ERR_INVALID_OPT_VALUE } = errors.codes; @@ -37,13 +38,20 @@ class Resolver { } setServers(servers) { + if (!Array.isArray(servers)) { + throw new ERR_INVALID_ARG_TYPE('servers', 'Array', servers); + } + // Cache the original servers because in the event of an error while // setting the servers, c-ares won't have any servers available for // resolution. const orig = this._handle.getServers(); const newSet = []; - servers.forEach((serv) => { + servers.forEach((serv, index) => { + if (typeof serv !== 'string') { + throw new ERR_INVALID_ARG_TYPE(`servers[${index}]`, 'string', serv); + } var ipVersion = isIP(serv); if (ipVersion !== 0) diff --git a/test/parallel/test-dns-setservers-type-check.js b/test/parallel/test-dns-setservers-type-check.js new file mode 100644 index 00000000000000..256c029427b86a --- /dev/null +++ b/test/parallel/test-dns-setservers-type-check.js @@ -0,0 +1,87 @@ +'use strict'; +require('../common'); +const { addresses } = require('../common/internet'); +const assert = require('assert'); +const dns = require('dns'); +const resolver = new dns.promises.Resolver(); +const dnsPromises = dns.promises; +const promiseResolver = new dns.promises.Resolver(); + +{ + [ + null, + undefined, + Number(addresses.DNS4_SERVER), + addresses.DNS4_SERVER, + { + address: addresses.DNS4_SERVER + } + ].forEach((val) => { + const errObj = { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError [ERR_INVALID_ARG_TYPE]', + message: 'The "servers" argument must be of type Array. Received type ' + + typeof val + }; + assert.throws( + () => { + dns.setServers(val); + }, errObj + ); + assert.throws( + () => { + resolver.setServers(val); + }, errObj + ); + assert.throws( + () => { + dnsPromises.setServers(val); + }, errObj + ); + assert.throws( + () => { + promiseResolver.setServers(val); + }, errObj + ); + }); +} + +{ + [ + [null], + [undefined], + [Number(addresses.DNS4_SERVER)], + [ + { + address: addresses.DNS4_SERVER + } + ] + ].forEach((val) => { + const errObj = { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError [ERR_INVALID_ARG_TYPE]', + message: 'The "servers[0]" argument must be of type string. ' + + `Received type ${typeof val[0]}` + }; + assert.throws( + () => { + dns.setServers(val); + }, errObj + ); + assert.throws( + () => { + resolver.setServers(val); + }, errObj + ); + assert.throws( + () => { + dnsPromises.setServers(val); + }, errObj + ); + assert.throws( + () => { + promiseResolver.setServers(val); + }, errObj + ); + }); +}