From 31f2ca7bf74be2b6629bf96aa74274e70fc4485e Mon Sep 17 00:00:00 2001 From: "shopify-build-cli[bot]" <145388831+shopify-build-cli[bot]@users.noreply.github.com> Date: Sat, 5 Dec 2026 01:01:00 +0000 Subject: [PATCH] Update from World Published by the World mirror. World-Commit: c4cf3658aabb28507072817dc76b3f4093533c5f --- .../redact-shopify-tokens-error-reports.md | 6 + .../node/analytics/error-grouping.test.ts | 9 + .../private/node/analytics/error-grouping.ts | 4 +- .../src/private/node/analytics/redact.test.ts | 94 +++++++++ .../src/private/node/analytics/redact.ts | 37 ++++ .../cli-kit/src/public/node/analytics.test.ts | 29 +++ packages/cli-kit/src/public/node/analytics.ts | 4 +- .../src/public/node/error-handler.test.ts | 178 ++++++++++++++++-- .../cli-kit/src/public/node/error-handler.ts | 31 ++- 9 files changed, 373 insertions(+), 19 deletions(-) create mode 100644 .changeset/redact-shopify-tokens-error-reports.md create mode 100644 packages/cli-kit/src/private/node/analytics/redact.test.ts create mode 100644 packages/cli-kit/src/private/node/analytics/redact.ts diff --git a/.changeset/redact-shopify-tokens-error-reports.md b/.changeset/redact-shopify-tokens-error-reports.md new file mode 100644 index 00000000000..79b03721e5d --- /dev/null +++ b/.changeset/redact-shopify-tokens-error-reports.md @@ -0,0 +1,6 @@ +--- +'@shopify/cli-kit': patch +'@shopify/cli': patch +--- + +Remove Shopify tokens and Theme Access passwords from the error reports and usage analytics that the CLI sends, also from the details that plugins add to error reports. diff --git a/packages/cli-kit/src/private/node/analytics/error-grouping.test.ts b/packages/cli-kit/src/private/node/analytics/error-grouping.test.ts index a87c5cedf80..e18fb88a001 100644 --- a/packages/cli-kit/src/private/node/analytics/error-grouping.test.ts +++ b/packages/cli-kit/src/private/node/analytics/error-grouping.test.ts @@ -101,6 +101,15 @@ describe('errorGroupingHash — message fallback', () => { test('returns undefined for a non-Error value', () => { expect(errorGroupingHash(undefined, 'cli')).toBeUndefined() }) + + test('builds the hash from the message without its Shopify tokens', () => { + const error = new Error('Invalid value "shpat_fake_token_value" for header "X-Shopify-Access-Token"') + + const hash = errorGroupingHash(error, 'theme') + + expect(hash).toEqual('theme:authentication:invalid-value-for-header-x-shopify-access') + expect(hash).not.toMatch(/shpat|fake|token-value/) + }) }) describe('errorGroupingHash — multi-error & nested codes (review #3/#5)', () => { diff --git a/packages/cli-kit/src/private/node/analytics/error-grouping.ts b/packages/cli-kit/src/private/node/analytics/error-grouping.ts index 05e1673b578..926c8a1b714 100644 --- a/packages/cli-kit/src/private/node/analytics/error-grouping.ts +++ b/packages/cli-kit/src/private/node/analytics/error-grouping.ts @@ -1,5 +1,6 @@ import {categorizeError, ErrorCategory, formatErrorMessage} from './error-categorizer.js' import {graphQLErrorCodes, isPermissionCode, isRateLimitCode} from './graphql-error-codes.js' +import {redactShopifyTokens} from './redact.js' import {GraphQLClientError} from '../api/headers.js' import {slugify} from '../../../public/common/string.js' import {ClientError} from 'graphql-request' @@ -77,7 +78,8 @@ export function errorGroupingSignals(error: unknown): ErrorGroupingSignals { * @returns The resolved hash (or `undefined`), category, and structured signals. */ export function resolveErrorGrouping(error: unknown, sliceName: string): ResolvedErrorGrouping { - const message = errorMessage(error) + // The hash keeps part of the message, so a token in the message would reach the report. + const message = redactShopifyTokens(errorMessage(error)) // Object signals are authoritative; message-derived signals fill gaps (e.g. 5xx errors that the // API layer flattens into an AbortError, dropping the structured status field). Merge field by // field so an absent object signal never clobbers one recovered from the message. diff --git a/packages/cli-kit/src/private/node/analytics/redact.test.ts b/packages/cli-kit/src/private/node/analytics/redact.test.ts new file mode 100644 index 00000000000..1bddb23ed57 --- /dev/null +++ b/packages/cli-kit/src/private/node/analytics/redact.test.ts @@ -0,0 +1,94 @@ +import {redactShopifyTokens, redactShopifyTokensInValue} from './redact.js' +import {describe, expect, test} from 'vitest' + +describe('redactShopifyTokens', () => { + test.each(['shpat_', 'shpca_', 'shppa_', 'shpss_', 'shprt_', 'shpsb_', 'shptka_', 'shpua_', 'atkn_'])( + 'redacts a %s credential', + (prefix) => { + const credential = `${prefix}fake_value` + + const redacted = redactShopifyTokens(`Invalid value "${credential}" for header "X-Shopify-Access-Token"`) + + expect(redacted).toBe('Invalid value "*****" for header "X-Shopify-Access-Token"') + }, + ) + + test('redacts the whole of an Identity token that has parts', () => { + const text = 'Authorization: Bearer atkn_2.CiQfake-part_one.second~part+/3==. Try again.' + + expect(redactShopifyTokens(text)).toBe('Authorization: Bearer *****. Try again.') + }) + + test('redacts every credential in a multiline text', () => { + const text = [ + 'Error: request failed with shpat_fake_token', + ' at fetch (headers: {"X-Shopify-Access-Token":"shptka_fake_password"})', + ].join('\n') + + expect(redactShopifyTokens(text)).toBe( + ['Error: request failed with *****', ' at fetch (headers: {"X-Shopify-Access-Token":"*****"})'].join('\n'), + ) + }) + + test('keeps a serialized JSON payload valid', () => { + const payload = JSON.stringify({ + error_message: 'Invalid password "shpat_abc123"\nTry again', + args: '--password shptka_x', + }) + + expect(JSON.parse(redactShopifyTokens(payload))).toEqual({ + error_message: 'Invalid password "*****"\nTry again', + args: '--password *****', + }) + }) + + test('keeps a bare prefix and text without credentials', () => { + const text = 'Use a token that starts with shpat_, shptka_ or atkn_, not ghp_abc or shopify_app' + + expect(redactShopifyTokens(text)).toBe(text) + }) +}) + +describe('redactShopifyTokensInValue', () => { + test('redacts the credentials in every nested string', () => { + const value = { + config: { + overriddenEnvironmentVariables: [ + {isSecret: true, key: 'PRIVATE_API_TOKEN', value: 'shpat_fake_token'}, + {isSecret: true, key: 'SESSION', value: 'Bearer atkn_fake_token'}, + ], + workerOnly: false, + verificationMaxDuration: 180, + }, + } + + expect(redactShopifyTokensInValue(value)).toEqual({ + config: { + overriddenEnvironmentVariables: [ + {isSecret: true, key: 'PRIVATE_API_TOKEN', value: '*****'}, + {isSecret: true, key: 'SESSION', value: 'Bearer *****'}, + ], + workerOnly: false, + verificationMaxDuration: 180, + }, + }) + }) + + test('leaves the original value unchanged', () => { + const value = {headers: ['X-Shopify-Access-Token: shpat_fake_token']} + + redactShopifyTokensInValue(value) + + expect(value).toEqual({headers: ['X-Shopify-Access-Token: shpat_fake_token']}) + }) + + test('copies a value that refers to itself', () => { + const value: {token: string; self?: unknown} = {token: 'shpat_fake_token'} + value.self = value + + const redacted = redactShopifyTokensInValue(value) + + expect(redacted.token).toBe('*****') + expect(redacted.self).toBe(redacted) + }) +}) diff --git a/packages/cli-kit/src/private/node/analytics/redact.ts b/packages/cli-kit/src/private/node/analytics/redact.ts new file mode 100644 index 00000000000..4a78ba5258d --- /dev/null +++ b/packages/cli-kit/src/private/node/analytics/redact.ts @@ -0,0 +1,37 @@ +import cloneDeepWith from 'lodash/cloneDeepWith.js' + +// The public prefixes of Shopify access tokens, API secrets, Theme Access passwords and Identity +// access tokens. An Identity token can hold dots between its parts (`atkn_2.…`). A bare prefix with +// nothing after it holds no secret, so it stays. The value never takes a backslash or a quote, so +// redacting a serialized JSON string leaves it valid JSON. +const SHOPIFY_TOKEN_PATTERN = /shp(?:at|ca|pa|ss|rt|sb|tka|ua)_\w+|atkn_[\w~+/-]+(?:\.[\w~+/-]+)*=*/g + +/** + * Replaces every Shopify access token, API secret, Theme Access password and Identity access token + * in a text with `*****`. + * + * Use it on any text that leaves the user's machine and can repeat a credential, such as an error + * message, a stack trace or a serialized analytics payload. + * + * @param text - The text to redact. + * @returns The text with each Shopify credential replaced. + */ +export function redactShopifyTokens(text: string): string { + return text.replace(SHOPIFY_TOKEN_PATTERN, '*****') +} + +/** + * Returns a deep copy of a value in which every string has its Shopify credentials replaced with + * `*****`, as {@link redactShopifyTokens} does. + * + * Use it on structured data that leaves the user's machine, such as the metadata of an error report. + * The original value stays as it is, because other code can still read it. + * + * @param value - The value to redact. + * @returns The redacted copy. + */ +export function redactShopifyTokensInValue(value: T): T { + return cloneDeepWith(value, (item: unknown) => + typeof item === 'string' ? redactShopifyTokens(item) : undefined, + ) as T +} diff --git a/packages/cli-kit/src/public/node/analytics.test.ts b/packages/cli-kit/src/public/node/analytics.test.ts index 02ed9838c1c..1a494864e23 100644 --- a/packages/cli-kit/src/public/node/analytics.test.ts +++ b/packages/cli-kit/src/public/node/analytics.test.ts @@ -407,6 +407,35 @@ describe('event tracking', () => { }) }) + test('does not send Shopify access tokens to Monorail', async () => { + await inProjectWithFile('package.json', async (args) => { + // Given + const accessToken = 'shpat_fake_token' + const commandContent = {command: 'dev', topic: 'theme'} + const argsWithPassword = args.concat(['--password', accessToken]) + await startAnalytics({commandContent, args: argsWithPassword, currentTime: currentDate.getTime() - 100}) + + // When + const config = { + runHook: vi.fn().mockResolvedValue({successes: [], failures: []}), + plugins: [], + } as any + await reportAnalyticsEvent({ + config, + errorMessage: `Invalid value "${accessToken}" for header "X-Shopify-Access-Token"`, + exitMode: 'unexpected_error', + }) + await sendReportedAnalyticsPayload() + + // Then + expect(publishEventMock).toHaveBeenCalledOnce() + const sensitivePayload = publishEventMock.mock.calls[0]![2] + expect(sensitivePayload.args).toContain('--password *****') + expect(sensitivePayload.error_message).toBe('Invalid value "*****" for header "X-Shopify-Access-Token"') + expect(JSON.stringify(publishEventMock.mock.calls[0])).not.toContain('shpat_') + }) + }) + test('does not send store password environment flags to Monorail', async () => { await inProjectWithFile('package.json', async (args) => { const commandContent = {command: 'dev', topic: 'app'} diff --git a/packages/cli-kit/src/public/node/analytics.ts b/packages/cli-kit/src/public/node/analytics.ts index 34cf3be704f..2fec4ab4a39 100644 --- a/packages/cli-kit/src/public/node/analytics.ts +++ b/packages/cli-kit/src/public/node/analytics.ts @@ -13,6 +13,7 @@ import { RuntimeData, } from '../../private/node/analytics/storage.js' import {getEnvironmentData, getSensitiveEnvironmentData} from '../../private/node/analytics.js' +import {redactShopifyTokens} from '../../private/node/analytics/redact.js' import {CLI_KIT_VERSION} from '../common/version.js' import {recordMetrics} from '../../private/node/otel-metrics.js' import {runWithRateLimit} from '../../private/node/conf-store.js' @@ -272,8 +273,7 @@ function sanitizePayload(payload: T): T { // escaped. Every flag rule below matches that escaped form first, and its bare-value alternative // treats a JSON escape as part of the value, so a value can never be redacted only halfway or leave // behind a string that no longer parses. - const sanitizedPayloadString = payloadString - .replace(/shptka_\w*/g, '*****') + const sanitizedPayloadString = redactShopifyTokens(payloadString) .replace(/(--store-password(?:=|\s+))(?:\\"[^"\\]*\\"|'[^']*'|(?:\\.|[^\s"\\])+)/g, '$1*****') .replace(/((?:store-password|SHOPIFY_FLAG_STORE_PASSWORD)\\?":\\?")[^"\\]*/g, '$1*****') .replace(/(--signup(?:=|\s+))(?:\\"[^"\\]*\\"|'[^']*'|(?:\\.|[^\s"\\])+)/g, '$1*****') diff --git a/packages/cli-kit/src/public/node/error-handler.test.ts b/packages/cli-kit/src/public/node/error-handler.test.ts index f30ca603b30..1d8af092f36 100644 --- a/packages/cli-kit/src/public/node/error-handler.test.ts +++ b/packages/cli-kit/src/public/node/error-handler.test.ts @@ -1,4 +1,10 @@ -import {errorHandler, cleanStackFrameFilePath, addBugsnagMetadata, sendErrorToBugsnag} from './error-handler.js' +import { + errorHandler, + cleanStackFrameFilePath, + addBugsnagMetadata, + sendErrorToBugsnag, + registerCleanBugsnagErrorsFromWithinPlugins, +} from './error-handler.js' import * as metadata from './metadata.js' import {ciPlatform, cloudEnvironment, isUnitTest, macAddress} from './context/local.js' import {mockAndCaptureOutput} from './testing/output.js' @@ -9,28 +15,41 @@ import {getLastSeenUserIdAfterAuth} from '../../private/node/session.js' import {GraphQLClientError} from '../../private/node/api/headers.js' import {settings} from '@oclif/core' +import Bugsnag, {Breadcrumb, Event, OnErrorCallback} from '@bugsnag/js' import {beforeEach, describe, expect, test, vi} from 'vitest' const onNotify = vi.fn() const capturedEventHandler = vi.fn() -let lastBugsnagEvent: {addMetadata: ReturnType; groupingHash?: string} | undefined +let lastBugsnagEvent: Event | undefined +let breadcrumbsOfNextBugsnagEvent: Breadcrumb[] = [] +let clientMetadataOfNextBugsnagEvent: {[section: string]: {[key: string]: unknown}} = {} vi.mock('process') -vi.mock('@bugsnag/js', () => { +vi.mock('@bugsnag/js', async (importOriginal) => { + const {default: realBugsnag} = await importOriginal() + const RealEvent = (realBugsnag as unknown as {Event: typeof Event}).Event return { default: { + Event: RealEvent, notify: (reportedError: any, eventHandler: any, callback: any) => { onNotify(reportedError) - // Create a mock event to pass to the event handler - const mockEvent = { - severity: '', - unhandled: false, - setUser: vi.fn(), - addMetadata: vi.fn(), - } - eventHandler(mockEvent) - capturedEventHandler(mockEvent) - lastBugsnagEvent = mockEvent as any + // A real event, with the breadcrumbs and the metadata that the client merges into each event + const event = RealEvent.create( + reportedError, + true, + {unhandled: false, severity: 'warning', severityReason: {type: 'handledException'}}, + 'notify()', + 0, + ) + event.breadcrumbs = breadcrumbsOfNextBugsnagEvent + Object.entries(clientMetadataOfNextBugsnagEvent).forEach(([section, values]) => { + event.addMetadata(section, values) + }) + vi.spyOn(event, 'setUser') + vi.spyOn(event, 'addMetadata') + eventHandler(event) + capturedEventHandler(event) + lastBugsnagEvent = event callback(null) }, isStarted: () => true, @@ -60,6 +79,8 @@ beforeEach(() => { onNotify.mockClear() capturedEventHandler.mockClear() lastBugsnagEvent = undefined + breadcrumbsOfNextBugsnagEvent = [] + clientMetadataOfNextBugsnagEvent = {} vi.mocked(settings).debug = false vi.mocked(isLocalEnvironment).mockReturnValue(false) vi.mocked(getLastSeenUserIdAfterAuth).mockResolvedValue('test-user-id-123') @@ -217,6 +238,92 @@ describe('sends errors to Bugsnag', () => { expect(onNotify).toHaveBeenCalledWith(res.error) }) + test('redacts Shopify credentials from the reported message and stack', async () => { + const toThrow = new Error('Invalid value "shpat_fake_token" for header "X-Shopify-Access-Token"') + + const res = await sendErrorToBugsnag(toThrow, 'unexpected_error') + + expect(res.reported).toEqual(true) + const {error} = res as any + expect(error.message).toEqual('Invalid value "*****" for header "X-Shopify-Access-Token"') + expect(error.stack).toMatch(/^Error: Invalid value "\*\*\*\*\*" for header "X-Shopify-Access-Token"\n/) + expect(error.stack).not.toContain('shpat_') + expect(onNotify).toHaveBeenCalledWith(error) + }) + + test('redacts Shopify credentials from string errors', async () => { + const res = await sendErrorToBugsnag('Wrong password shptka_fake_password', 'unexpected_error') + + expect(res.reported).toEqual(true) + const {error} = res as any + expect(error.message).toEqual('Wrong password *****') + expect(error.stack).not.toContain('shptka_') + }) + + test('redacts Shopify credentials from the console output in the breadcrumbs', async () => { + breadcrumbsOfNextBugsnagEvent = [ + { + message: 'Console output', + type: 'log', + timestamp: new Date(), + metadata: {severity: 'warn', '[0]': '╭─ error ─╮\n│ Invalid value "shpat_fake_token" for header │'}, + }, + { + message: 'Request sent', + type: 'request', + timestamp: new Date(), + metadata: {request: {headers: {'X-Shopify-Access-Token': 'shpat_fake_token'}}}, + }, + ] + const clientBreadcrumbs = breadcrumbsOfNextBugsnagEvent + + await sendErrorToBugsnag(new Error('Invalid value "shpat_fake_token" for header'), 'unexpected_error') + + expect(lastBugsnagEvent!.breadcrumbs).toEqual([ + expect.objectContaining({ + message: 'Console output', + metadata: {severity: 'warn', '[0]': '╭─ error ─╮\n│ Invalid value "*****" for header │'}, + }), + expect.objectContaining({ + message: 'Request sent', + metadata: {request: {headers: {'X-Shopify-Access-Token': '*****'}}}, + }), + ]) + expect(clientBreadcrumbs[1]!.metadata).toEqual({request: {headers: {'X-Shopify-Access-Token': 'shpat_fake_token'}}}) + }) + + test('builds the grouping hash from the message without its Shopify tokens', async () => { + await metadata.addSensitiveMetadata(() => ({ + commandStartOptions: {startTime: Date.now(), startCommand: 'theme push', startArgs: []}, + })) + + await sendErrorToBugsnag( + new Error('Invalid value "shpat_fake_token_value" for header "X-Shopify-Access-Token"'), + 'unexpected_error', + ) + + expect(lastBugsnagEvent!.groupingHash).toEqual('theme:authentication:invalid-value-for-header-x-shopify-access') + expect(lastBugsnagEvent!.groupingHash).not.toMatch(/shpat|fake|token-value/) + }) + + test('redacts Shopify credentials from the metadata and the error message of the report', async () => { + const pluginMetadata = { + overriddenEnvironmentVariables: [{isSecret: true, key: 'PRIVATE_API_TOKEN', value: 'shpat_fake_token'}], + } + clientMetadataOfNextBugsnagEvent = {config: pluginMetadata} + + await sendErrorToBugsnag(new Error('Request failed with atkn_2.fake-identity_token'), 'unexpected_error') + + expect(lastBugsnagEvent!.errors[0]!.errorMessage).toEqual('Request failed with *****') + expect(lastBugsnagEvent!.getMetadata('config')).toEqual({ + overriddenEnvironmentVariables: [{isSecret: true, key: 'PRIVATE_API_TOKEN', value: '*****'}], + }) + const report = JSON.stringify(lastBugsnagEvent) + expect(report).not.toContain('shpat_') + expect(report).not.toContain('atkn_') + expect(pluginMetadata.overriddenEnvironmentVariables[0]!.value).toEqual('shpat_fake_token') + }) + test('processes string instances', async () => { const res = await sendErrorToBugsnag('In test' as any, 'unexpected_error') expect(res.reported).toEqual(true) @@ -377,3 +484,48 @@ describe('sends errors to Bugsnag', () => { }) }) }) + +describe('registerCleanBugsnagErrorsFromWithinPlugins', () => { + test('redacts Shopify credentials from the events that plugins report on the shared Bugsnag client', async () => { + const config = {runHook: vi.fn().mockResolvedValue({successes: [], failures: []}), plugins: new Map()} + const bugsnagClient = Bugsnag as unknown as {Event: typeof Event; addOnError: (onError: OnErrorCallback) => void} + await registerCleanBugsnagErrorsFromWithinPlugins(config as any) + const onError = vi.mocked(bugsnagClient.addOnError).mock.lastCall![0] + const event = bugsnagClient.Event.create( + new Error('Deploy failed with atkn_fake_identity_token'), + true, + {unhandled: false, severity: 'warning', severityReason: {type: 'handledException'}}, + 'notify()', + 0, + ) + event.addMetadata('config', {overriddenEnvironmentVariables: [{key: 'TOKEN', value: 'shpat_fake_token'}]}) + event.errors[0]!.stacktrace[0]!.code = {'12': "const token = 'shpat_fake_token'"} + + await onError(event, () => {}) + + expect(event.errors[0]!.errorMessage).toEqual('Deploy failed with *****') + expect(event.errors[0]!.stacktrace[0]!.code).toEqual({'12': "const token = '*****'"}) + expect(event.getMetadata('config')).toEqual({overriddenEnvironmentVariables: [{key: 'TOKEN', value: '*****'}]}) + }) + + test('redacts Shopify credentials from the Command section that the CLI adds to the events of plugins', async () => { + await metadata.addPublicMetadata(() => ({cmd_theme_errors: 'Invalid value "shpat_fake_token" for header'})) + const config = {runHook: vi.fn().mockResolvedValue({successes: [], failures: []}), plugins: new Map()} + const bugsnagClient = Bugsnag as unknown as {Event: typeof Event; addOnError: (onError: OnErrorCallback) => void} + await registerCleanBugsnagErrorsFromWithinPlugins(config as any) + const onError = vi.mocked(bugsnagClient.addOnError).mock.lastCall![0] + const event = bugsnagClient.Event.create( + new Error('Theme upload failed'), + true, + {unhandled: false, severity: 'warning', severityReason: {type: 'handledException'}}, + 'notify()', + 0, + ) + + await onError(event, () => {}) + + expect(event.getMetadata('Command')).toEqual( + expect.objectContaining({cmd_theme_errors: 'Invalid value "*****" for header'}), + ) + }) +}) diff --git a/packages/cli-kit/src/public/node/error-handler.ts b/packages/cli-kit/src/public/node/error-handler.ts index 706249ed1d4..eae4bc4af48 100644 --- a/packages/cli-kit/src/public/node/error-handler.ts +++ b/packages/cli-kit/src/public/node/error-handler.ts @@ -13,6 +13,7 @@ import { import {outputDebug, outputInfo} from './output.js' import {getEnvironmentData} from '../../private/node/analytics.js' import {resolveErrorGrouping} from '../../private/node/analytics/error-grouping.js' +import {redactShopifyTokens, redactShopifyTokensInValue} from '../../private/node/analytics/redact.js' import {isLocalEnvironment} from '../../private/node/context/service.js' import {bugsnagApiKey, reportingRateLimit} from '../../private/node/constants.js' import {CLI_KIT_VERSION} from '../common/version.js' @@ -98,7 +99,7 @@ export async function sendErrorToBugsnag( if (error instanceof Error) { report = true - reportableError = new Error(error.message) + reportableError = new Error(redactShopifyTokens(error.message)) stacktrace = error.stack /** @@ -110,7 +111,7 @@ export async function sendErrorToBugsnag( */ } else if (typeof error === 'string' && error.trim().length !== 0) { report = true - reportableError = new Error(error) + reportableError = new Error(redactShopifyTokens(error)) stacktrace = reportableError.stack } else { report = false @@ -124,7 +125,7 @@ export async function sendErrorToBugsnag( return ` at ${item.callee} (${filePath}:${item.line}:${item.column})` }) .join('\n') - reportableError.stack = `Error: ${reportableError.message}\n${formattedStacktrace}` + reportableError.stack = redactShopifyTokens(`Error: ${reportableError.message}\n${formattedStacktrace}`) let withinRateLimit = false await runWithRateLimit({ @@ -178,6 +179,7 @@ export async function sendErrorToBugsnag( error_code: signals.code, error_class: signals.errorClass, }) + redactBugsnagEvent(event) } const errorHandler = (error: unknown) => { if (error) { @@ -199,6 +201,28 @@ export async function sendErrorToBugsnag( } } +/** + * Removes Shopify credentials from the errors, the breadcrumbs and the metadata of a Bugsnag event. + * Each stack frame can carry the source lines around it. Bugsnag records console output as + * breadcrumbs, and the CLI prints an error there before it reports it. Plugins share the CLI's + * Bugsnag client and add their own metadata to it, so the metadata can hold values that the CLI + * never saw. + * + * @param event - The event to redact before Bugsnag sends it. + */ +function redactBugsnagEvent(event: Event): void { + event.errors.forEach((error) => { + error.errorMessage = redactShopifyTokens(error.errorMessage) + error.stacktrace = redactShopifyTokensInValue(error.stacktrace) + }) + // A copy, because the event shares its breadcrumb objects with the client. + event.breadcrumbs = redactShopifyTokensInValue(event.breadcrumbs) + // Bugsnag has no public way to list the metadata sections of an event. The event holds its own copy + // of the sections, so replacing it leaves the client's metadata as it is. + const eventWithMetadata = event as unknown as {_metadata: {[section: string]: unknown}} + eventWithMetadata._metadata = redactShopifyTokensInValue(eventWithMetadata._metadata) +} + /** * If the given file path is within a node_modules folder, remove prefix up * to and including the node_modules folder. @@ -262,6 +286,7 @@ export async function registerCleanBugsnagErrorsFromWithinPlugins(config: Interf } catch (metadataError) { outputDebug(`There was an error adding metadata to the Bugsnag report; Ignoring and carrying on ${metadataError}`) } + redactBugsnagEvent(event) }) }