Skip to content

Commit c535023

Browse files
Merge branch 'master' into APS-22894-cypress-16-expose
2 parents e64dcc1 + aedf9e9 commit c535023

11 files changed

Lines changed: 556 additions & 46 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/distrustedCaCheck.js‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
'use strict';
2+
3+
/*
4+
* The private keys of 8 eMudhra intermediate CAs are recoverable, so anyone can issue certificates
5+
* under them. Browsers and OS trust stores block them, but Node's bundled roots still accept their
6+
* chains. Reject any TLS chain that carries one of those keys (SPKI SHA-256, which catches both the
7+
* emSign-issued and the Sectigo cross-signed copies) or one of their names.
8+
* Source: https://emudhra.we-have-a-problem.com/impacted-intermediates.json
9+
*/
10+
11+
const tls = require('tls');
12+
const crypto = require('crypto');
13+
14+
const STATE_KEY = Symbol.for('browserstack.distrustedCaCheck');
15+
16+
const DISTRUSTED_SPKI_SHA256 = [
17+
'EBED6475C2C2D80FCB199F3FE8DD6E6B3CE60B77EB15D4E42C3DEC0C6F5B5105', // EM DV TLS CA - G3B
18+
'43BFFA19D6EF651451F6841E019931E96F6F2EAEFF28AB4B6F1CE4576DE2717B', // EM OV TLS CA - G3B
19+
'E0254C7FCDC265E2F0F8A428DABB75AB4AE039B4872D62F5EE57F0877D5A8A41', // EM EV TLS CA - G3B
20+
'49DD353DC2B919A3770645117D0E60C16115E7D1BC259EEFE734B00EA434FE5F', // EM DV TLS CA - G3C
21+
'63ECEFEE431D49523BC1136C4E72D0206A477086CAF606CD5CF025686C109CF8', // EM OV TLS CA - G3C
22+
'5C0660A2B164910D8FF589C18E14552E9E0EC237DCEFE2CB736D41A4811F81A0', // EM EV TLS CA - G3C
23+
'EC4FFA1AD0AC88081314B7AAFFEF6A91F97CD57291BB5BA686C5415F5EB4F6B6', // EM OV CS CA - G3B
24+
'92C063D67E8F14DB71D288E11266FFDAF69CBF115F7BAB14F3BC2F68D25E0E30' // EM OV CS CA - G3C
25+
];
26+
27+
// Node links issuerCertificate by name, so a decoy certificate sent ahead of the real intermediate can divert
28+
// the walk away from the distrusted key. The 8 intermediates are pathlen:0, so the leaf's issuer is always
29+
// one of their names; matching names closes that gap.
30+
const DISTRUSTED_NAMES = [
31+
'EM DV TLS CA - G3B|eMudhra BV|NL',
32+
'EM OV TLS CA - G3B|eMudhra BV|NL',
33+
'EM EV TLS CA - G3B|eMudhra BV|NL',
34+
'EM DV TLS CA - G3C|eMudhra Inc|US',
35+
'EM OV TLS CA - G3C|eMudhra Inc|US',
36+
'EM EV TLS CA - G3C|eMudhra Inc|US',
37+
'EM OV CS CA - G3B|eMudhra BV|NL',
38+
'EM OV CS CA - G3C|eMudhra Inc|US'
39+
].map((name) => name.toLowerCase());
40+
41+
// OpenSSL chains names case-insensitively with whitespace collapsed, so compare them the same way.
42+
function normalize(value) {
43+
return String((Array.isArray(value) ? value.join(',') : value) || '').trim().replace(/\s+/g, ' ').toLowerCase();
44+
}
45+
46+
function nameKey(name) {
47+
return name ? `${normalize(name.CN)}|${normalize(name.O)}|${normalize(name.C)}` : '';
48+
}
49+
50+
// The peer certificate's `pubkey` is the raw point for EC keys, not the SPKI, so re-export the SPKI from
51+
// the certificate. createPublicKey rather than X509Certificate, which needs Node 15.6.
52+
function spkiSha256(rawCert) {
53+
const pem = `-----BEGIN CERTIFICATE-----\n${rawCert.toString('base64').match(/.{1,64}/g).join('\n')}\n-----END CERTIFICATE-----\n`;
54+
const spki = crypto.createPublicKey(pem).export({type: 'spki', format: 'der'});
55+
56+
return crypto.createHash('sha256').update(spki).digest('hex').toUpperCase();
57+
}
58+
59+
// Returns the name of the distrusted intermediate found in the chain, or null.
60+
function findDistrustedIntermediate(cert, state) {
61+
for (let current = cert, previous; current && current !== previous; previous = current, current = current.issuerCertificate) {
62+
if (state.distrustedNames.has(nameKey(current.subject))) {
63+
return current.subject.CN;
64+
}
65+
if (state.distrustedNames.has(nameKey(current.issuer))) {
66+
return current.issuer.CN;
67+
}
68+
let hash;
69+
try {
70+
hash = current.raw && spkiSha256(current.raw);
71+
} catch (err) {
72+
// A key createPublicKey cannot parse is not one of the distrusted EC keys; keep checking its issuers.
73+
continue;
74+
}
75+
if (hash && state.distrusted.has(hash)) {
76+
return (current.subject && current.subject.CN) || 'unknown';
77+
}
78+
}
79+
80+
return null;
81+
}
82+
83+
// Every copy of this module in the process shares one state and one wrapper. The state lives on the tls module,
84+
// not on global: Jest gives each test file its own global but shares core modules across them.
85+
function installDistrustedCaCheck() {
86+
if (typeof crypto.createPublicKey !== 'function') {
87+
return false;
88+
}
89+
const existing = tls[STATE_KEY];
90+
if (existing) {
91+
DISTRUSTED_SPKI_SHA256.forEach((hash) => existing.distrusted.add(hash));
92+
DISTRUSTED_NAMES.forEach((name) => existing.distrustedNames.add(name));
93+
94+
return false;
95+
}
96+
const state = {distrusted: new Set(DISTRUSTED_SPKI_SHA256), distrustedNames: new Set(DISTRUSTED_NAMES)};
97+
tls[STATE_KEY] = state;
98+
99+
const originalCheckServerIdentity = tls.checkServerIdentity;
100+
tls.checkServerIdentity = function checkServerIdentity(hostname, cert) {
101+
const identityError = originalCheckServerIdentity(hostname, cert);
102+
if (identityError) {
103+
return identityError;
104+
}
105+
const distrustedName = findDistrustedIntermediate(cert, state);
106+
if (!distrustedName) {
107+
return undefined;
108+
}
109+
const error = new Error(`Certificate chain for ${hostname} contains the distrusted eMudhra intermediate "${distrustedName}"`);
110+
error.code = 'ERR_TLS_DISTRUSTED_INTERMEDIATE';
111+
error.host = hostname;
112+
113+
return error;
114+
};
115+
116+
return true;
117+
}
118+
119+
module.exports = {installDistrustedCaCheck};

