diff --git a/.changeset/service-account-app-store-lookup.md b/.changeset/service-account-app-store-lookup.md new file mode 100644 index 00000000000..ccf3c5cd64d --- /dev/null +++ b/.changeset/service-account-app-store-lookup.md @@ -0,0 +1,6 @@ +--- +'@shopify/cli-kit': patch +'@shopify/cli': patch +--- + +Fix the HTTP 401 that `app execute`, `app bulk execute` and other app commands that look up a store get with a service account token that has Dev store management access. diff --git a/.changeset/theme-password-and-locked-store-errors.md b/.changeset/theme-password-and-locked-store-errors.md new file mode 100644 index 00000000000..a9c9c1dbc91 --- /dev/null +++ b/.changeset/theme-password-and-locked-store-errors.md @@ -0,0 +1,6 @@ +--- +'@shopify/cli-kit': patch +'@shopify/cli': patch +--- + +Explain theme passwords with characters that can't be sent, and locked or not yet set up stores, instead of reporting an unknown error. diff --git a/packages/cli-kit/src/public/node/api/admin.test.ts b/packages/cli-kit/src/public/node/api/admin.test.ts index d7b240b4323..8faa69cfdb1 100644 --- a/packages/cli-kit/src/public/node/api/admin.test.ts +++ b/packages/cli-kit/src/public/node/api/admin.test.ts @@ -224,6 +224,36 @@ describe('fetchApiVersions error classification', () => { expect((error as AbortError).message).not.toContain('Unknown error') }) + test('reports a 423 locked store as an expected store-state failure, not a CLI bug', async () => { + // Given + vi.mocked(graphqlRequestDoc).mockRejectedValue(clientError(423, 'This store is unavailable')) + + // When + const error = await admin.fetchApiVersions(Session).catch((err: unknown) => err) + + // Then + expect(error).toBeInstanceOf(AbortError) + expect(error).not.toBeInstanceOf(BugError) + expect(shouldReportErrorAsUnexpected(error)).toBe(false) + expect((error as AbortError).message).toBe(`The store ${Session.storeFqdn} is temporarily locked.`) + expect(String((error as AbortError).tryMessage)).toContain('Wait a few minutes and try again.') + }) + + test('reports a 422 Unavailable Shop as an expected store-state failure, not a CLI bug', async () => { + // Given + vi.mocked(graphqlRequestDoc).mockRejectedValue(clientError(422, 'Unavailable Shop')) + + // When + const error = await admin.fetchApiVersions(Session).catch((err: unknown) => err) + + // Then + expect(error).toBeInstanceOf(AbortError) + expect(error).not.toBeInstanceOf(BugError) + expect(shouldReportErrorAsUnexpected(error)).toBe(false) + expect((error as AbortError).message).toBe(`The store ${Session.storeFqdn} can't accept requests yet.`) + expect(String((error as AbortError).tryMessage)).toContain("setup isn't complete") + }) + test('reports an Admin API 5xx as an expected server-side failure, not a CLI bug', async () => { // Given vi.mocked(graphqlRequestDoc).mockRejectedValue(clientError(500, 'Internal Server Error')) diff --git a/packages/cli-kit/src/public/node/api/admin.ts b/packages/cli-kit/src/public/node/api/admin.ts index 7ed3eda69a8..842d98709d3 100644 --- a/packages/cli-kit/src/public/node/api/admin.ts +++ b/packages/cli-kit/src/public/node/api/admin.ts @@ -218,6 +218,22 @@ export async function fetchApiVersions( ) } + // HTTP 423 means Shopify locked the store for a short time. The lock ends without any action from the user. + if (error instanceof ClientError && error.response.status === 423) { + throw new AbortError( + `The store ${session.storeFqdn} is temporarily locked.`, + 'Shopify locks a store for a short time, for example during maintenance. Wait a few minutes and try again.', + ) + } + + // HTTP 422 on this query, which takes no input, comes from the store and not from the request. + if (error instanceof ClientError && error.response.status === 422) { + throw new AbortError( + `The store ${session.storeFqdn} can't accept requests yet.`, + "This usually means the store's setup isn't complete. Finish setting up the store in the Shopify admin and try again.", + ) + } + // HTTP 5xx is a Shopify-side failure. This query takes no user input, so the user's command // cannot have caused it. `isExpectedApiError` covers 502/503/504, but only for raw errors, so // it never sees one we have already wrapped in a BugError. diff --git a/packages/cli-kit/src/public/node/session.test.ts b/packages/cli-kit/src/public/node/session.test.ts index 5aa72a0a4e2..52c46e01ef6 100644 --- a/packages/cli-kit/src/public/node/session.test.ts +++ b/packages/cli-kit/src/public/node/session.test.ts @@ -14,6 +14,7 @@ import { } from './session.js' import {nonRandomUUID} from './crypto.js' +import {AbortError, shouldReportErrorAsUnexpected} from './error.js' import {getAppAutomationToken} from './environment.js' import {shopifyFetch} from './http.js' import { @@ -329,6 +330,30 @@ describe('ensureAuthenticatedTheme', () => { expect(resolvePermanentStoreFqdn).toHaveBeenCalledWith('renamed-store.myshopify.com') expect(got).toEqual({token: 'shptka_password', storeFqdn: 'abc123-xy.myshopify.com'}) }) + + // Synthetic passwords with a line break, an arrow-key escape sequence, the dots that hide a password, and letters + // outside ASCII. An HTTP client refuses each one in a request header. + test.each([ + 'shptka_0000\n0000', + '\u001b[Cshptka_00000000', + '\u2022\u2022\u2022\u2022\u2022\u2022', + 'shptka_\u0160\u0172', + ])('rejects a password with a character that a request header cannot carry (%j)', async (password) => { + // When + const error = await ensureAuthenticatedThemes('mystore.myshopify.com', password).catch((err: unknown) => err) + + // Then + expect(error).toBeInstanceOf(AbortError) + expect(shouldReportErrorAsUnexpected(error)).toBe(false) + expect((error as AbortError).message).toBe( + "The password for mystore.myshopify.com contains a character that isn't allowed.", + ) + const {message, tryMessage, nextSteps} = error as AbortError + expect(`${message} ${tryMessage} ${nextSteps}`).not.toContain(password) + expect(setLastSeenAuthMethod).not.toHaveBeenCalled() + expect(setLastSeenUserIdAfterAuth).not.toHaveBeenCalled() + expect(resolvePermanentStoreFqdn).not.toHaveBeenCalled() + }) }) describe('ensureAuthenticatedBusinessPlatform', () => { @@ -463,8 +488,8 @@ describe('ensureAuthenticatedAppManagementAndBusinessPlatform', () => { userId: '575e2102-cb13-7bea-4631-ce3469eac491cdcba07d', businessPlatformToken: 'business-platform-token', }) - // App commands keep the exchange's default Business Platform scopes. - expect(exchangeAppAutomationTokenForBusinessPlatformAccessToken).toHaveBeenCalledWith('custom_cli_token') + // No fixed scopes, so a service account with Dev store management gets the scope that store lookups need. + expect(exchangeAppAutomationTokenForBusinessPlatformAccessToken).toHaveBeenCalledWith('custom_cli_token', []) expect(ensureAuthenticated).not.toHaveBeenCalled() }) }) diff --git a/packages/cli-kit/src/public/node/session.ts b/packages/cli-kit/src/public/node/session.ts index ef93c864a6e..9134f41dd29 100644 --- a/packages/cli-kit/src/public/node/session.ts +++ b/packages/cli-kit/src/public/node/session.ts @@ -189,7 +189,10 @@ ${outputToken.json(appManagementScopes)} const envToken = getAppAutomationToken() if (envToken) { const appManagmentToken = await exchangeAppAutomationTokenForAppManagementAccessToken(envToken) - const businessPlatformToken = await exchangeAppAutomationTokenForBusinessPlatformAccessToken(envToken) + // Request no explicit scopes, as ensureAuthenticatedBusinessPlatform does. App commands also call the + // organizations API to find and list stores, which admits the token only with an organization scope such as + // organization.store-management. Only some tokens hold it, so naming it would fail the exchange for the others. + const businessPlatformToken = await exchangeAppAutomationTokenForBusinessPlatformAccessToken(envToken, []) return { appManagementToken: appManagmentToken.accessToken, @@ -297,6 +300,7 @@ export async function ensureAuthenticatedThemes( ${outputToken.json(scopes)} `) if (password) { + validateThemePassword(password, store) const session = {token: password, storeFqdn: store} const themeAccess = isThemeAccessSession(session) setLastSeenAuthMethod(themeAccess ? 'theme_access_token' : 'custom_app_token') @@ -307,6 +311,27 @@ ${outputToken.json(scopes)} return ensureAuthenticatedAdmin(store, scopes, options) } +/** + * Rejects a password with a character outside printable ASCII, which no Theme Access password or Admin API token has. + * The password goes into a request header. The HTTP client refuses most of these characters before the request leaves + * the machine, with an error that repeats the password, and the store rejects the rest. + * + * @param password - Password generated from the Theme Access app, or an Admin API access token. + * @param store - Store the password is for. + * @throws AbortError when the password has a character outside printable ASCII. + */ +function validateThemePassword(password: string, store: string): void { + if (/^[\x20-\x7E]*$/.test(password)) return + + throw new AbortError( + `The password for ${store} contains a character that isn't allowed.`, + 'A password can contain only printable ASCII characters. Line breaks, arrow-key presses, and the dots that hide a password often get into a password when it is copied.', + [ + 'Copy the password again from the Theme Access app, or the Admin API access token again from your app, and run the command again.', + ], + ) +} + /** * Options for `ensureAuthenticatedBusinessPlatform`. */