Skip to content

Commit 3bf5017

Browse files
manish-bothraclaude
andcommitted
Read the collector override lazily and validate it on the runs path
constants.js is loaded through bin/helpers/utils.js, which every command loads, so validating at module load meant a bad BROWSERSTACK_TEST_OBSERVABILITY_API_URL crashed init, info, stop and the reporter on the machine at startup, outside any handler. API_URL becomes apiUrl(), read when a request is built; nodeRequest rejects rather than throws, since its executor is async and a throw there would never reach the returned promise. validateCollectorUrls() runs at runs.js:136, before TestHubHandler.launchBuild, so a bad value fails before a build exists. Comments in constants.js trimmed to the one that earns its place. Jira: A11Y-13909 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent c40a12b commit 3bf5017

6 files changed

Lines changed: 40 additions & 24 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: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -572,6 +572,12 @@ 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+
remoteReporterApiUrl();
579+
};
580+
575581
exports.setSystemEnvs = (bsConfig) => {
576582
let envKeys = {};
577583

‎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: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,12 @@ exports.BATCH_SIZE = 1000;
55
exports.BATCH_INTERVAL = 2000;
66
const DEFAULT_API_URL = 'https://collector-observability.browserstack.com';
77

8-
// Requests to the collector carry BS_TESTOPS_JWT, so an http:// override would put the build's token
9-
// on the wire in cleartext. Request urls are also built as `${base}/${path}`, so a query or fragment
10-
// would swallow the endpoint. Reject such values instead of quietly using the default collector.
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.
1110
const httpsOverride = (name) => {
1211
const value = process.env[name];
1312
if (!value) return undefined;
1413
let parsed;
15-
// The value can carry credentials, and callers log the error, so never echo it back.
1614
try {
1715
parsed = new URL(value);
1816
} catch (err) {
@@ -24,16 +22,14 @@ const httpsOverride = (name) => {
2422
if (parsed.search || parsed.hash) {
2523
throw new Error(`${name} must not contain a query or fragment`);
2624
}
27-
// Normalise to origin + path with no trailing separator: a stray `/`, `?` or `#` would otherwise
28-
// turn the appended endpoint into a query or fragment.
25+
// Endpoints are appended as `${base}/${path}`.
2926
return `${parsed.origin}${parsed.pathname}`.replace(/\/+$/, '');
3027
};
3128

32-
// Overridable so the remote reporter (own install of this package) can target the launching cli's collector
33-
exports.API_URL = httpsOverride('BROWSERSTACK_TEST_OBSERVABILITY_API_URL') || DEFAULT_API_URL;
34-
// Collector handed to the reporter on the remote machine; separate override for when it cannot reach API_URL
29+
exports.apiUrl = () => httpsOverride('BROWSERSTACK_TEST_OBSERVABILITY_API_URL') || DEFAULT_API_URL;
30+
// Separate override for when the remote machine cannot reach the cli's own collector.
3531
exports.remoteReporterApiUrl = () => httpsOverride('BROWSERSTACK_TEST_OBSERVABILITY_REMOTE_API_URL')
36-
|| httpsOverride('BROWSERSTACK_TEST_OBSERVABILITY_API_URL') || DEFAULT_API_URL;
32+
|| exports.apiUrl();
3733

3834
exports.IPC_EVENTS = {
3935
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/testObservability/collectorUrl.js‎

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,18 @@ const expect = chai.expect;
44
const sinon = require('sinon');
55
const proxyquire = require('proxyquire').noPreserveCache();
66

7-
const CONSTANTS_PATH = require.resolve('../../../../bin/testObservability/helper/constants');
87
const API_URL_ENV = 'BROWSERSTACK_TEST_OBSERVABILITY_API_URL';
98
const DEFAULT_API_URL = 'https://collector-observability.browserstack.com';
109

1110
// A11Y-13909: the reporter runs on the BrowserStack machine from its own install of this package,
1211
// so the collector it posts to has to come from the environment the launching cli forwards. These
1312
// pin the request destination itself, not just the forwarding done by setSystemEnvs.
1413
describe('observability collector url', () => {
15-
let savedApiUrl, cachedConstants;
14+
let savedApiUrl;
1615

1716
beforeEach(() => {
1817
savedApiUrl = process.env[API_URL_ENV];
1918
delete process.env[API_URL_ENV];
20-
// constants.js reads the override at load, so it must be re-evaluated per case.
21-
cachedConstants = require.cache[CONSTANTS_PATH];
22-
delete require.cache[CONSTANTS_PATH];
2319
});
2420

2521
afterEach(() => {
@@ -28,10 +24,6 @@ describe('observability collector url', () => {
2824
} else {
2925
process.env[API_URL_ENV] = savedApiUrl;
3026
}
31-
delete require.cache[CONSTANTS_PATH];
32-
if (cachedConstants) {
33-
require.cache[CONSTANTS_PATH] = cachedConstants;
34-
}
3527
});
3628

3729
const loadHelperWithAxios = () => {
@@ -42,8 +34,8 @@ describe('observability collector url', () => {
4234
};
4335

4436
it('sends requests to the overridden collector', async () => {
45-
process.env[API_URL_ENV] = 'https://collector-example.bsstag.com';
4637
const { helper, axiosStub } = loadHelperWithAxios();
38+
process.env[API_URL_ENV] = 'https://collector-example.bsstag.com';
4739

4840
await helper.nodeRequest('POST', 'api/v1/batch', {}, { headers: {} });
4941

@@ -57,4 +49,16 @@ describe('observability collector url', () => {
5749

5850
expect(axiosStub.firstCall.args[0].url).to.equal(`${DEFAULT_API_URL}/api/v1/batch`);
5951
});
52+
53+
// Loading this module must never throw on a bad value: every command loads it through
54+
// bin/helpers/utils.js, so init, info and stop would die at startup, as would the reporter.
55+
it('does not reject an invalid collector url until a request is made', async () => {
56+
process.env[API_URL_ENV] = 'http://collector-example.bsstag.com';
57+
58+
const { helper } = loadHelperWithAxios();
59+
60+
let thrown;
61+
await helper.nodeRequest('POST', 'api/v1/batch', {}, { headers: {} }).catch((err) => { thrown = err; });
62+
expect(String(thrown)).to.match(/must be an https:\/\/ URL/);
63+
});
6064
});

0 commit comments

Comments
 (0)