diff --git a/.changeset/pr-405.md b/.changeset/pr-405.md new file mode 100644 index 00000000..22f397f1 --- /dev/null +++ b/.changeset/pr-405.md @@ -0,0 +1,6 @@ +--- +"@wdio/browserstack-service": minor +--- + +- Improved diagnostics when a test session fails to start. +- Fixed SDK telemetry events (`SDKFeaturePerformance`, `DriverInitFailure`) being recorded with day and month swapped on days 1–12 of the month. diff --git a/packages/browserstack-service/src/constants.ts b/packages/browserstack-service/src/constants.ts index b3cec94c..e80d871d 100644 --- a/packages/browserstack-service/src/constants.ts +++ b/packages/browserstack-service/src/constants.ts @@ -84,6 +84,14 @@ export const FUNNEL_INSTRUMENTATION_URL = 'https://api.browserstack.com/sdk/v1/e export const EDS_URL = 'https://eds.browserstack.com' +export const DRIVER_INIT_FAILURE_EVENT = 'DriverInitFailure' +export const DRIVER_INIT_FAILURE_EVENT_TAG = 'sdk:driver:init:failure' +export const MAX_DRIVER_INIT_ERROR_BYTES = 8000 +export const DRIVER_INIT_FAILURE_SEND_TIMEOUT_MS = 5000 +export const DRIVER_INIT_FAILURE_MAX_ATTEMPTS = 4 +export const DRIVER_INIT_FAILURE_RETRY_BASE_MS = 500 +export const DRIVER_INIT_FAILURE_DEADLINE_MS = 10000 + // Env variables - Define all the env variable constants over here // To store the JWT token returned the session launch diff --git a/packages/browserstack-service/src/instrumentation/createdDay.ts b/packages/browserstack-service/src/instrumentation/createdDay.ts new file mode 100644 index 00000000..65b04ee9 --- /dev/null +++ b/packages/browserstack-service/src/instrumentation/createdDay.ts @@ -0,0 +1,3 @@ +export function formatCreatedDay(date = new Date()) { + return `${date.toISOString().slice(0, 23)}000 UTC` +} diff --git a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts index e08e3953..613edcec 100644 --- a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts +++ b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts @@ -7,12 +7,25 @@ import UsageStats from '../testOps/usageStats.js' import TestOpsConfig from '../testOps/testOpsConfig.js' import { BStackLogger } from '../bstackLogger.js' import type BrowserStackConfig from '../config.js' -import { BSTACK_A11Y_POLLING_TIMEOUT, BSTACK_SERVICE_VERSION, WDIO_NAMING_PREFIX } from '../constants.js' +import { + BSTACK_A11Y_POLLING_TIMEOUT, + BSTACK_SERVICE_VERSION, + WDIO_NAMING_PREFIX, + BROWSERSTACK_TESTHUB_UUID, + DRIVER_INIT_FAILURE_EVENT, + DRIVER_INIT_FAILURE_EVENT_TAG, + MAX_DRIVER_INIT_ERROR_BYTES, + DRIVER_INIT_FAILURE_SEND_TIMEOUT_MS, + DRIVER_INIT_FAILURE_MAX_ATTEMPTS, + DRIVER_INIT_FAILURE_RETRY_BASE_MS, + DRIVER_INIT_FAILURE_DEADLINE_MS +} from '../constants.js' import { getDataFromWorkers, removeWorkersDataDir } from '../data-store.js' import { getProductMap } from '../testHub/utils.js' import APIUtils from '../cli/apiUtils.js' import PerformanceTester from './performance/performance-tester.js' import { EVENTS } from './performance/constants.js' +import { formatCreatedDay } from './createdDay.js' async function fireFunnelTestEvent(eventType: string, config: BrowserStackConfig, isCLIEnabled = false) { if (!config.userName || !config.accessKey) { @@ -188,3 +201,154 @@ function getReferrer(framework?: string) { return `${fullName}/${BSTACK_SERVICE_VERSION}` } + +export interface DriverInitFailureDetails { + userName?: string + accessKey?: string + framework?: string + errorMessage: string +} + +function truncateToBytes(value: string, maxBytes: number) { + const buf = Buffer.from(value, 'utf8') + if (buf.length <= maxBytes) { + return value + } + let end = maxBytes + while (end > 0 && (buf[end] & 0xc0) === 0x80) { + end-- + } + return buf.subarray(0, end).toString('utf8') +} + +const SCRUB_INPUT_MAX_BYTES = MAX_DRIVER_INIT_ERROR_BYTES * 4 +const MIN_MASKED_USERNAME_LENGTH = 4 + +function isWordChar(ch: string | undefined) { + return ch !== undefined && /[A-Za-z0-9_]/.test(ch) +} + +function maskWholeToken(text: string, token: string) { + let out = '' + let from = 0 + let at = text.indexOf(token) + while (at !== -1) { + const end = at + token.length + if (!isWordChar(text[at - 1]) && !isWordChar(text[end])) { + out += text.slice(from, at) + '***' + from = end + at = text.indexOf(token, end) + } else { + at = text.indexOf(token, at + 1) + } + } + return out + text.slice(from) +} + +function scrubCredentials(message: string, userName?: string, accessKey?: string) { + let scrubbed = message + const literals = new Set() + if (accessKey) { + literals.add(accessKey) + literals.add(encodeURIComponent(accessKey)) + if (userName) { + literals.add(Buffer.from(`${userName}:${accessKey}`).toString('base64')) + } + } + for (const literal of [...literals].sort((a, b) => b.length - a.length)) { + scrubbed = scrubbed.split(literal).join('***') + } + scrubbed = scrubbed + .replace(/:\/\/[^\s/?#@]+@/g, '://***@') + .replace(/\b(Basic|Bearer)\s+[A-Za-z0-9._~+/=-]{8,}/g, '$1 ***') + .replace(/\b(access_?key|key|token|password)(\s*=\s*["']?|["']\s*:\s*["']?)[^\s&"',;]+/gi, '$1$2***') + if (userName && userName.length >= MIN_MASKED_USERNAME_LENGTH) { + scrubbed = maskWholeToken(scrubbed, userName) + } + return scrubbed +} + +function resolveTesthubUuid() { + const candidates = [TestOpsConfig.getInstance().buildHashedId, process.env[BROWSERSTACK_TESTHUB_UUID]] + return candidates.find((value) => value && value !== 'null' && value !== 'undefined') || null +} + +export function buildDriverInitFailurePayload(details: DriverInitFailureDetails) { + const testhubUuid = resolveTesthubUuid() + const workerId = process.env.WDIO_WORKER_ID + const platformIndex = workerId ? parseInt(workerId.split('-')[0], 10) || 0 : 0 + return { + event_type: 'sdk_events', + data: { + testhub_uuid: testhubUuid, + created_day: formatCreatedDay(), + event_name: DRIVER_INIT_FAILURE_EVENT, + user_data: details.userName || null, + host_info: { + hostname: os.hostname(), + platform: os.platform(), + type: os.type(), + version: os.version(), + arch: os.arch() + }, + event_json: { + errorMessage: truncateToBytes(`[DriverInitError] ${scrubCredentials(truncateToBytes(details.errorMessage, SCRUB_INPUT_MAX_BYTES), details.userName, details.accessKey)}`, MAX_DRIVER_INIT_ERROR_BYTES), + framework: details.framework ? WDIO_NAMING_PREFIX + details.framework : 'unknown', + driverType: 'webdriverio', + event: DRIVER_INIT_FAILURE_EVENT_TAG, + timestamp: Date.now(), + worker: workerId || String(process.pid), + platform: platformIndex, + sdkRunId: testhubUuid + } + } + } +} + +export async function sendDriverInitFailure(details: DriverInitFailureDetails): Promise { + try { + if (!details.userName || !details.accessKey) { + return + } + const payload = buildDriverInitFailurePayload(details) + BStackLogger.debug(`${DRIVER_INIT_FAILURE_EVENT} payload ${JSON.stringify(payload.data.event_json)}`) + + // workers whose sessions fail together post at the same instant and EDS sheds the burst + // with 429/503 before processing it; anything else may have landed, so it is not resent + const deadline = Date.now() + DRIVER_INIT_FAILURE_DEADLINE_MS + let attempts = 0 + while (attempts < DRIVER_INIT_FAILURE_MAX_ATTEMPTS) { + const remaining = deadline - Date.now() + if (remaining <= 0) { + break + } + attempts++ + const { statusCode } = await got.post(`${APIUtils.EDS_URL}/send_sdk_events`, { + headers: { + 'content-type': 'application/json' + }, + username: details.userName, + password: details.accessKey, + json: payload, + timeout: { request: Math.min(DRIVER_INIT_FAILURE_SEND_TIMEOUT_MS, remaining) }, + retry: { limit: 0 }, + throwHttpErrors: false + }) + if (statusCode !== 429 && statusCode !== 503) { + BStackLogger.debug(`Sent EDS event ${DRIVER_INIT_FAILURE_EVENT} | Status ${statusCode}`) + return + } + if (attempts === DRIVER_INIT_FAILURE_MAX_ATTEMPTS) { + break + } + const delay = DRIVER_INIT_FAILURE_RETRY_BASE_MS * attempts * (1 + Math.random() * 2) + if (Date.now() + delay >= deadline) { + break + } + await new Promise((resolve) => setTimeout(resolve, delay)) + } + BStackLogger.debug(`Failed to send EDS event ${DRIVER_INIT_FAILURE_EVENT} after ${attempts} attempts`) + } catch (error) { + BStackLogger.debug(`Failed to send EDS event ${DRIVER_INIT_FAILURE_EVENT}: ${error instanceof Error ? error.message : 'unknown error'}`) + } +} diff --git a/packages/browserstack-service/src/instrumentation/performance/performance-tester.ts b/packages/browserstack-service/src/instrumentation/performance/performance-tester.ts index f9d8db22..aee0b849 100644 --- a/packages/browserstack-service/src/instrumentation/performance/performance-tester.ts +++ b/packages/browserstack-service/src/instrumentation/performance/performance-tester.ts @@ -15,6 +15,7 @@ import { PERF_MEASUREMENT_ENV } from '../../constants.js' import APIUtils from '../../cli/apiUtils.js' import { CLIUtils } from '../../cli/cliUtils.js' import { EVENTS } from './constants.js' +import { formatCreatedDay } from '../createdDay.js' // Telemetry must never throw into business logic. Node 18's perf_hooks rejects // negative timestamps (e.g. performance.now() under faked timers, or any other @@ -390,25 +391,7 @@ export default class PerformanceTester { }) } measures = ensureEpochTimes(measures) - const date = new Date() - // yyyy-MM-dd'T'HH:mm:ss.SSSSSS Z - const options: Intl.DateTimeFormatOptions = { - timeZone: 'UTC', - year: 'numeric', - month: '2-digit', - day: '2-digit', - hour: '2-digit', - minute: '2-digit', - second: '2-digit', - fractionalSecondDigits: 3, // To include microseconds - hour12: false - } - // Format the date and replace the default separator for time zone - const formattedDate = new Intl.DateTimeFormat('en-GB', options) - .formatToParts(date) - .map(({ type, value }) => type === 'timeZoneName' ? 'Z' : value) - .join('') - .replace(',', 'T') + const formattedDate = formatCreatedDay() this.end(EVENTS.SDK_KEY_METRICS_PREPARATION, true) const payload = { diff --git a/packages/browserstack-service/src/service.ts b/packages/browserstack-service/src/service.ts index 55a47701..58b8b78b 100644 --- a/packages/browserstack-service/src/service.ts +++ b/packages/browserstack-service/src/service.ts @@ -31,6 +31,7 @@ import { shouldProcessEventForTesthub } from './testHub/utils.js' import PerformanceTester from './instrumentation/performance/performance-tester.js' import * as PERFORMANCE_SDK_EVENTS from './instrumentation/performance/constants.js' import { EVENTS } from './instrumentation/performance/constants.js' +import { sendDriverInitFailure } from './instrumentation/funnelInstrumentation.js' import { BrowserstackCLI } from './cli/index.js' import { TestFrameworkState } from './cli/states/testFrameworkState.js' import { HookState } from './cli/states/hookState.js' @@ -75,6 +76,9 @@ export default class BrowserstackService implements Services.ServiceInstance { private _percyCaptureMode: string | undefined = undefined private _percyHandler?: PercyHandler private _turboScale + private _sessionInitAttempted: boolean = false + private _sessionCreated: boolean = false + private _driverInitFailureReported: boolean = false constructor ( options: BrowserstackConfig & Options.Testrunner, @@ -128,6 +132,7 @@ export default class BrowserstackService implements Services.ServiceInstance { @PerformanceTester.Measure(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_HOOK, { hookType: 'beforeSession' }) async beforeSession (config: Omit, capabilities: WebdriverIO.Capabilities) { + this._sessionInitAttempted = true PerformanceTester.start(PERFORMANCE_SDK_EVENTS.DRIVER_EVENT.INIT) // if no user and key is specified even though a browserstack service was @@ -189,6 +194,7 @@ export default class BrowserstackService implements Services.ServiceInstance { @PerformanceTester.Measure(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_HOOK, { hookType: 'before' }) async before(caps: Capabilities.RemoteCapability, specs: string[], browser: WebdriverIO.Browser) { + this._sessionCreated = true // End device allocation tracking - remote session is now created and browser object is available PerformanceTester.end(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_DEVICE_ALLOCATION, true, 'Device allocated and session created') BStackLogger.debug('Device allocation tracking ended - remote session created successfully') @@ -542,6 +548,10 @@ export default class BrowserstackService implements Services.ServiceInstance { } async after (result: number) { + // wdio calls `after` without `before` only when the worker could not create its session + if (this._sessionInitAttempted && !this._sessionCreated) { + await this._reportDriverInitFailure() + } PerformanceTester.start(PERFORMANCE_SDK_EVENTS.HOOK_EVENTS.AFTER) PerformanceTester.start(PERFORMANCE_SDK_EVENTS.DRIVER_EVENT.QUIT) @@ -916,6 +926,24 @@ export default class BrowserstackService implements Services.ServiceInstance { this._cliCucumberFramework()?.onStepEnd(step, result) } + async _reportDriverInitFailure() { + if (this._driverInitFailureReported) { + return + } + this._driverInitFailureReported = true + try { + const { hostname, connectionRetryTimeout, connectionRetryCount } = this._config + await sendDriverInitFailure({ + userName: this._config.user, + accessKey: this._config.key, + framework: this._config.framework, + errorMessage: `WebdriverIO session could not be created (hostname=${hostname}, connectionRetryTimeout=${connectionRetryTimeout}ms, connectionRetryCount=${connectionRetryCount})` + }) + } catch (err) { + BStackLogger.debug(`Exception reporting driver init failure: ${util.format(err)}`) + } + } + @PerformanceTester.Measure(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_HOOK, { hookType: 'onReload' }) async onReload(oldSessionId: string, newSessionId: string) { if (!this._browser) { diff --git a/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts b/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts index 78c2585a..e95113a3 100644 --- a/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts +++ b/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts @@ -5,6 +5,8 @@ import fs from 'node:fs' import got from 'got' import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import { FUNNEL_INSTRUMENTATION_URL } from '../../src/constants.js' +import { formatCreatedDay } from '../../src/instrumentation/createdDay.js' +import TestOpsConfig from '../../src/testOps/testOpsConfig.js' vi.mock('got', () => ({ default: { @@ -183,3 +185,341 @@ describe('funnelInstrumentation', () => { })) }) }) + +describe('DriverInitFailure', () => { + beforeEach(() => { + process.env.BROWSERSTACK_TESTHUB_UUID = 'testhub-uuid-1' + process.env.WDIO_WORKER_ID = '2-1' + vi.mocked(got.post).mockReset() + vi.mocked(got.post).mockResolvedValue({ statusCode: 200 } as never) + }) + + afterEach(() => { + delete process.env.BROWSERSTACK_TESTHUB_UUID + delete process.env.WDIO_WORKER_ID + }) + + it('builds the sdk_events payload keyed by the TestHub build uuid', () => { + const payload = FunnelTestEvent.buildDriverInitFailurePayload({ userName: 'user', accessKey: 'key', framework: 'mocha', errorMessage: 'boom' }) + + expect(payload.event_type).toBe('sdk_events') + expect(Object.keys(payload.data)).toEqual(['testhub_uuid', 'created_day', 'event_name', 'user_data', 'host_info', 'event_json']) + expect(payload.data).toMatchObject({ testhub_uuid: 'testhub-uuid-1', event_name: 'DriverInitFailure', user_data: 'user' }) + expect(payload.data.created_day).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6} UTC$/) + expect(Object.keys(payload.data.host_info)).toEqual(['hostname', 'platform', 'type', 'version', 'arch']) + expect(payload.data.event_json).toEqual({ + errorMessage: '[DriverInitError] boom', + framework: 'WebdriverIO-mocha', + driverType: 'webdriverio', + event: 'sdk:driver:init:failure', + timestamp: expect.any(Number), + worker: '2-1', + platform: 2, + sdkRunId: 'testhub-uuid-1' + }) + }) + + it('formats created_day as UTC ISO with microseconds and a UTC suffix', () => { + expect(formatCreatedDay(new Date('2026-12-01T09:41:04.106Z'))).toBe('2026-12-01T09:41:04.106000 UTC') + expect(formatCreatedDay(new Date('2026-03-25T23:59:59.007Z'))).toBe('2026-03-25T23:59:59.007000 UTC') + expect(formatCreatedDay(new Date('2026-12-01T23:30:00.000-05:00'))).toBe('2026-12-02T04:30:00.000000 UTC') + }) + + it('sends null testhub_uuid when the build uuid is not known', () => { + delete process.env.BROWSERSTACK_TESTHUB_UUID + const payload = FunnelTestEvent.buildDriverInitFailurePayload({ errorMessage: 'boom' }) + + expect(payload.data.testhub_uuid).toBeNull() + expect(payload.data.event_json.framework).toBe('unknown') + }) + + describe('testhub_uuid resolution', () => { + const testOpsConfig = TestOpsConfig.getInstance() + let savedBuildHashedId: string | undefined + + beforeEach(() => { + savedBuildHashedId = testOpsConfig.buildHashedId + testOpsConfig.buildHashedId = undefined + }) + + afterEach(() => { + testOpsConfig.buildHashedId = savedBuildHashedId + }) + + it('prefers the build hashed id the process owns', () => { + testOpsConfig.buildHashedId = 'owned-build-uuid' + const payload = FunnelTestEvent.buildDriverInitFailurePayload({ errorMessage: 'boom' }) + + expect(payload.data.testhub_uuid).toBe('owned-build-uuid') + expect(payload.data.event_json.sdkRunId).toBe('owned-build-uuid') + }) + + it('falls back to the inherited env var in a worker', () => { + expect(FunnelTestEvent.buildDriverInitFailurePayload({ errorMessage: 'boom' }).data.testhub_uuid).toBe('testhub-uuid-1') + }) + + it.each(['undefined', 'null', ''])('treats an env value of %j as unknown', (value) => { + process.env.BROWSERSTACK_TESTHUB_UUID = value + const payload = FunnelTestEvent.buildDriverInitFailurePayload({ errorMessage: 'boom' }) + + expect(payload.data.testhub_uuid).toBeNull() + expect(payload.data.event_json.sdkRunId).toBeNull() + }) + }) + + it('caps the error message at 8000 bytes', () => { + const payload = FunnelTestEvent.buildDriverInitFailurePayload({ errorMessage: 'é'.repeat(10000) }) + + expect(Buffer.byteLength(payload.data.event_json.errorMessage, 'utf8')).toBeLessThanOrEqual(8000) + }) + + it.each([ + ['3-byte', 0, '€'], + ['3-byte', 1, '€'], + ['3-byte', 2, '€'], + ['4-byte', 0, '😀'], + ['4-byte', 1, '😀'], + ['4-byte', 2, '😀'], + ['4-byte', 3, '😀'] + ])('cuts a %s character after %i leading bytes back to a whole code point within 8000 bytes', (_width, pad, char) => { + const payload = FunnelTestEvent.buildDriverInitFailurePayload({ errorMessage: 'a'.repeat(pad) + char.repeat(5000) }) + const message = payload.data.event_json.errorMessage + + expect(Buffer.byteLength(message, 'utf8')).toBeLessThanOrEqual(8000) + expect(Buffer.byteLength(message, 'utf8')).toBeGreaterThan(8000 - Buffer.byteLength(char, 'utf8')) + expect(message).not.toContain('\uFFFD') + expect(message.endsWith(char)).toBe(true) + }) + + it('keeps credentials out of the request body and the debug log', async () => { + const debug = vi.spyOn(BStackLogger, 'debug').mockImplementation(() => {}) + await FunnelTestEvent.sendDriverInitFailure({ + userName: 'jane_doe1', + accessKey: 'placeholder-secret', + framework: 'mocha', + errorMessage: 'Failed to create session at https://jane_doe1:placeholder-secret@hub.example.com/wd/hub; rejected placeholder-secret for jane_doe1, proxy http://u:p@proxy.local:8080' + }) + + const json = (vi.mocked(got.post).mock.calls[0] as unknown as [string, any])[1].json + const body = JSON.stringify(json) + const logged = debug.mock.calls.map(([line]) => String(line)).join('\n') + for (const text of [body, logged]) { + expect(text).not.toContain('placeholder-secret') + expect(text).not.toContain('u:p@') + } + expect(JSON.stringify(json.data.event_json)).not.toContain('jane_doe1') + expect(logged).not.toContain('jane_doe1') + expect(json.data.event_json.errorMessage).toBe( + '[DriverInitError] Failed to create session at https://***@hub.example.com/wd/hub; rejected *** for ***, proxy http://***@proxy.local:8080' + ) + debug.mockRestore() + }) + + it('leaves a message without credentials unchanged', () => { + const errorMessage = 'Failed to create a session on hub-cloud.browserstack.com after 3 retries (connectionRetryTimeout 1500ms): fetch failed' + const payload = FunnelTestEvent.buildDriverInitFailurePayload({ userName: 'user', accessKey: 'key', errorMessage }) + + expect(payload.data.event_json.errorMessage).toBe(`[DriverInitError] ${errorMessage}`) + }) + + const scrubbed = (errorMessage: string, userName = 'jane_doe1', accessKey = 'placeholder-secret') => + FunnelTestEvent.buildDriverInitFailurePayload({ userName, accessKey, errorMessage }).data.event_json.errorMessage + + it('scrubs a 100KB run of scheme characters in linear time', () => { + const errorMessage = 'a1+.-'.repeat(20000) + const start = performance.now() + const message = scrubbed(errorMessage) + const elapsed = performance.now() - start + + expect(elapsed).toBeLessThan(200) + expect(Buffer.byteLength(message, 'utf8')).toBeLessThanOrEqual(8000) + }) + + it('masks Basic and Bearer credentials', () => { + expect(scrubbed('header Authorization: Basic dXNlcjpwYXNzd29yZA== rejected')) + .toBe('[DriverInitError] header Authorization: Basic *** rejected') + expect(scrubbed('header Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.e30.sig rejected')) + .toBe('[DriverInitError] header Authorization: Bearer *** rejected') + }) + + it('masks the base64 of userName:accessKey wherever it appears', () => { + const encoded = Buffer.from('jane_doe1:placeholder-secret').toString('base64') + expect(scrubbed(`auth blob ${encoded} rejected`)).toBe('[DriverInitError] auth blob *** rejected') + }) + + it('masks the URL-encoded access key', () => { + const accessKey = 'p@ss/k+y=1' + expect(scrubbed(`GET /status?k=${encodeURIComponent(accessKey)} and raw ${accessKey}`, 'jane_doe1', accessKey)) + .toBe('[DriverInitError] GET /status?k=*** and raw ***') + }) + + it.each([ + ['access_key=abc123', 'access_key=***'], + ['accessKey=abc123', 'accessKey=***'], + ['key=abc123', 'key=***'], + ['token=abc123', 'token=***'], + ['password=abc123', 'password=***'], + ['"accessKey":"abc123"', '"accessKey":"***"'], + ['password = \'abc123\'', 'password = \'***\''] + ])('masks the value of %s', (input, expected) => { + expect(scrubbed(`https://api.example.com/app?x=1&${input}&y=2`)) + .toBe(`[DriverInitError] https://api.example.com/app?x=1&${expected}&y=2`) + }) + + it('does not alter hostnames for a short userName', () => { + expect(scrubbed('Could not reach hub.browserstack.com for ab', 'ab')) + .toBe('[DriverInitError] Could not reach hub.browserstack.com for ab') + }) + + it('masks a userName only as a whole token', () => { + expect(scrubbed('user jane rejected; janet, jane_x and xjane kept', 'jane')) + .toBe('[DriverInitError] user *** rejected; janet, jane_x and xjane kept') + }) + + it('masks a whole-token userName that overlaps a rejected match', () => { + expect(scrubbed('abab-ab ababa abab', 'abab')) + .toBe('[DriverInitError] ***-ab ababa ***') + }) + + it('treats regex metacharacters in a userName literally', () => { + expect(scrubbed('user a.b+c(1) rejected; axb+c(1) kept; a.b+c(1)', 'a.b+c(1)')) + .toBe('[DriverInitError] user *** rejected; axb+c(1) kept; ***') + }) + + it('masks every occurrence of a whole-token userName', () => { + expect(scrubbed('jane jane,jane;(jane)', 'jane')) + .toBe('[DriverInitError] *** ***,***;(***)') + }) + + it('logs only the error message when the send throws', async () => { + const debug = vi.spyOn(BStackLogger, 'debug').mockImplementation(() => {}) + const error = Object.assign(new Error('socket hang up'), { options: { headers: { authorization: 'Basic c2VjcmV0' } } }) + vi.mocked(got.post).mockRejectedValueOnce(error) + await FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', errorMessage: 'boom' }) + + expect(debug).toHaveBeenLastCalledWith('Failed to send EDS event DriverInitFailure: socket hang up') + debug.mockRestore() + }) + + it('posts to the EDS send_sdk_events endpoint with basic auth and no got retries', async () => { + await FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', framework: 'mocha', errorMessage: 'boom' }) + + expect(got.post).toHaveBeenCalledTimes(1) + const [url, options] = vi.mocked(got.post).mock.calls[0] as unknown as [string, any] + expect(url).toBe('https://eds.browserstack.com/send_sdk_events') + expect(options).toMatchObject({ username: 'user', password: 'key', retry: { limit: 0 }, throwHttpErrors: false }) + expect(options.json.data.event_name).toBe('DriverInitFailure') + }) + + it('sends nothing without credentials', async () => { + await FunnelTestEvent.sendDriverInitFailure({ framework: 'mocha', errorMessage: 'boom' }) + + expect(got.post).not.toHaveBeenCalled() + }) + + it('resends only while EDS sheds the request with 429/503', async () => { + vi.useFakeTimers() + vi.mocked(got.post) + .mockResolvedValueOnce({ statusCode: 503 } as never) + .mockResolvedValueOnce({ statusCode: 429 } as never) + .mockResolvedValueOnce({ statusCode: 200 } as never) + const sending = FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', errorMessage: 'boom' }) + await vi.runAllTimersAsync() + await sending + vi.useRealTimers() + + expect(got.post).toHaveBeenCalledTimes(3) + }) + + it('gives up after four attempts', async () => { + vi.useFakeTimers() + vi.mocked(got.post).mockResolvedValue({ statusCode: 503 } as never) + const sending = FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', errorMessage: 'boom' }) + await vi.runAllTimersAsync() + await sending + vi.useRealTimers() + + expect(got.post).toHaveBeenCalledTimes(4) + }) + + describe('within the 10s deadline', () => { + const shedAfter = (ms: number) => (_url: unknown, options: any) => new Promise((resolve, reject) => { + const limit = options.timeout.request + if (ms < limit) { + setTimeout(() => resolve({ statusCode: 503 }), ms) + } else { + setTimeout(() => reject(new Error(`Timeout awaiting 'request' for ${limit}ms`)), limit) + } + }) + + const timeSend = async () => { + const start = Date.now() + const sending = FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', errorMessage: 'boom' }) + await vi.runAllTimersAsync() + await sending + return Date.now() - start + } + + let randomSpy: ReturnType | undefined + + beforeEach(() => { + vi.useFakeTimers() + }) + + afterEach(() => { + randomSpy?.mockRestore() + randomSpy = undefined + vi.useRealTimers() + }) + + it('skips a backoff that would overrun the deadline', async () => { + randomSpy = vi.spyOn(Math, 'random').mockReturnValue(1) + vi.mocked(got.post).mockImplementation(shedAfter(4000) as never) + + const elapsed = await timeSend() + + expect(got.post).toHaveBeenCalledTimes(2) + expect(elapsed).toBe(9500) + }) + + it('caps the last attempt at the time remaining', async () => { + randomSpy = vi.spyOn(Math, 'random').mockReturnValue(0) + vi.mocked(got.post).mockImplementation(shedAfter(3000) as never) + + const elapsed = await timeSend() + + expect(got.post).toHaveBeenCalledTimes(3) + expect((vi.mocked(got.post).mock.calls[2] as any)[1].timeout.request).toBe(2500) + expect(elapsed).toBe(10000) + }) + + it('does not resend after an attempt times out', async () => { + vi.mocked(got.post).mockImplementation(shedAfter(60000) as never) + + const elapsed = await timeSend() + + expect(got.post).toHaveBeenCalledTimes(1) + expect(elapsed).toBe(5000) + }) + + it('never exceeds the deadline while EDS keeps shedding', async () => { + for (const latency of [0, 1000, 2500, 4999]) { + vi.mocked(got.post).mockReset().mockImplementation(shedAfter(latency) as never) + expect(await timeSend()).toBeLessThanOrEqual(10000) + } + }) + }) + + it('does not resend a request that may have landed', async () => { + vi.mocked(got.post).mockResolvedValueOnce({ statusCode: 500 } as never) + await FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', errorMessage: 'boom' }) + + expect(got.post).toHaveBeenCalledTimes(1) + }) + + it('never throws when the request fails', async () => { + vi.mocked(got.post).mockRejectedValue(new Error('network down')) + + await expect(FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', errorMessage: 'boom' })).resolves.toBeUndefined() + }) +}) diff --git a/packages/browserstack-service/tests/performance-tester.test.ts b/packages/browserstack-service/tests/performance-tester.test.ts index 59875f26..2487d233 100644 --- a/packages/browserstack-service/tests/performance-tester.test.ts +++ b/packages/browserstack-service/tests/performance-tester.test.ts @@ -2,6 +2,7 @@ import fsPromises from 'node:fs/promises' import fs from 'node:fs' import { describe, expect, it, vi, afterEach, beforeEach } from 'vitest' import { performance } from 'node:perf_hooks' +import got from 'got' import * as bstackLogger from '../src/bstackLogger.js' import PerformanceTester from '../src/instrumentation/performance/performance-tester.js' @@ -213,4 +214,25 @@ describe('PerformanceTester', function () { ) }) }) + describe('uploadEventsData', () => { + const originalAccess = fsPromises.access + afterEach(() => { + fsPromises.access = originalAccess + vi.useRealTimers() + vi.restoreAllMocks() + }) + + it('sends created_day as UTC ISO with microseconds and a UTC suffix', async () => { + vi.useFakeTimers({ now: new Date('2026-12-01T09:41:04.106Z'), toFake: ['Date'] }) + fsPromises.access = vi.fn().mockRejectedValue(new Error('missing')) + const postMock = vi.spyOn(got, 'post').mockResolvedValue({ body: '{}' } as any) + + await PerformanceTester.uploadEventsData() + + expect(postMock).toHaveBeenCalledTimes(1) + const { json } = postMock.mock.calls[0][1] as any + expect(json.data.event_name).toBe('SDKFeaturePerformance') + expect(json.data.created_day).toBe('2026-12-01T09:41:04.106000 UTC') + }) + }) }) diff --git a/packages/browserstack-service/tests/service.test.ts b/packages/browserstack-service/tests/service.test.ts index 377b9fbf..da707d79 100644 --- a/packages/browserstack-service/tests/service.test.ts +++ b/packages/browserstack-service/tests/service.test.ts @@ -2341,3 +2341,77 @@ describe('cucumber CLI dispatch (binary flow)', () => { }) }) + +describe('DriverInitFailure when the worker cannot create its session', () => { + const edsCalls = () => vi.mocked(got.post).mock.calls + .filter(([url]) => String(url).endsWith('/send_sdk_events')) + .map(([, options]) => (options as { json: any }).json) + const makeService = () => new BrowserstackService( + { testObservability: false } as never, + [] as never, + { user: 'foo', key: 'bar', framework: 'jasmine', hostname: 'hub.browserstack.com', connectionRetryTimeout: 1500, connectionRetryCount: 0 } as never + ) + + beforeEach(() => { + process.env.BROWSERSTACK_TESTHUB_UUID = 'testhub-uuid-1' + process.env.WDIO_WORKER_ID = '1-0' + // the manual got mock has no `post` + Object.assign(got, { post: vi.fn().mockResolvedValue({ statusCode: 200 }) }) + }) + + afterEach(() => { + delete process.env.BROWSERSTACK_TESTHUB_UUID + delete process.env.WDIO_WORKER_ID + delete (got as unknown as { post?: unknown }).post + }) + + it('sends exactly one DriverInitFailure when after() runs without before()', async () => { + const svc = makeService() + await svc.beforeSession({ user: 'foo', key: 'bar' } as never, {} as never) + await svc.after(1) + await svc.after(1) + + const events = edsCalls() + expect(events).toHaveLength(1) + expect(events[0].event_type).toBe('sdk_events') + expect(events[0].data).toMatchObject({ + testhub_uuid: 'testhub-uuid-1', + event_name: 'DriverInitFailure', + user_data: 'foo' + }) + expect(events[0].data.event_json).toMatchObject({ + framework: 'WebdriverIO-jasmine', + driverType: 'webdriverio', + event: 'sdk:driver:init:failure', + worker: '1-0', + platform: 1, + sdkRunId: 'testhub-uuid-1' + }) + expect(events[0].data.event_json.errorMessage).toContain('[DriverInitError] WebdriverIO session could not be created') + expect(events[0].data.event_json.errorMessage).toContain('connectionRetryTimeout=1500ms') + }) + + it('sends nothing when the session was created', async () => { + const svc = makeService() + await svc.beforeSession({ user: 'foo', key: 'bar' } as never, {} as never) + await svc.before({} as never, [], browser as WebdriverIO.Browser) + await svc.after(0) + + expect(edsCalls()).toHaveLength(0) + }) + + it('sends nothing when no session was attempted', async () => { + await makeService().after(1) + + expect(edsCalls()).toHaveLength(0) + }) + + it('does not fail after() when the event cannot be sent', async () => { + const svc = makeService() + await svc.beforeSession({ user: 'foo', key: 'bar' } as never, {} as never) + vi.mocked(got.post).mockRejectedValue(new Error('network down')) + + await expect(svc.after(1)).resolves.not.toThrow() + expect(edsCalls()).toHaveLength(1) + }) +})