Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/redact-shopify-tokens-error-reports.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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)', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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.
Expand Down
94 changes: 94 additions & 0 deletions packages/cli-kit/src/private/node/analytics/redact.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
37 changes: 37 additions & 0 deletions packages/cli-kit/src/private/node/analytics/redact.ts
Original file line number Diff line number Diff line change
@@ -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<T>(value: T): T {
return cloneDeepWith(value, (item: unknown) =>
typeof item === 'string' ? redactShopifyTokens(item) : undefined,
) as T
}
29 changes: 29 additions & 0 deletions packages/cli-kit/src/public/node/analytics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'}
Expand Down
4 changes: 2 additions & 2 deletions packages/cli-kit/src/public/node/analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -272,8 +273,7 @@ function sanitizePayload<T>(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*****')
Expand Down
Loading
Loading