Skip to content

Commit 391e716

Browse files
Merge pull request #190 from browserstack/LOC-7724/proxy-auth-binary-download
Send proxy credentials when downloading the binary (fixes #164)
2 parents 2f41dd8 + 26fb0df commit 391e716

9 files changed

Lines changed: 312 additions & 37 deletions

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ To use a proxy for local testing -
8080
* proxyPass: Password for USERNAME, will be ignored if USERNAME is empty or not specified
8181
* useCaCertificate: Path to ca cert file, if required
8282

83+
The same settings, including proxyUser/proxyPass and useCaCertificate, are used when the library downloads the BrowserStack Local binary. The download goes through the proxy only when both proxyHost and proxyPort are set.
84+
8385
```js
8486
bs_local_args = { 'key': '<browserstack-accesskey>', 'proxyHost': '127.0.0.1', 'proxyPort': '8000', 'proxyUser': 'user', 'proxyPass': 'password', 'useCaCertificate': '/Users/test/cert.pem' }
8587
```

‎lib/Local.js‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,12 @@ function Local(){
320320
if(this.proxyHost && this.proxyPort){
321321
conf.proxyHost = this.proxyHost;
322322
conf.proxyPort = this.proxyPort;
323+
/* The running binary already gets these as --proxy-user/--proxy-pass
324+
(getBinaryArgs); the download goes through the same proxy and needs them too. */
325+
if(this.proxyUser) {
326+
conf.proxyUser = this.proxyUser;
327+
conf.proxyPass = this.proxyPass;
328+
}
323329
}
324330
if (this.useCaCertificate) {
325331
conf.useCaCertificate = this.useCaCertificate;

‎lib/LocalBinary.js‎

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ var https = require('https'),
88
util = require('util'),
99
childProcess = require('child_process'),
1010
zlib = require('zlib'),
11-
HttpsProxyAgent = require('https-proxy-agent'),
11+
{ buildProxyAgent } = require('./util'),
1212
version = require('../package.json').version,
1313
LocalError = require('./LocalError'),
1414
fetchDownloadSourceUrlAsync = require('./fetchDownloadSourceUrlAsync');
@@ -37,6 +37,21 @@ function LocalBinary(){
3737
*/
3838
this.downloadState = { fallbackEnabled: false, errorMessage: null, sourceURL: null };
3939

40+
/* Proxy credentials reach the spawned download scripts through their environment,
41+
never argv — same reason as the auth token. A copy already sitting in process.env
42+
is dropped first so only this instance's settings are used. */
43+
this.addProxyCredentialsToEnv = function(env, conf) {
44+
delete env.BROWSERSTACK_LOCAL_PROXY_USER;
45+
delete env.BROWSERSTACK_LOCAL_PROXY_PASS;
46+
if(conf.proxyHost && conf.proxyPort && conf.proxyUser) {
47+
env.BROWSERSTACK_LOCAL_PROXY_USER = String(conf.proxyUser);
48+
if(conf.proxyPass !== undefined && conf.proxyPass !== null) {
49+
env.BROWSERSTACK_LOCAL_PROXY_PASS = String(conf.proxyPass);
50+
}
51+
}
52+
return env;
53+
};
54+
4055
this.getSourceUrlSync = function(conf, retries) {
4156
/* Request for an endpoint to download the local binary from Rails no more than twice with 5 retries each */
4257
if (![4, 9].includes(retries) && this.sourceURL != null) {
@@ -74,6 +89,7 @@ function LocalBinary(){
7489
if (this.key) {
7590
env.BROWSERSTACK_LOCAL_AUTH_TOKEN = this.key;
7691
}
92+
this.addProxyCredentialsToEnv(env, conf);
7793
const obj = childProcess.spawnSync(cmd, opts, { env: env });
7894
/* stdout is null on a spawn failure; reading .length masked the real cause. */
7995
if(obj.error) {
@@ -108,7 +124,7 @@ function LocalBinary(){
108124
downloadErrorMessage = this.downloadErrorMessage || this.downloadState.errorMessage;
109125
}
110126

111-
fetchDownloadSourceUrlAsync(this.key, this.bsHost, downloadFallback, downloadErrorMessage, conf.proxyHost, conf.proxyPort, conf.useCaCertificate, (err, sourceURL) => {
127+
fetchDownloadSourceUrlAsync(this.key, this.bsHost, downloadFallback, downloadErrorMessage, conf.proxyHost, conf.proxyPort, conf.proxyUser, conf.proxyPass, conf.useCaCertificate, (err, sourceURL) => {
112128
if (err) return callback(err);
113129
this.sourceURL = sourceURL;
114130
this.downloadState.sourceURL = sourceURL;
@@ -242,6 +258,7 @@ function LocalBinary(){
242258
try{
243259
const userAgent = [packageName, version].join('/');
244260
const env = Object.assign({ 'USER_AGENT': userAgent }, process.env);
261+
this.addProxyCredentialsToEnv(env, conf);
245262
const obj = childProcess.spawnSync(cmd, opts, { env: env });
246263
if(obj.status !== 0) {
247264
that.binaryDownloadError('Download failed with status', String(obj.status));
@@ -304,11 +321,9 @@ function LocalBinary(){
304321
});
305322

306323
var options = url.parse(this.httpPath);
307-
if(conf.proxyHost && conf.proxyPort) {
308-
options.agent = new HttpsProxyAgent({
309-
host: conf.proxyHost,
310-
port: conf.proxyPort
311-
});
324+
var agent = buildProxyAgent(conf.proxyHost, conf.proxyPort, conf.proxyUser, conf.proxyPass);
325+
if(agent) {
326+
options.agent = agent;
312327
}
313328
if (conf.useCaCertificate) {
314329
try {

‎lib/download.js‎

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
const https = require('https'),
22
fs = require('fs'),
3-
HttpsProxyAgent = require('https-proxy-agent'),
43
url = require('url'),
54
zlib = require('zlib'),
6-
{ isUndefined } = require('./util');
5+
{ isUndefined, buildProxyAgent } = require('./util');
76

87
const binaryPath = process.argv[2], httpPath = process.argv[3], proxyHost = process.argv[4], proxyPort = process.argv[5], useCaCertificate = process.argv[6];
8+
/* Proxy credentials come through the environment, never argv (see fetchDownloadSourceUrl.js). */
9+
const proxyUser = process.env.BROWSERSTACK_LOCAL_PROXY_USER, proxyPass = process.env.BROWSERSTACK_LOCAL_PROXY_PASS;
910

1011
var fileStream = fs.createWriteStream(binaryPath);
1112

@@ -22,15 +23,13 @@ fileStream.on('error', function (err) {
2223
});
2324

2425
var options = url.parse(httpPath);
25-
/* isUndefined, not plain truthiness: the parent passes literal `undefined`
26-
placeholders for the proxy slots when only a CA is configured, and those
27-
arrive here as the *string* "undefined" — which is truthy, and previously
28-
built a proxy agent pointing at the host "undefined". */
29-
if(!isUndefined(proxyHost) && !isUndefined(proxyPort)) {
30-
options.agent = new HttpsProxyAgent({
31-
host: proxyHost,
32-
port: proxyPort
33-
});
26+
/* buildProxyAgent treats the *string* "undefined" as absent: the parent passes
27+
literal `undefined` placeholders for the proxy slots when only a CA is
28+
configured, and plain truthiness previously built a proxy agent pointing at
29+
the host "undefined". */
30+
const agent = buildProxyAgent(proxyHost, proxyPort, proxyUser, proxyPass);
31+
if(agent) {
32+
options.agent = agent;
3433
}
3534

3635
/* Applied regardless of whether a proxy is configured: this is the caller's TLS

‎lib/fetchDownloadSourceUrl.js‎

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
const https = require('https'),
22
fs = require('fs'),
3-
HttpsProxyAgent = require('https-proxy-agent'),
4-
{ isUndefined } = require('./util');
3+
{ isUndefined, buildProxyAgent } = require('./util');
54

6-
/* The auth token is read from the environment, never from argv: argv is world-readable
7-
via `ps` / /proc/<pid>/cmdline, whereas /proc/<pid>/environ is restricted to the
8-
owning user. Keep it out of this argument list. */
5+
/* The auth token and proxy credentials are read from the environment, never from argv:
6+
argv is world-readable via `ps` / /proc/<pid>/cmdline, whereas /proc/<pid>/environ is
7+
restricted to the owning user. Keep them out of this argument list. */
98
const authToken = process.env.BROWSERSTACK_LOCAL_AUTH_TOKEN, bsHost = process.argv[2], proxyHost = process.argv[5], proxyPort = process.argv[6], useCaCertificate = process.argv[7], downloadFallback = process.argv[3], downloadErrorMessage = process.argv[4];
9+
const proxyUser = process.env.BROWSERSTACK_LOCAL_PROXY_USER, proxyPass = process.env.BROWSERSTACK_LOCAL_PROXY_PASS;
1010

1111
let body = '', data = {'auth_token': authToken};
1212
const options = {
@@ -24,11 +24,9 @@ if (downloadFallback == 'true') {
2424
data['error_message'] = downloadErrorMessage;
2525
}
2626

27-
if(!isUndefined(proxyHost) && !isUndefined(proxyPort)) {
28-
options.agent = new HttpsProxyAgent({
29-
host: proxyHost,
30-
port: proxyPort
31-
});
27+
const agent = buildProxyAgent(proxyHost, proxyPort, proxyUser, proxyPass);
28+
if(agent) {
29+
options.agent = agent;
3230
}
3331
if (!isUndefined(useCaCertificate)) {
3432
try {

‎lib/fetchDownloadSourceUrlAsync.js‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
const https = require('https'),
22
fs = require('fs'),
3-
HttpsProxyAgent = require('https-proxy-agent'),
4-
{ isUndefined } = require('./util'),
3+
{ isUndefined, buildProxyAgent } = require('./util'),
54
version = require('../package.json').version;
65

76
const packageName = 'browserstack-local-nodejs';
87

9-
function fetchDownloadSourceUrlAsync(authToken, bsHost, downloadFallback, downloadErrorMessage, proxyHost, proxyPort, useCaCertificate, callback) {
8+
function fetchDownloadSourceUrlAsync(authToken, bsHost, downloadFallback, downloadErrorMessage, proxyHost, proxyPort, proxyUser, proxyPass, useCaCertificate, callback) {
109
let body = '', data = {'auth_token': authToken};
1110
const userAgent = [packageName, version].join('/');
1211
const options = {
@@ -24,11 +23,9 @@ function fetchDownloadSourceUrlAsync(authToken, bsHost, downloadFallback, downlo
2423
data['error_message'] = downloadErrorMessage;
2524
}
2625

27-
if(!isUndefined(proxyHost) && !isUndefined(proxyPort)) {
28-
options.agent = new HttpsProxyAgent({
29-
host: proxyHost,
30-
port: proxyPort
31-
});
26+
const agent = buildProxyAgent(proxyHost, proxyPort, proxyUser, proxyPass);
27+
if(agent) {
28+
options.agent = agent;
3229
}
3330
if (!isUndefined(useCaCertificate)) {
3431
try {

‎lib/util.js‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,21 @@
1-
module.exports.isUndefined = value => (value === undefined || value === null || value === 'undefined');
1+
const HttpsProxyAgent = require('https-proxy-agent');
2+
3+
const isUndefined = value => (value === undefined || value === null || value === 'undefined');
4+
module.exports.isUndefined = isUndefined;
5+
6+
const isBlank = value => (isUndefined(value) || value === '');
7+
8+
/* Builds the proxy agent for every binary-download request: the in-process async
9+
download and the scripts the sync path spawns. Without proxyUser/proxyPass in it,
10+
an authenticating proxy answers the CONNECT with 407 and the binary is never
11+
downloaded, even though the running binary gets them as --proxy-user/--proxy-pass.
12+
Same rule as the README: proxyPass is ignored unless proxyUser is set. */
13+
module.exports.buildProxyAgent = (proxyHost, proxyPort, proxyUser, proxyPass) => {
14+
if(isBlank(proxyHost) || isBlank(proxyPort)) return undefined;
15+
const agentOptions = { host: proxyHost, port: proxyPort };
16+
if(!isBlank(proxyUser)) {
17+
/* https-proxy-agent sends this as `Proxy-Authorization: Basic base64(auth)`. */
18+
agentOptions.auth = proxyUser + ':' + (isUndefined(proxyPass) ? '' : proxyPass);
19+
}
20+
return new HttpsProxyAgent(agentOptions);
21+
};

‎test/fixtures/recording_proxy.js‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/* Test double for a corporate proxy that requires Basic auth. It runs in its own
2+
process so the sync download path, which blocks the test process in spawnSync,
3+
can still reach it. Every CONNECT is recorded and refused with 407, so nothing
4+
leaves the machine. Talks to the parent over the fork IPC channel:
5+
sends { port } once listening, answers 'dump' with { requests }, exits on 'stop'. */
6+
const http = require('http');
7+
8+
const requests = [];
9+
const server = http.createServer(function (req, res) {
10+
res.writeHead(405);
11+
res.end();
12+
});
13+
14+
server.on('connect', function (req, socket) {
15+
requests.push({ target: req.url, auth: req.headers['proxy-authorization'] || null });
16+
socket.end('HTTP/1.1 407 Proxy Authentication Required\r\n' +
17+
'Proxy-Authenticate: Basic realm="corp"\r\n' +
18+
'Content-Length: 0\r\n' +
19+
'Connection: close\r\n\r\n');
20+
});
21+
22+
process.on('message', function (msg) {
23+
if (msg === 'dump') process.send({ requests: requests.splice(0) });
24+
if (msg === 'stop') server.close(function () { process.exit(0); });
25+
});
26+
27+
server.listen(0, '127.0.0.1', function () {
28+
process.send({ port: server.address().port });
29+
});

0 commit comments

Comments
 (0)