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/service-account-app-store-lookup.md
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 6 additions & 0 deletions .changeset/theme-password-and-locked-store-errors.md
Original file line number Diff line number Diff line change
@@ -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.
30 changes: 30 additions & 0 deletions packages/cli-kit/src/public/node/api/admin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'))
Expand Down
16 changes: 16 additions & 0 deletions packages/cli-kit/src/public/node/api/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
29 changes: 27 additions & 2 deletions packages/cli-kit/src/public/node/session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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()
})
})
Expand Down
27 changes: 26 additions & 1 deletion packages/cli-kit/src/public/node/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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')
Expand All @@ -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`.
*/
Expand Down
Loading