Skip to content

Commit 8fe6821

Browse files
authored
Merge pull request #1215 from browserstack/A11Y-13909-forward-observability-api-url
2 parents 0608814 + 8513d91 commit 8fe6821

7 files changed

Lines changed: 293 additions & 6 deletions

File tree

‎bin/commands/runs.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,8 @@ module.exports = function run(args, rawArgs) {
133133
const port = await findAvailablePort(preferredPort);
134134
process.env.REPORTER_API_PORT_NO = port
135135

136+
utils.validateCollectorUrls();
137+
136138
// Send build start to TEST REPORTING AND ANALYTICS
137139
if(shouldProcessEventForTesthub()) {
138140
await TestHubHandler.launchBuild(bsConfig, bsConfigPath);

‎bin/helpers/utils.js‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ const usageReporting = require("./usageReporting"),
3131
pkg = require('../../package.json'),
3232
transports = require('./logger').transports,
3333
o11yHelpers = require('../testObservability/helper/helper'),
34-
{ OBSERVABILITY_ENV_VARS, TEST_OBSERVABILITY_REPORTER } = require('../testObservability/helper/constants');
34+
{ OBSERVABILITY_ENV_VARS, TEST_OBSERVABILITY_REPORTER, API_URL_ENV, REMOTE_API_URL_ENV, apiUrl, remoteReporterApiUrl } = require('../testObservability/helper/constants');
3535

3636
const { default: axios } = require("axios");
3737
const { shouldProcessEventForTesthub } = require("../testhub/utils");
@@ -572,6 +572,22 @@ exports.setBuildTags = (bsConfig, args) => {
572572
logger.debug(`Setting the build tag = ${bsConfig.run_settings.build_tag}`);
573573
};
574574

575+
// Called before anything is created server-side: setSystemEnvs runs after the TestHub build
576+
// exists, so a malformed collector override would otherwise fail with a build already open.
577+
exports.validateCollectorUrls = () => {
578+
// Both, because remoteReporterApiUrl() short-circuits past apiUrl() when the remote override
579+
// is set, which would leave a malformed general override unchecked until the first request.
580+
apiUrl();
581+
remoteReporterApiUrl();
582+
// Remote-only means this process keeps its built-in collector while the machine reports to
583+
// another one. That is correct when the built-in default has been pointed at the same
584+
// environment, and a silently split build when it has not. Only the host is named: the
585+
// path survives normalization and can carry a token.
586+
if (process.env[REMOTE_API_URL_ENV] && !process.env[API_URL_ENV]) {
587+
logger.warn(`${REMOTE_API_URL_ENV} is set without ${API_URL_ENV}: this run will create its build on the built-in collector and the remote reporter will post test results to ${new URL(remoteReporterApiUrl()).host}. Both must be the same environment.`);
588+
}
589+
};
590+
575591
exports.setSystemEnvs = (bsConfig) => {
576592
let envKeys = {};
577593

@@ -610,6 +626,10 @@ exports.setSystemEnvs = (bsConfig) => {
610626
logger.error(`Error in adding accessibility configs ${error}`)
611627
}
612628

629+
// Remote reporter must post to this build's collector, not its package default. Kept out of the
630+
// try below, which swallows errors: a rejected override must fail rather than fall back silently.
631+
envKeys[API_URL_ENV] = remoteReporterApiUrl();
632+
613633
try {
614634
OBSERVABILITY_ENV_VARS.forEach(key => {
615635
envKeys[key] = process.env[key];

‎bin/testObservability/crashReporter/index.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ const { HttpsProxyAgent = require('https-proxy-agent') } = require('https-proxy-
77
const logger = require("../../helpers/logger").winstonLogger;
88
const utils = require('../../helpers/utils');
99

10-
const { API_URL, consoleHolder, TEST_REPORTING_ANALYTICS } = require('../helper/constants');
10+
const { apiUrl, consoleHolder, TEST_REPORTING_ANALYTICS } = require('../helper/constants');
1111

1212
/* Below global methods are added here to remove cyclic dependency with helper.js, refactor later */
1313
const httpsKeepAliveAgent = new https.Agent({
@@ -148,7 +148,7 @@ class CrashReporter {
148148
'X-BSTACK-TESTOPS': 'true'
149149
},
150150
method: 'POST',
151-
url: `${API_URL}/api/v1/analytics`,
151+
url: `${apiUrl()}/api/v1/analytics`,
152152
data: data,
153153
json: true,
154154
agent: httpsKeepAliveAgent

‎bin/testObservability/helper/constants.js‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,42 @@ const path = require('path');
33
exports.consoleHolder = Object.assign({},console);
44
exports.BATCH_SIZE = 1000;
55
exports.BATCH_INTERVAL = 2000;
6-
exports.API_URL = 'https://collector-observability.browserstack.com';
6+
const DEFAULT_API_URL = 'https://collector-observability.browserstack.com';
7+
8+
// Overridable so the reporter on the remote machine posts to the collector the build was created
9+
// on. Errors never echo the value: it can carry credentials and callers log them.
10+
const httpsOverride = (name) => {
11+
const value = process.env[name];
12+
if (!value) return undefined;
13+
let parsed;
14+
try {
15+
parsed = new URL(value);
16+
} catch (err) {
17+
throw new Error(`${name} must be a valid https:// URL`);
18+
}
19+
if (parsed.protocol !== 'https:' || !parsed.hostname) {
20+
throw new Error(`${name} must be an https:// URL`);
21+
}
22+
if (parsed.search || parsed.hash) {
23+
throw new Error(`${name} must not contain a query or fragment`);
24+
}
25+
// URL.origin drops userinfo, so accepting it would silently discard a credential the
26+
// caller believes it is sending.
27+
if (parsed.username || parsed.password) {
28+
throw new Error(`${name} must not contain a username or password`);
29+
}
30+
// Endpoints are appended as `${base}/${path}`.
31+
return `${parsed.origin}${parsed.pathname}`.replace(/\/+$/, '');
32+
};
33+
34+
const API_URL_ENV = 'BROWSERSTACK_TEST_OBSERVABILITY_API_URL';
35+
// Separate override for when the remote machine cannot reach the cli's own collector.
36+
const REMOTE_API_URL_ENV = 'BROWSERSTACK_TEST_OBSERVABILITY_REMOTE_API_URL';
37+
exports.API_URL_ENV = API_URL_ENV;
38+
exports.REMOTE_API_URL_ENV = REMOTE_API_URL_ENV;
39+
40+
exports.apiUrl = () => httpsOverride(API_URL_ENV) || DEFAULT_API_URL;
41+
exports.remoteReporterApiUrl = () => httpsOverride(REMOTE_API_URL_ENV) || exports.apiUrl();
742

843
exports.IPC_EVENTS = {
944
LOG: 'testObservability:cypressLog',

‎bin/testObservability/helper/helper.js‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ const GLOBAL_MODULE_PATH = execSync('npm root -g').toString().trim();
2727
const { name, version } = require('../../../package.json');
2828

2929
const { CYPRESS_V10_AND_ABOVE_CONFIG_FILE_EXTENSIONS } = require('../../helpers/constants');
30-
const { consoleHolder, API_URL, TEST_OBSERVABILITY_REPORTER, TEST_OBSERVABILITY_REPORTER_LOCAL, TEST_REPORTING_ANALYTICS } = require('./constants');
30+
const { consoleHolder, apiUrl, TEST_OBSERVABILITY_REPORTER, TEST_OBSERVABILITY_REPORTER_LOCAL, TEST_REPORTING_ANALYTICS } = require('./constants');
3131

3232
const ALLOWED_MODULES = [
3333
'cypress/package.json',
@@ -128,10 +128,18 @@ exports.printBuildLink = async (shouldStopSession, exitCode = null) => {
128128
exports.nodeRequest = (type, url, data, config) => {
129129
const requestQueueHandler = require('./requestQueueHandler');
130130
return new Promise(async (resolve, reject) => {
131+
// Rejected rather than thrown: this executor is async, so a throw here would never reach
132+
// the returned promise and the caller would hang.
133+
let collectorUrl;
134+
try {
135+
collectorUrl = apiUrl();
136+
} catch (err) {
137+
return reject(err);
138+
}
131139
const options = {
132140
...config,
133141
method: type,
134-
url: `${API_URL}/${url}`,
142+
url: `${collectorUrl}/${url}`,
135143
data: data,
136144
httpsAgent: this.httpsKeepAliveAgent,
137145
maxAttempts: 2,

‎test/unit/bin/helpers/utils.js‎

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -961,6 +961,156 @@ describe('utils', () => {
961961
delete process.env.CYPRESS_TEST_1;
962962
delete process.env.cypress_test_2;
963963
});
964+
965+
const URL_ENV_VARS = [
966+
'BROWSERSTACK_TEST_OBSERVABILITY_API_URL',
967+
'BROWSERSTACK_TEST_OBSERVABILITY_REMOTE_API_URL',
968+
];
969+
let savedUrlEnvs = {};
970+
971+
beforeEach(() => {
972+
URL_ENV_VARS.forEach((key) => {
973+
savedUrlEnvs[key] = process.env[key];
974+
delete process.env[key];
975+
});
976+
});
977+
978+
afterEach(() => {
979+
URL_ENV_VARS.forEach((key) => {
980+
if (savedUrlEnvs[key] === undefined) {
981+
delete process.env[key];
982+
} else {
983+
process.env[key] = savedUrlEnvs[key];
984+
}
985+
});
986+
});
987+
988+
it('forwards the observability collector url for the remote reporter', () => {
989+
let bsConfig = { run_settings: { env: null } };
990+
991+
utils.setSystemEnvs(bsConfig);
992+
expect(bsConfig.run_settings.system_env_vars)
993+
.to.be.an('array')
994+
.that.includes('BROWSERSTACK_TEST_OBSERVABILITY_API_URL=https://collector-observability.browserstack.com');
995+
});
996+
997+
it('forwards an overridden observability collector url', () => {
998+
process.env.BROWSERSTACK_TEST_OBSERVABILITY_API_URL = 'https://collector-example.bsstag.com';
999+
let bsConfig = { run_settings: { env: null } };
1000+
1001+
utils.setSystemEnvs(bsConfig);
1002+
expect(bsConfig.run_settings.system_env_vars)
1003+
.to.be.an('array')
1004+
.that.includes('BROWSERSTACK_TEST_OBSERVABILITY_API_URL=https://collector-example.bsstag.com');
1005+
});
1006+
1007+
it('prefers a separate remote collector url for the remote reporter', () => {
1008+
process.env.BROWSERSTACK_TEST_OBSERVABILITY_API_URL = 'https://collector-private.bsstag.com';
1009+
process.env.BROWSERSTACK_TEST_OBSERVABILITY_REMOTE_API_URL = 'https://collector-public.bsstag.com';
1010+
let bsConfig = { run_settings: { env: null } };
1011+
1012+
utils.setSystemEnvs(bsConfig);
1013+
expect(bsConfig.run_settings.system_env_vars)
1014+
.to.be.an('array')
1015+
.that.includes('BROWSERSTACK_TEST_OBSERVABILITY_API_URL=https://collector-public.bsstag.com');
1016+
});
1017+
1018+
it('warns when only the remote collector is overridden', () => {
1019+
process.env.BROWSERSTACK_TEST_OBSERVABILITY_REMOTE_API_URL = 'https://collector-public.bsstag.com';
1020+
const warn = sinon.stub(logger, 'warn');
1021+
1022+
try {
1023+
utils.validateCollectorUrls();
1024+
sinon.assert.calledOnce(warn);
1025+
expect(warn.firstCall.args[0]).to.match(/collector-public\.bsstag\.com/);
1026+
expect(warn.firstCall.args[0]).to.match(/same environment/);
1027+
} finally {
1028+
warn.restore();
1029+
}
1030+
});
1031+
1032+
it('names only the host in that warning, never the path', () => {
1033+
process.env.BROWSERSTACK_TEST_OBSERVABILITY_REMOTE_API_URL = 'https://collector-public.bsstag.com/t0ken';
1034+
const warn = sinon.stub(logger, 'warn');
1035+
1036+
try {
1037+
utils.validateCollectorUrls();
1038+
expect(warn.firstCall.args[0]).to.not.match(/t0ken/);
1039+
} finally {
1040+
warn.restore();
1041+
}
1042+
});
1043+
1044+
it('does not warn when both collector urls are set', () => {
1045+
process.env.BROWSERSTACK_TEST_OBSERVABILITY_API_URL = 'https://collector-private.bsstag.com';
1046+
process.env.BROWSERSTACK_TEST_OBSERVABILITY_REMOTE_API_URL = 'https://collector-public.bsstag.com';
1047+
const warn = sinon.stub(logger, 'warn');
1048+
1049+
try {
1050+
utils.validateCollectorUrls();
1051+
sinon.assert.notCalled(warn);
1052+
} finally {
1053+
warn.restore();
1054+
}
1055+
});
1056+
1057+
it('neither warns nor throws when no collector url is overridden', () => {
1058+
const warn = sinon.stub(logger, 'warn');
1059+
1060+
try {
1061+
expect(() => utils.validateCollectorUrls()).to.not.throw();
1062+
sinon.assert.notCalled(warn);
1063+
} finally {
1064+
warn.restore();
1065+
}
1066+
});
1067+
1068+
it('rejects a collector url carrying a username or password', () => {
1069+
process.env.BROWSERSTACK_TEST_OBSERVABILITY_REMOTE_API_URL = 'https://user:secret@collector-public.bsstag.com';
1070+
1071+
expect(() => utils.validateCollectorUrls()).to.throw(/must not contain a username or password/);
1072+
});
1073+
1074+
it('validates both overrides, even when the remote one is valid', () => {
1075+
process.env.BROWSERSTACK_TEST_OBSERVABILITY_API_URL = 'http://collector-private.bsstag.com';
1076+
process.env.BROWSERSTACK_TEST_OBSERVABILITY_REMOTE_API_URL = 'https://collector-public.bsstag.com';
1077+
1078+
expect(() => utils.validateCollectorUrls()).to.throw(/BROWSERSTACK_TEST_OBSERVABILITY_API_URL must be an https/);
1079+
});
1080+
1081+
it('rejects a collector url that is not https', () => {
1082+
process.env.BROWSERSTACK_TEST_OBSERVABILITY_REMOTE_API_URL = 'http://collector-public.bsstag.com';
1083+
let bsConfig = { run_settings: { env: null } };
1084+
1085+
expect(() => utils.setSystemEnvs(bsConfig)).to.throw(/must be an https:\/\/ URL/);
1086+
});
1087+
1088+
it('rejects a collector url carrying a query or fragment', () => {
1089+
process.env.BROWSERSTACK_TEST_OBSERVABILITY_REMOTE_API_URL = 'https://collector-public.bsstag.com/#staging';
1090+
let bsConfig = { run_settings: { env: null } };
1091+
1092+
expect(() => utils.setSystemEnvs(bsConfig)).to.throw(/must not contain a query or fragment/);
1093+
});
1094+
1095+
it('normalises a bare query or fragment delimiter', () => {
1096+
process.env.BROWSERSTACK_TEST_OBSERVABILITY_REMOTE_API_URL = 'https://collector-public.bsstag.com?';
1097+
let bsConfig = { run_settings: { env: null } };
1098+
1099+
utils.setSystemEnvs(bsConfig);
1100+
expect(bsConfig.run_settings.system_env_vars)
1101+
.to.be.an('array')
1102+
.that.includes('BROWSERSTACK_TEST_OBSERVABILITY_API_URL=https://collector-public.bsstag.com');
1103+
});
1104+
1105+
it('trims a trailing slash so endpoint paths are not doubled', () => {
1106+
process.env.BROWSERSTACK_TEST_OBSERVABILITY_REMOTE_API_URL = 'https://collector-public.bsstag.com/';
1107+
let bsConfig = { run_settings: { env: null } };
1108+
1109+
utils.setSystemEnvs(bsConfig);
1110+
expect(bsConfig.run_settings.system_env_vars)
1111+
.to.be.an('array')
1112+
.that.includes('BROWSERSTACK_TEST_OBSERVABILITY_API_URL=https://collector-public.bsstag.com');
1113+
});
9641114
});
9651115

9661116
describe('fixCommaSeparatedString', () => {
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
'use strict';
2+
const chai = require('chai');
3+
const expect = chai.expect;
4+
const sinon = require('sinon');
5+
const proxyquire = require('proxyquire').noPreserveCache();
6+
7+
const API_URL_ENV = 'BROWSERSTACK_TEST_OBSERVABILITY_API_URL';
8+
const DEFAULT_API_URL = 'https://collector-observability.browserstack.com';
9+
const HELPER_PATH = '../../../../bin/testObservability/helper/helper';
10+
const CONSTANTS_PATH = '../../../../bin/testObservability/helper/constants';
11+
12+
// A11Y-13909: the reporter runs on the BrowserStack machine from its own install of this package,
13+
// so the collector it posts to has to come from the environment the launching cli forwards. These
14+
// pin the request destination itself, not just the forwarding done by setSystemEnvs.
15+
describe('observability collector url', () => {
16+
let savedApiUrl;
17+
18+
beforeEach(() => {
19+
savedApiUrl = process.env[API_URL_ENV];
20+
delete process.env[API_URL_ENV];
21+
});
22+
23+
afterEach(() => {
24+
if (savedApiUrl === undefined) {
25+
delete process.env[API_URL_ENV];
26+
} else {
27+
process.env[API_URL_ENV] = savedApiUrl;
28+
}
29+
});
30+
31+
const loadHelperWithAxios = () => {
32+
const axiosStub = sinon.stub().resolves({ status: 200, data: '{}' });
33+
axiosStub['@noCallThru'] = true;
34+
// proxyquire clears only the proxied module and its stubs, and the url is resolved in
35+
// constants.js, so without this the url code is a cache hit and a module-load-time
36+
// regression there would never turn these red.
37+
delete require.cache[require.resolve(CONSTANTS_PATH)];
38+
const helper = proxyquire(HELPER_PATH, { axios: axiosStub });
39+
return { helper, axiosStub };
40+
};
41+
42+
it('sends requests to the overridden collector', async () => {
43+
const { helper, axiosStub } = loadHelperWithAxios();
44+
process.env[API_URL_ENV] = 'https://collector-example.bsstag.com';
45+
46+
await helper.nodeRequest('POST', 'api/v1/batch', {}, { headers: {} });
47+
48+
expect(axiosStub.firstCall.args[0].url).to.equal('https://collector-example.bsstag.com/api/v1/batch');
49+
});
50+
51+
it('sends requests to the default collector when no override is set', async () => {
52+
const { helper, axiosStub } = loadHelperWithAxios();
53+
54+
await helper.nodeRequest('POST', 'api/v1/batch', {}, { headers: {} });
55+
56+
expect(axiosStub.firstCall.args[0].url).to.equal(`${DEFAULT_API_URL}/api/v1/batch`);
57+
});
58+
59+
// Loading this module must never throw on a bad value: every command loads it through
60+
// bin/helpers/utils.js, so init, info and stop would die at startup, as would the reporter.
61+
it('does not reject an invalid collector url until a request is made', async () => {
62+
process.env[API_URL_ENV] = 'http://collector-example.bsstag.com';
63+
64+
let loaded;
65+
expect(() => { loaded = loadHelperWithAxios(); }).to.not.throw();
66+
const { helper } = loaded;
67+
68+
let thrown;
69+
await helper.nodeRequest('POST', 'api/v1/batch', {}, { headers: {} }).catch((err) => { thrown = err; });
70+
expect(String(thrown)).to.match(/must be an https:\/\/ URL/);
71+
});
72+
});

0 commit comments

Comments
 (0)