‎bin/helpers/utils.js‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
11
"use strict";
2+
// Installed here rather than in runner.js: the CLI and the reporter/plugins that run inside the customer's Cypress all load this file.
3+
try {
4+
require('./distrustedCaCheck').installDistrustedCaCheck();
5+
} catch (err) {
6+
require('./logger').winstonLogger.debug(`Distrusted CA check failed to install: ${err && err.message}`);
7+
}
8+
29
const os = require("os");
310
const path = require("path");
411
const fs = require("fs");
@@ -24,7 +31,7 @@ const usageReporting = require("./usageReporting"),
2431
pkg = require('../../package.json'),
2532
transports = require('./logger').transports,
2633
o11yHelpers = require('../testObservability/helper/helper'),
27-
{ 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');
2835

2936
const { default: axios } = require("axios");
3037
const { shouldProcessEventForTesthub } = require("../testhub/utils");
@@ -568,6 +575,22 @@ exports.setBuildTags = (bsConfig, args) => {
568575
logger.debug(`Setting the build tag = ${bsConfig.run_settings.build_tag}`);
569576
};
570577

578+
// Called before anything is created server-side: setSystemEnvs runs after the TestHub build
579+
// exists, so a malformed collector override would otherwise fail with a build already open.
580+
exports.validateCollectorUrls = () => {
581+
// Both, because remoteReporterApiUrl() short-circuits past apiUrl() when the remote override
582+
// is set, which would leave a malformed general override unchecked until the first request.
583+
apiUrl();
584+
remoteReporterApiUrl();
585+
// Remote-only means this process keeps its built-in collector while the machine reports to
586+
// another one. That is correct when the built-in default has been pointed at the same
587+
// environment, and a silently split build when it has not. Only the host is named: the
588+
// path survives normalization and can carry a token.
589+
if (process.env[REMOTE_API_URL_ENV] && !process.env[API_URL_ENV]) {
590+
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.`);
591+
}
592+
};
593+
571594
exports.setSystemEnvs = (bsConfig) => {
572595
let envKeys = {};
573596

@@ -606,6 +629,10 @@ exports.setSystemEnvs = (bsConfig) => {
606629
logger.error(`Error in adding accessibility configs ${error}`)
607630
}
608631

632+
// Remote reporter must post to this build's collector, not its package default. Kept out of the
633+
// try below, which swallows errors: a rejected override must fail rather than fall back silently.
634+
envKeys[API_URL_ENV] = remoteReporterApiUrl();
635+
609636
try {
610637
OBSERVABILITY_ENV_VARS.forEach(key => {
611638
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,

0 commit comments

Comments
 (0)