diff --git a/.changeset/app-client-secret-on-demand.md b/.changeset/app-client-secret-on-demand.md new file mode 100644 index 00000000000..13778c3b880 --- /dev/null +++ b/.changeset/app-client-secret-on-demand.md @@ -0,0 +1,6 @@ +--- +'@shopify/app': patch +'@shopify/cli': patch +--- + +Improve error messages and guidance for app commands. diff --git a/packages/app/src/cli/api/graphql/app-management/generated/active-app-release-from-api-key.ts b/packages/app/src/cli/api/graphql/app-management/generated/active-app-release-from-api-key.ts index 2ba6adaaa6e..395f856f185 100644 --- a/packages/app/src/cli/api/graphql/app-management/generated/active-app-release-from-api-key.ts +++ b/packages/app/src/cli/api/graphql/app-management/generated/active-app-release-from-api-key.ts @@ -13,7 +13,7 @@ export type ActiveAppReleaseFromApiKeyQuery = { id: string key: string organizationId: string - activeRoot: {grantedShopifyApprovalScopes: string[]; clientCredentials: {secrets: {key: string}[]}} + activeRoot: {grantedShopifyApprovalScopes: string[]} activeRelease: { id: string version: { @@ -120,26 +120,7 @@ export const ActiveAppReleaseFromApiKey = { name: {kind: 'Name', value: 'activeRoot'}, selectionSet: { kind: 'SelectionSet', - selections: [ - { - kind: 'Field', - name: {kind: 'Name', value: 'clientCredentials'}, - selectionSet: { - kind: 'SelectionSet', - selections: [ - { - kind: 'Field', - name: {kind: 'Name', value: 'secrets'}, - selectionSet: { - kind: 'SelectionSet', - selections: [{kind: 'Field', name: {kind: 'Name', value: 'key'}}], - }, - }, - ], - }, - }, - {kind: 'Field', name: {kind: 'Name', value: 'grantedShopifyApprovalScopes'}}, - ], + selections: [{kind: 'Field', name: {kind: 'Name', value: 'grantedShopifyApprovalScopes'}}], }, }, { diff --git a/packages/app/src/cli/api/graphql/app-management/generated/active-app-release.ts b/packages/app/src/cli/api/graphql/app-management/generated/active-app-release.ts index f4c874b90ab..14d03ce9933 100644 --- a/packages/app/src/cli/api/graphql/app-management/generated/active-app-release.ts +++ b/packages/app/src/cli/api/graphql/app-management/generated/active-app-release.ts @@ -13,7 +13,7 @@ export type ActiveAppReleaseQuery = { id: string key: string organizationId: string - activeRoot: {grantedShopifyApprovalScopes: string[]; clientCredentials: {secrets: {key: string}[]}} + activeRoot: {grantedShopifyApprovalScopes: string[]} activeRelease: { id: string version: { @@ -41,7 +41,7 @@ export type AppVersionInfoFragment = { id: string key: string organizationId: string - activeRoot: {grantedShopifyApprovalScopes: string[]; clientCredentials: {secrets: {key: string}[]}} + activeRoot: {grantedShopifyApprovalScopes: string[]} activeRelease: { id: string version: { @@ -131,26 +131,7 @@ export const AppVersionInfoFragmentDoc = { name: {kind: 'Name', value: 'activeRoot'}, selectionSet: { kind: 'SelectionSet', - selections: [ - { - kind: 'Field', - name: {kind: 'Name', value: 'clientCredentials'}, - selectionSet: { - kind: 'SelectionSet', - selections: [ - { - kind: 'Field', - name: {kind: 'Name', value: 'secrets'}, - selectionSet: { - kind: 'SelectionSet', - selections: [{kind: 'Field', name: {kind: 'Name', value: 'key'}}], - }, - }, - ], - }, - }, - {kind: 'Field', name: {kind: 'Name', value: 'grantedShopifyApprovalScopes'}}, - ], + selections: [{kind: 'Field', name: {kind: 'Name', value: 'grantedShopifyApprovalScopes'}}], }, }, { @@ -297,26 +278,7 @@ export const ActiveAppRelease = { name: {kind: 'Name', value: 'activeRoot'}, selectionSet: { kind: 'SelectionSet', - selections: [ - { - kind: 'Field', - name: {kind: 'Name', value: 'clientCredentials'}, - selectionSet: { - kind: 'SelectionSet', - selections: [ - { - kind: 'Field', - name: {kind: 'Name', value: 'secrets'}, - selectionSet: { - kind: 'SelectionSet', - selections: [{kind: 'Field', name: {kind: 'Name', value: 'key'}}], - }, - }, - ], - }, - }, - {kind: 'Field', name: {kind: 'Name', value: 'grantedShopifyApprovalScopes'}}, - ], + selections: [{kind: 'Field', name: {kind: 'Name', value: 'grantedShopifyApprovalScopes'}}], }, }, { diff --git a/packages/app/src/cli/api/graphql/app-management/generated/app-client-credentials.ts b/packages/app/src/cli/api/graphql/app-management/generated/app-client-credentials.ts new file mode 100644 index 00000000000..af91b4a2696 --- /dev/null +++ b/packages/app/src/cli/api/graphql/app-management/generated/app-client-credentials.ts @@ -0,0 +1,85 @@ +/* eslint-disable @typescript-eslint/consistent-type-definitions */ +import * as Types from './types.js' + +import {TypedDocumentNode as DocumentNode} from '@graphql-typed-document-node/core' + +export type AppClientCredentialsQueryVariables = Types.Exact<{ + apiKey: Types.Scalars['String']['input'] +}> + +export type AppClientCredentialsQuery = { + app: {id: string; activeRoot: {clientCredentials: {secrets: {key: string}[]}}} +} + +export const AppClientCredentials = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'query', + name: {kind: 'Name', value: 'AppClientCredentials'}, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: {kind: 'Variable', name: {kind: 'Name', value: 'apiKey'}}, + type: {kind: 'NonNullType', type: {kind: 'NamedType', name: {kind: 'Name', value: 'String'}}}, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + alias: {kind: 'Name', value: 'app'}, + name: {kind: 'Name', value: 'appByKey'}, + arguments: [ + { + kind: 'Argument', + name: {kind: 'Name', value: 'key'}, + value: {kind: 'Variable', name: {kind: 'Name', value: 'apiKey'}}, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + {kind: 'Field', name: {kind: 'Name', value: 'id'}}, + { + kind: 'Field', + name: {kind: 'Name', value: 'activeRoot'}, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: {kind: 'Name', value: 'clientCredentials'}, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: {kind: 'Name', value: 'secrets'}, + selectionSet: { + kind: 'SelectionSet', + selections: [ + {kind: 'Field', name: {kind: 'Name', value: 'key'}}, + {kind: 'Field', name: {kind: 'Name', value: '__typename'}}, + ], + }, + }, + {kind: 'Field', name: {kind: 'Name', value: '__typename'}}, + ], + }, + }, + {kind: 'Field', name: {kind: 'Name', value: '__typename'}}, + ], + }, + }, + {kind: 'Field', name: {kind: 'Name', value: '__typename'}}, + ], + }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode diff --git a/packages/app/src/cli/api/graphql/app-management/generated/create-app.ts b/packages/app/src/cli/api/graphql/app-management/generated/create-app.ts index 1c409ba36fc..57e54acf657 100644 --- a/packages/app/src/cli/api/graphql/app-management/generated/create-app.ts +++ b/packages/app/src/cli/api/graphql/app-management/generated/create-app.ts @@ -11,7 +11,7 @@ export type CreateAppMutationVariables = Types.Exact<{ export type CreateAppMutation = { appCreate: { - app?: {id: string; key: string; activeRoot: {clientCredentials: {secrets: {key: string}[]}}} | null + app?: {id: string; key: string} | null userErrors: {category: string; message: string; on: JsonMapType}[] } } @@ -64,37 +64,6 @@ export const CreateApp = { selections: [ {kind: 'Field', name: {kind: 'Name', value: 'id'}}, {kind: 'Field', name: {kind: 'Name', value: 'key'}}, - { - kind: 'Field', - name: {kind: 'Name', value: 'activeRoot'}, - selectionSet: { - kind: 'SelectionSet', - selections: [ - { - kind: 'Field', - name: {kind: 'Name', value: 'clientCredentials'}, - selectionSet: { - kind: 'SelectionSet', - selections: [ - { - kind: 'Field', - name: {kind: 'Name', value: 'secrets'}, - selectionSet: { - kind: 'SelectionSet', - selections: [ - {kind: 'Field', name: {kind: 'Name', value: 'key'}}, - {kind: 'Field', name: {kind: 'Name', value: '__typename'}}, - ], - }, - }, - {kind: 'Field', name: {kind: 'Name', value: '__typename'}}, - ], - }, - }, - {kind: 'Field', name: {kind: 'Name', value: '__typename'}}, - ], - }, - }, {kind: 'Field', name: {kind: 'Name', value: '__typename'}}, ], }, diff --git a/packages/app/src/cli/api/graphql/app-management/queries/active-app-release.graphql b/packages/app/src/cli/api/graphql/app-management/queries/active-app-release.graphql index 4bf5b82d8d9..2fafbd4e06d 100644 --- a/packages/app/src/cli/api/graphql/app-management/queries/active-app-release.graphql +++ b/packages/app/src/cli/api/graphql/app-management/queries/active-app-release.graphql @@ -9,11 +9,6 @@ fragment AppVersionInfo on App { key organizationId activeRoot { - clientCredentials { - secrets { - key - } - } grantedShopifyApprovalScopes } activeRelease { diff --git a/packages/app/src/cli/api/graphql/app-management/queries/app-client-credentials.graphql b/packages/app/src/cli/api/graphql/app-management/queries/app-client-credentials.graphql new file mode 100644 index 00000000000..c5edc0e9962 --- /dev/null +++ b/packages/app/src/cli/api/graphql/app-management/queries/app-client-credentials.graphql @@ -0,0 +1,12 @@ +query AppClientCredentials($apiKey: String!) { + app: appByKey(key: $apiKey) { + id + activeRoot { + clientCredentials { + secrets { + key + } + } + } + } +} diff --git a/packages/app/src/cli/api/graphql/app-management/queries/create-app.graphql b/packages/app/src/cli/api/graphql/app-management/queries/create-app.graphql index 26bcd737f27..c529781aa93 100644 --- a/packages/app/src/cli/api/graphql/app-management/queries/create-app.graphql +++ b/packages/app/src/cli/api/graphql/app-management/queries/create-app.graphql @@ -3,13 +3,6 @@ mutation CreateApp($initialVersion: AppVersionInput!, $organizationId: ID!) { app { id key - activeRoot { - clientCredentials { - secrets { - key - } - } - } } userErrors { category diff --git a/packages/app/src/cli/commands/app/info.test.ts b/packages/app/src/cli/commands/app/info.test.ts index 58e008f3f5c..d873dc83025 100644 --- a/packages/app/src/cli/commands/app/info.test.ts +++ b/packages/app/src/cli/commands/app/info.test.ts @@ -2,6 +2,7 @@ import AppInfo from './info.js' import { testAppLinked, testOrganizationApp, + testOrganizationAppWithoutClientSecret, testProject, testDeveloperPlatformClient, } from '../../models/app/app.test-data.js' @@ -95,7 +96,9 @@ test('keeps app information on stderr in text mode', async () => { test.each([{secret: 'api-secret'}, {secret: undefined}])( 'preserves web environment JSON: $secret', async ({secret}) => { - const remoteApp = testOrganizationApp({apiSecretKeys: secret === undefined ? [] : [{secret}]}) + const remoteApp = secret + ? testOrganizationApp({apiSecretKeys: [{secret}]}) + : testOrganizationAppWithoutClientSecret() await withCapturedStandardStreams(async ({stdout, stderr}) => { await runCommand(['--web-env', '--json'], testAppLinked(), remoteApp) expect(stdout()).toBe( @@ -103,18 +106,22 @@ test.each([{secret: 'api-secret'}, {secret: undefined}])( ? '{\n "SHOPIFY_API_KEY": "api-key",\n "SCOPES": "read_products"\n}\n' : '{\n "SHOPIFY_API_KEY": "api-key",\n "SHOPIFY_API_SECRET": "api-secret",\n "SCOPES": "read_products"\n}\n', ) - expect(stderr()).toBe('') + if (secret === undefined) { + expect(stderr()).toContain("SHOPIFY_API_SECRET isn't included") + } else { + expect(stderr()).toBe('') + } }) }, ) test('keeps web environment text on stdout, with an empty missing secret', async () => { await withCapturedStandardStreams(async ({stdout, stderr}) => { - await runCommand(['--web-env'], testAppLinked(), testOrganizationApp({apiSecretKeys: []})) + await runCommand(['--web-env'], testAppLinked(), testOrganizationAppWithoutClientSecret()) expect(unstyled(stdout())).toBe( '\n SHOPIFY_API_KEY=api-key\n SHOPIFY_API_SECRET=\n SCOPES=read_products\n \n', ) - expect(stderr()).toBe('') + expect(stderr()).toContain("SHOPIFY_API_SECRET isn't included") }) }) diff --git a/packages/app/src/cli/models/app/app.test-data.ts b/packages/app/src/cli/models/app/app.test-data.ts index a2efc77064e..df3f1543f26 100644 --- a/packages/app/src/cli/models/app/app.test-data.ts +++ b/packages/app/src/cli/models/app/app.test-data.ts @@ -196,7 +196,8 @@ export function testOrganizationApp(app: Partial = {}): Organiz id: '1', title: 'app1', apiKey: 'api-key', - apiSecretKeys: [{secret: 'api-secret'}], + // As in production: app lookups leave the secret out, and commands fetch it with appClientSecrets. + apiSecretKeys: [], organizationId: '1', grantedScopes: [], disabledFlags: ['5b25141b'], @@ -206,6 +207,17 @@ export function testOrganizationApp(app: Partial = {}): Organiz return {...defaultApp, ...app} } +/** + * An app whose client secret the App Management API doesn't return, as for credentials that can't read it. + */ +export function testOrganizationAppWithoutClientSecret(app: Partial = {}): OrganizationApp { + return testOrganizationApp({ + apiSecretKeys: [], + developerPlatformClient: testDeveloperPlatformClient({appClientSecrets: () => Promise.resolve([])}), + ...app, + }) +} + export const placeholderAppConfiguration: AppConfiguration = { client_id: '', } @@ -1340,6 +1352,7 @@ export function testDeveloperPlatformClient( unsafeRefreshToken: () => Promise.resolve(testPartnersUserSession.token), accountInfo: () => Promise.resolve(testPartnersUserSession.accountInfo), appFromIdentifiers: (_apiKey: string) => Promise.resolve(testOrganizationApp()), + appClientSecrets: (_app: Pick) => Promise.resolve([{secret: 'api-secret'}]), organizations: () => Promise.resolve(organizationsResponse), orgFromId: (_organizationId: string) => Promise.resolve(testOrganization()), appsForOrg: (_organizationId: string) => Promise.resolve({apps: [testOrganizationApp()], hasMorePages: false}), diff --git a/packages/app/src/cli/models/organization.test.ts b/packages/app/src/cli/models/organization.test.ts new file mode 100644 index 00000000000..6372c97bc3c --- /dev/null +++ b/packages/app/src/cli/models/organization.test.ts @@ -0,0 +1,136 @@ +import {appClientSecret, fetchAppClientSecret, missingClientSecretTryMessage} from './organization.js' +import {testDeveloperPlatformClient, testOrganizationApp} from './app/app.test-data.js' +import {afterEach, describe, expect, test, vi} from 'vitest' +import {AbortError} from '@shopify/cli-kit/node/error' + +function appWithRemoteSecrets(secrets: {secret: string}[]) { + const appClientSecrets = vi.fn().mockResolvedValue(secrets) + const remoteApp = testOrganizationApp({ + apiKey: 'api-key', + apiSecretKeys: [], + developerPlatformClient: testDeveloperPlatformClient({appClientSecrets}), + }) + return {remoteApp, appClientSecrets} +} + +describe('fetchAppClientSecret', () => { + test('returns an already loaded secret without asking the App Management API', async () => { + // Given + const appClientSecrets = vi.fn() + const remoteApp = testOrganizationApp({ + apiSecretKeys: [{secret: ''}, {secret: 'secret-1'}], + developerPlatformClient: testDeveloperPlatformClient({appClientSecrets}), + }) + + // When + const secret = await fetchAppClientSecret(remoteApp) + + // Then + expect(secret).toEqual('secret-1') + expect(appClientSecrets).not.toHaveBeenCalled() + }) + + test('asks the App Management API for the secret when it is not loaded', async () => { + // Given + const {remoteApp, appClientSecrets} = appWithRemoteSecrets([{secret: 'secret-1'}, {secret: 'secret-2'}]) + + // When + const secret = await fetchAppClientSecret(remoteApp) + + // Then + expect(secret).toEqual('secret-1') + expect(appClientSecrets).toHaveBeenCalledWith(remoteApp) + }) + + test('returns undefined when the App Management API returns no secrets', async () => { + // Given + const {remoteApp} = appWithRemoteSecrets([]) + + // When / Then + await expect(fetchAppClientSecret(remoteApp)).resolves.toBeUndefined() + }) +}) + +describe('appClientSecret', () => { + afterEach(() => { + vi.unstubAllEnvs() + }) + + test('returns the secret the App Management API returns to an automation token', async () => { + // Given + vi.stubEnv('SHOPIFY_SERVICE_ACCOUNT_TOKEN', 'automation-token') + const {remoteApp} = appWithRemoteSecrets([{secret: 'secret-1'}]) + + // When / Then + await expect(appClientSecret(remoteApp)).resolves.toEqual('secret-1') + }) + + test('throws an AbortError when a logged-in user gets no secret', async () => { + // Given + const {remoteApp} = appWithRemoteSecrets([]) + + // When / Then + await expect(appClientSecret(remoteApp)).rejects.toThrow(AbortError) + await expect(appClientSecret(remoteApp)).rejects.toMatchObject({ + message: expect.stringContaining("didn't return one for your credentials"), + tryMessage: expect.stringContaining('Developer Dashboard'), + }) + }) + + test('suggests logging in when an automation token gets no secret', async () => { + // Given + vi.stubEnv('SHOPIFY_SERVICE_ACCOUNT_TOKEN', 'automation-token') + const {remoteApp} = appWithRemoteSecrets([]) + + // When / Then + await expect(appClientSecret(remoteApp)).rejects.toMatchObject({ + tryMessage: expect.stringContaining('shopify auth login'), + }) + }) + + test.each(['SHOPIFY_SERVICE_ACCOUNT_TOKEN', 'SHOPIFY_APP_AUTOMATION_TOKEN', 'SHOPIFY_CLI_PARTNERS_TOKEN'])( + 'tells the user to unset %s before logging in, without showing its value', + async (variable) => { + // Given + vi.stubEnv(variable, 'automation-token-value') + + // When + const message = missingClientSecretTryMessage() + + // Then + expect(message).toContain(`The token in ${variable} might not have access to the app's client secret.`) + expect(message).toContain(`unset ${variable}, log in with \`shopify auth login\`, and run the command again`) + expect(message).not.toContain('automation-token-value') + }, + ) + + test('names every automation token variable that is set', async () => { + // Given + vi.stubEnv('SHOPIFY_SERVICE_ACCOUNT_TOKEN', 'token-1') + vi.stubEnv('SHOPIFY_CLI_PARTNERS_TOKEN', 'token-2') + + // When + const message = missingClientSecretTryMessage() + + // Then + expect(message).toContain('unset SHOPIFY_SERVICE_ACCOUNT_TOKEN and SHOPIFY_CLI_PARTNERS_TOKEN,') + }) + + test('links a logged-in user to the Developer Dashboard', () => { + // When + const message = missingClientSecretTryMessage() + + // Then + expect(message).toContain('Developer Dashboard: https://dev.shopify.com') + }) + + test('uses the command-specific way to provide the secret', async () => { + // Given + const {remoteApp} = appWithRemoteSecrets([]) + + // When / Then + await expect(appClientSecret(remoteApp, 'Pass the secret with a flag.')).rejects.toMatchObject({ + tryMessage: 'Pass the secret with a flag.', + }) + }) +}) diff --git a/packages/app/src/cli/models/organization.ts b/packages/app/src/cli/models/organization.ts index 5f5b2172243..06219b7df01 100644 --- a/packages/app/src/cli/models/organization.ts +++ b/packages/app/src/cli/models/organization.ts @@ -4,6 +4,9 @@ import { Organization as BaseOrganization, type OrganizationWithDetails as BaseOrganizationWithDetails, } from '@shopify/organizations' +import {getEnvironmentVariables} from '@shopify/cli-kit/node/environment' +import {AbortError} from '@shopify/cli-kit/node/error' +import {outputWarn} from '@shopify/cli-kit/node/output' export enum OrganizationSource { Partners = 'Partners', @@ -60,6 +63,80 @@ export type OrganizationApp = MinimalOrganizationApp & { developerPlatformClient: DeveloperPlatformClient } +type AppWithClientSecrets = Pick + +const developerDashboardUrl = 'https://dev.shopify.com' + +const automationTokenVariables = [ + 'SHOPIFY_SERVICE_ACCOUNT_TOKEN', + 'SHOPIFY_APP_AUTOMATION_TOKEN', + 'SHOPIFY_CLI_PARTNERS_TOKEN', +] + +/** + * Fetches the app's client secret for commands that authenticate as the app. + * + * App lookups don't include the secret, so this asks the App Management API for it, which decides whether the current + * credentials may read it. + * + * @param remoteApp - The app whose secret to fetch. + * @returns The first client secret, or undefined when the App Management API returns none. + */ +export async function fetchAppClientSecret(remoteApp: AppWithClientSecrets): Promise { + const loadedSecret = firstClientSecret(remoteApp.apiSecretKeys) + if (loadedSecret) return loadedSecret + + return firstClientSecret(await remoteApp.developerPlatformClient.appClientSecrets(remoteApp)) +} + +/** + * Fetches the app's client secret, and fails with an actionable error when the App Management API returns none. + * + * @param remoteApp - The app whose secret to fetch. + * @param tryMessage - What the user can do instead, when there's a way to provide the secret directly. + * @returns The first client secret of the app. + */ +export async function appClientSecret(remoteApp: AppWithClientSecrets, tryMessage?: string): Promise { + const secret = await fetchAppClientSecret(remoteApp) + if (secret) return secret + + throw new AbortError( + "This command needs the app's client secret, and the App Management API didn't return one for your credentials.", + tryMessage ?? missingClientSecretTryMessage(), + ) +} + +/** + * Explains why the client secret may be missing and what to do, for errors and warnings. + * + * The CLI keeps using an automation token while its variable is set, even after `shopify auth login`, so the message + * names the variables to unset. It never reads or shows their values. + * + * @returns The explanation. + */ +export function missingClientSecretTryMessage(): string { + const environment = getEnvironmentVariables() + const setTokenVariables = automationTokenVariables.filter((name) => environment[name] !== undefined) + if (setTokenVariables.length > 0) { + return `The token in ${setTokenVariables[0]} might not have access to the app's client secret. To use your own account, unset ${setTokenVariables.join(' and ')}, log in with \`shopify auth login\`, and run the command again.` + } + + return `Check that your account can view the app's client credentials in the Developer Dashboard: ${developerDashboardUrl}` +} + +/** + * Warns that a command's output leaves out SHOPIFY_API_SECRET. In JSON mode the warning is a diagnostic event. + */ +export function warnClientSecretOmitted(): void { + outputWarn( + `SHOPIFY_API_SECRET isn't included because the App Management API didn't return the app's client secret for your credentials. ${missingClientSecretTryMessage()}`, + ) +} + +function firstClientSecret(apiSecretKeys: OrganizationApp['apiSecretKeys']): string | undefined { + return apiSecretKeys.find((key) => key.secret)?.secret +} + export interface OrganizationStore { shopId: string link: string diff --git a/packages/app/src/cli/services/app/env/pull.test.ts b/packages/app/src/cli/services/app/env/pull.test.ts index c8fd46e2488..9cc42702435 100644 --- a/packages/app/src/cli/services/app/env/pull.test.ts +++ b/packages/app/src/cli/services/app/env/pull.test.ts @@ -1,11 +1,16 @@ import {pullEnv} from './pull.js' import {AppInterface, AppLinkedInterface} from '../../../models/app/app.js' -import {testApp, testOrganizationApp} from '../../../models/app/app.test-data.js' +import { + testApp, + testOrganizationApp, + testOrganizationAppWithoutClientSecret, +} from '../../../models/app/app.test-data.js' import {Organization, OrganizationApp, OrganizationSource} from '../../../models/organization.js' import {describe, expect, vi, beforeEach, test} from 'vitest' import * as file from '@shopify/cli-kit/node/fs' import {resolvePath} from '@shopify/cli-kit/node/path' import {unstyled, stringifyMessage} from '@shopify/cli-kit/node/output' +import {mockAndCaptureOutput} from '@shopify/cli-kit/node/testing/output' const ORG1: Organization = { id: '1', @@ -98,6 +103,25 @@ describe('env pull', () => { `) }) }) + + test('keeps custom variables, comments, and the local secret when the App Management API returns no secret', async () => { + await file.inTemporaryDirectory(async (tmpDir: string) => { + // Given + const output = mockAndCaptureOutput() + const filePath = resolvePath(tmpDir, '.env') + file.writeFileSync(filePath, '# Local settings\nCUSTOM=value\nSHOPIFY_API_SECRET=existing-secret') + + // When + await pullEnv({app, remoteApp: testOrganizationAppWithoutClientSecret(), organization: ORG1, envFile: filePath}) + + // Then + await expect(file.readFile(filePath)).resolves.toBe( + '# Local settings\nCUSTOM=value\nSHOPIFY_API_SECRET=existing-secret\nSHOPIFY_API_KEY=api-key\nSCOPES=my-scope', + ) + expect(output.warn()).toContain("SHOPIFY_API_SECRET isn't included") + output.clear() + }) + }) }) function mockApp(): AppInterface { diff --git a/packages/app/src/cli/services/app/env/pull.ts b/packages/app/src/cli/services/app/env/pull.ts index 422749dd02e..036571cd8e6 100644 --- a/packages/app/src/cli/services/app/env/pull.ts +++ b/packages/app/src/cli/services/app/env/pull.ts @@ -2,7 +2,12 @@ import {AppLinkedInterface, getAppScopes} from '../../../models/app/app.js' import {logMetadataForLoadedContext} from '../../context.js' -import {Organization, OrganizationApp} from '../../../models/organization.js' +import { + Organization, + OrganizationApp, + fetchAppClientSecret, + warnClientSecretOmitted, +} from '../../../models/organization.js' import {patchEnvFile} from '@shopify/cli-kit/node/dot-env' import {diffLines} from 'diff' import {fileExists, readFile, writeFile} from '@shopify/cli-kit/node/fs' @@ -17,10 +22,13 @@ interface PullEnvOptions { export async function pullEnv({app, remoteApp, organization, envFile}: PullEnvOptions): Promise { await logMetadataForLoadedContext(remoteApp, organization.source) + const apiSecret = await fetchAppClientSecret(remoteApp) + if (!apiSecret) warnClientSecretOmitted() const updatedValues = { SHOPIFY_API_KEY: remoteApp.apiKey, - SHOPIFY_API_SECRET: remoteApp.apiSecretKeys[0]?.secret, + // Without a secret, the file keeps its current value, so pulling never blanks a local secret. + ...(apiSecret ? {SHOPIFY_API_SECRET: apiSecret} : {}), SCOPES: getAppScopes(app.configuration), } diff --git a/packages/app/src/cli/services/app/env/show.test.ts b/packages/app/src/cli/services/app/env/show.test.ts index 229d583cf54..8b5ba79bcb4 100644 --- a/packages/app/src/cli/services/app/env/show.test.ts +++ b/packages/app/src/cli/services/app/env/show.test.ts @@ -1,17 +1,25 @@ import {showEnv} from './show.js' import {fetchOrganizations} from '../../dev/fetch.js' import {AppInterface} from '../../../models/app/app.js' -import {testApp, testOrganizationApp} from '../../../models/app/app.test-data.js' -import {OrganizationSource} from '../../../models/organization.js' +import { + testApp, + testOrganizationApp, + testOrganizationAppWithoutClientSecret, + testDeveloperPlatformClient, +} from '../../../models/app/app.test-data.js' +import {Organization, OrganizationSource} from '../../../models/organization.js' import {selectOrganizationPrompt} from '@shopify/organizations' import {describe, expect, vi, test} from 'vitest' import * as file from '@shopify/cli-kit/node/fs' import {stringifyMessage, unstyled} from '@shopify/cli-kit/node/output' +import {mockAndCaptureOutput} from '@shopify/cli-kit/node/testing/output' vi.mock('../../dev/fetch.js') vi.mock('@shopify/organizations') vi.mock('@shopify/cli-kit/node/node-package-manager') +const ORGANIZATION: Organization = {id: '123', businessName: 'test', source: OrganizationSource.BusinessPlatform} + describe('env show', () => { test('outputs the new environment', async () => { // Given @@ -46,6 +54,41 @@ describe('env show', () => { " `) }) + + test('fetches the client secret when the app lookup did not include it', async () => { + // Given + const appClientSecrets = vi.fn().mockResolvedValue([{secret: 'fetched-secret'}]) + const remoteApp = testOrganizationApp({ + apiSecretKeys: [], + developerPlatformClient: testDeveloperPlatformClient({appClientSecrets}), + }) + + // When + const result = await showEnv(mockApp(), remoteApp, ORGANIZATION) + + // Then + expect(appClientSecrets).toHaveBeenCalledWith(remoteApp) + expect(unstyled(stringifyMessage(result))).toContain('SHOPIFY_API_SECRET=fetched-secret') + }) + + test('shows an empty SHOPIFY_API_SECRET and warns when the App Management API returns no secret', async () => { + // Given + const output = mockAndCaptureOutput() + + // When + const result = await showEnv(mockApp(), testOrganizationAppWithoutClientSecret(), ORGANIZATION) + + // Then + expect(unstyled(stringifyMessage(result))).toMatchInlineSnapshot(` + " + SHOPIFY_API_KEY=api-key + SHOPIFY_API_SECRET= + SCOPES=my-scope + " + `) + expect(output.warn()).toContain("SHOPIFY_API_SECRET isn't included") + output.clear() + }) }) function mockApp(): AppInterface { diff --git a/packages/app/src/cli/services/app/env/show.ts b/packages/app/src/cli/services/app/env/show.ts index 58fa8c4125e..42e4cb28c70 100644 --- a/packages/app/src/cli/services/app/env/show.ts +++ b/packages/app/src/cli/services/app/env/show.ts @@ -1,5 +1,10 @@ import {AppInterface, getAppScopes} from '../../../models/app/app.js' -import {Organization, OrganizationApp} from '../../../models/organization.js' +import { + Organization, + OrganizationApp, + fetchAppClientSecret, + warnClientSecretOmitted, +} from '../../../models/organization.js' import {logMetadataForLoadedContext} from '../../context.js' import {OutputMessage, outputContent, outputToken} from '@shopify/cli-kit/node/output' @@ -20,17 +25,19 @@ async function outputEnv( format: Format, ): Promise { await logMetadataForLoadedContext(remoteApp, organization.source) + const apiSecret = await fetchAppClientSecret(remoteApp) + if (!apiSecret) warnClientSecretOmitted() if (format === 'json') { return outputContent`${outputToken.json({ SHOPIFY_API_KEY: remoteApp.apiKey, - SHOPIFY_API_SECRET: remoteApp.apiSecretKeys[0]?.secret, + SHOPIFY_API_SECRET: apiSecret, SCOPES: getAppScopes(app.configuration), })}` } else { return outputContent` ${outputToken.green('SHOPIFY_API_KEY')}=${remoteApp.apiKey} - ${outputToken.green('SHOPIFY_API_SECRET')}=${remoteApp.apiSecretKeys[0]?.secret ?? ''} + ${outputToken.green('SHOPIFY_API_SECRET')}=${apiSecret ?? ''} ${outputToken.green('SCOPES')}=${getAppScopes(app.configuration)} ` } diff --git a/packages/app/src/cli/services/app/graphiql.test.ts b/packages/app/src/cli/services/app/graphiql.test.ts index 0458579af07..0d5e6a177e4 100644 --- a/packages/app/src/cli/services/app/graphiql.test.ts +++ b/packages/app/src/cli/services/app/graphiql.test.ts @@ -1,11 +1,12 @@ import {openAppGraphiQL} from './graphiql.js' import {createClientCredentialsTokenProvider} from '../dev/processes/graphiql-token-provider.js' -import {testOrganizationApp} from '../../models/app/app.test-data.js' +import {testOrganizationApp, testOrganizationAppWithoutClientSecret} from '../../models/app/app.test-data.js' import {AbortController} from '@shopify/cli-kit/node/abort' import {resolveGraphiQLKey} from '@shopify/cli-kit/node/graphiql/server' import {runGraphiQLSession} from '@shopify/cli-kit/node/graphiql/session' import {adminFqdn} from '@shopify/cli-kit/node/context/fqdn' -import {beforeEach, describe, expect, test, vi} from 'vitest' +import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest' +import {AbortError} from '@shopify/cli-kit/node/error' vi.mock('../dev/processes/graphiql-token-provider.js') vi.mock('@shopify/cli-kit/node/graphiql/session') @@ -30,6 +31,10 @@ describe('openAppGraphiQL', () => { }) }) + afterEach(() => { + vi.unstubAllEnvs() + }) + test('starts GraphiQL with app context and a client credentials token provider', async () => { const abortSignal = new AbortController().signal const remoteApp = testOrganizationApp({apiKey: 'api-key', title: 'Test App', apiSecretKeys: [{secret: 'secret'}]}) @@ -63,6 +68,16 @@ describe('openAppGraphiQL', () => { ) }) + test("doesn't start GraphiQL when the App Management API returns no client secret", async () => { + vi.stubEnv('SHOPIFY_SERVICE_ACCOUNT_TOKEN', 'automation-token') + const remoteApp = testOrganizationAppWithoutClientSecret() + + await expect(openAppGraphiQL({remoteApp, store: 'shop.myshopify.com'})).rejects.toThrow(AbortError) + + expect(mockedCreateTokenProvider).not.toHaveBeenCalled() + expect(mockedRunGraphiQLSession).not.toHaveBeenCalled() + }) + test('passes optional GraphiQL URL parameters to the shared session runner', async () => { const remoteApp = testOrganizationApp({apiSecretKeys: [{secret: 'secret'}]}) diff --git a/packages/app/src/cli/services/app/graphiql.ts b/packages/app/src/cli/services/app/graphiql.ts index 9389b778704..f7204d37e08 100644 --- a/packages/app/src/cli/services/app/graphiql.ts +++ b/packages/app/src/cli/services/app/graphiql.ts @@ -1,5 +1,5 @@ import {createClientCredentialsTokenProvider} from '../dev/processes/graphiql-token-provider.js' -import {OrganizationApp} from '../../models/organization.js' +import {OrganizationApp, appClientSecret} from '../../models/organization.js' import {buildAppURLForAdmin} from '../../utilities/app/app-url.js' import {resolveGraphiQLKey} from '@shopify/cli-kit/node/graphiql/server' import {runGraphiQLSession} from '@shopify/cli-kit/node/graphiql/session' @@ -20,7 +20,7 @@ interface OpenAppGraphiQLOptions { } export async function openAppGraphiQL(options: OpenAppGraphiQLOptions): Promise { - const apiSecret = options.remoteApp.apiSecretKeys[0]?.secret ?? '' + const apiSecret = await appClientSecret(options.remoteApp) const key = resolveGraphiQLKey(undefined, apiSecret, options.store) const tokenProvider = createClientCredentialsTokenProvider({ apiKey: options.remoteApp.apiKey, diff --git a/packages/app/src/cli/services/bulk-operations/bulk-operation-status.ts b/packages/app/src/cli/services/bulk-operations/bulk-operation-status.ts index df750616803..85e212575f6 100644 --- a/packages/app/src/cli/services/bulk-operations/bulk-operation-status.ts +++ b/packages/app/src/cli/services/bulk-operations/bulk-operation-status.ts @@ -1,5 +1,5 @@ import {formatOperationInfo, resolveApiVersion} from '../graphql/common.js' -import {OrganizationApp, Organization} from '../../models/organization.js' +import {OrganizationApp, Organization, appClientSecret} from '../../models/organization.js' import { BULK_OPERATIONS_MIN_API_VERSION, fetchBulkOperationById, @@ -12,7 +12,6 @@ import {renderInfo, renderSuccess, renderError, renderTable} from '@shopify/cli- import {outputContent, outputToken, outputNewline} from '@shopify/cli-kit/node/output' import {ensureAuthenticatedAdminAsApp} from '@shopify/cli-kit/node/session' import {timeAgo, formatDate} from '@shopify/cli-kit/common/string' -import {BugError} from '@shopify/cli-kit/node/error' import colors from '@shopify/cli-kit/node/colors' interface GetBulkOperationStatusOptions { @@ -42,9 +41,7 @@ export async function getBulkOperationStatus(options: GetBulkOperationStatusOpti ], }) - const appSecret = remoteApp.apiSecretKeys[0]?.secret - if (!appSecret) throw new BugError('No API secret keys found for app') - + const appSecret = await appClientSecret(remoteApp) const adminSession = await ensureAuthenticatedAdminAsApp(storeFqdn, remoteApp.apiKey, appSecret) const operation = await fetchBulkOperationById({ @@ -80,9 +77,7 @@ export async function listBulkOperations(options: ListBulkOperationsOptions): Pr ], }) - const appSecret = remoteApp.apiSecretKeys[0]?.secret - if (!appSecret) throw new BugError('No API secret keys found for app') - + const appSecret = await appClientSecret(remoteApp) const adminSession = await ensureAuthenticatedAdminAsApp(storeFqdn, remoteApp.apiKey, appSecret) const nodes = await fetchRecentBulkOperations({ diff --git a/packages/app/src/cli/services/dev.test.ts b/packages/app/src/cli/services/dev.test.ts index 119576f884d..5a3f0888956 100644 --- a/packages/app/src/cli/services/dev.test.ts +++ b/packages/app/src/cli/services/dev.test.ts @@ -2,6 +2,8 @@ import {dev, blockIfMigrationIncomplete} from './dev.js' import {setupDevProcesses} from './dev/processes/setup-dev-processes.js' import {renderDev} from './dev/ui.js' import {fetchAppRemoteConfiguration} from './app/select-app.js' +import * as devUrls from './dev/urls.js' +import {DevSessionStatusManager} from './dev/processes/dev-session/dev-session-status-manager.js' import { testAppLinked, testDeveloperPlatformClient, @@ -11,6 +13,9 @@ import { testProject, } from '../models/app/app.test-data.js' import metadata from '../metadata.js' +import {Web, WebType} from '../models/app/app.js' +import {DeveloperPlatformClient} from '../utilities/developer-platform-client.js' +import {AbortError} from '@shopify/cli-kit/node/error' import {describe, expect, test, vi} from 'vitest' import {hashString} from '@shopify/cli-kit/node/crypto' import {reportAnalyticsEvent} from '@shopify/cli-kit/node/analytics' @@ -86,6 +91,71 @@ describe('dev', () => { }) }) +describe('dev client secret', () => { + const webs: Web[] = [{directory: 'web', configuration: {roles: [WebType.Backend], commands: {dev: 'npm run dev'}}}] + + function runDevForWebApp(appClientSecrets: DeveloperPlatformClient['appClientSecrets']) { + const app = testAppLinked({webs}) + const developerPlatformClient = testDeveloperPlatformClient({appClientSecrets}) + vi.mocked(fetchAppRemoteConfiguration).mockResolvedValue({name: 'Remote app', application_url: '', embedded: true}) + vi.mocked(getAvailableTCPPort).mockResolvedValue(3456) + vi.mocked(checkPortAvailability).mockResolvedValue(true) + vi.mocked(setupDevProcesses).mockResolvedValue({ + processes: [], + previewUrl: 'https://dev-store.myshopify.com/admin/apps/api-key', + graphiqlUrl: undefined, + devSessionStatusManager: new DevSessionStatusManager({isReady: true}), + }) + vi.mocked(renderDev).mockResolvedValue(undefined) + const shouldOrPromptUpdateURLs = vi.spyOn(devUrls, 'shouldOrPromptUpdateURLs').mockResolvedValue(true) + + const running = dev({ + app, + project: testProject({usesWorkspaces: true}), + remoteApp: testOrganizationApp({apiKey: 'api-key', apiSecretKeys: [], developerPlatformClient}), + organization: testOrganization(), + specifications: [], + developerPlatformClient, + store: testOrganizationStore({}), + directory: app.directory, + update: true, + commandConfig: {} as any, + skipDependenciesInstallation: true, + tunnel: {mode: 'custom', url: 'https://localhost:3456'}, + }) + return {running, shouldOrPromptUpdateURLs} + } + + test('passes the client secret fetched on demand to the web processes', async () => { + // Given + vi.stubEnv('SHOPIFY_SERVICE_ACCOUNT_TOKEN', 'automation-token') + const appClientSecrets = vi.fn().mockResolvedValue([{secret: 'fetched-secret'}]) + + // When + const {running} = runDevForWebApp(appClientSecrets) + await running + + // Then + expect(appClientSecrets).toHaveBeenCalledWith(expect.objectContaining({apiKey: 'api-key'})) + expect(setupDevProcesses).toHaveBeenCalledWith(expect.objectContaining({apiSecret: 'fetched-secret'})) + vi.unstubAllEnvs() + }) + + test("stops before updating the app URLs when a web app can't get its client secret", async () => { + // Given + vi.stubEnv('SHOPIFY_SERVICE_ACCOUNT_TOKEN', 'automation-token') + + // When + const {running, shouldOrPromptUpdateURLs} = runDevForWebApp(vi.fn().mockResolvedValue([])) + + // Then + await expect(running).rejects.toThrow(AbortError) + expect(shouldOrPromptUpdateURLs).not.toHaveBeenCalled() + expect(setupDevProcesses).not.toHaveBeenCalled() + vi.unstubAllEnvs() + }) +}) + describe('blockIfMigrationIncomplete', () => { const baseConfig = () => ({ localApp: testAppLinked({}), diff --git a/packages/app/src/cli/services/dev.ts b/packages/app/src/cli/services/dev.ts index e5a81c4ad65..411c1641d45 100644 --- a/packages/app/src/cli/services/dev.ts +++ b/packages/app/src/cli/services/dev.ts @@ -10,6 +10,7 @@ import { import {showReusedDevValues} from './context.js' import {installAppDependencies} from './dependencies.js' import {DevConfig, DevProcesses, setupDevProcesses} from './dev/processes/setup-dev-processes.js' +import {devClientSecret} from './dev/client-secret.js' import {frontAndBackendConfig} from './dev/processes/utils.js' import {renderDev} from './dev/ui.js' import {DevProcessFunction} from './dev/processes/types.js' @@ -26,7 +27,7 @@ import {getAnalyticsTunnelType} from '../utilities/analytics.js' import metadata from '../metadata.js' import {AppConfigurationUsedByCli} from '../models/extensions/specifications/types/app_config.js' import {RemoteAwareExtensionSpecification} from '../models/extensions/specification.js' -import {ports} from '../constants.js' +import {environmentVariableNames, ports} from '../constants.js' import {generateCertificate} from '../utilities/mkcert.js' import {throwUidMappingError} from '../prompts/uid-mapping-error.js' import {TomlFile} from '@shopify/cli-kit/node/toml/toml-file' @@ -34,11 +35,12 @@ import {Config} from '@oclif/core' import {AbortController} from '@shopify/cli-kit/node/abort' import {checkPortAvailability, getAvailableTCPPort} from '@shopify/cli-kit/node/tcp' import {TunnelClient} from '@shopify/cli-kit/node/plugins/tunnel' -import {getBackendPort} from '@shopify/cli-kit/node/environment' +import {getBackendPort, getEnvironmentVariables} from '@shopify/cli-kit/node/environment' import {reportAnalyticsEvent} from '@shopify/cli-kit/node/analytics' import {OutputProcess} from '@shopify/cli-kit/node/output' import {hashString} from '@shopify/cli-kit/node/crypto' import {AbortError} from '@shopify/cli-kit/node/error' +import {isTruthy} from '@shopify/cli-kit/node/context/utilities' export interface DevOptions { app: AppLinkedInterface @@ -92,6 +94,13 @@ async function prepareForDev(commandOptions: DevOptions): Promise { ) remoteApp.configuration = remoteConfiguration + // Before anything changes remotely, so dev without a usable secret stops before it updates the app URLs. + const apiSecret = await devClientSecret({ + remoteApp, + hasWebs: app.webs.length > 0, + graphiqlEnabled: !isTruthy(getEnvironmentVariables()[environmentVariableNames.disableGraphiQLExplorer]), + }) + showReusedDevValues({ app, remoteApp, @@ -174,6 +183,7 @@ async function prepareForDev(commandOptions: DevOptions): Promise { partnerUrlsUpdated, graphiqlPort, graphiqlKey: commandOptions.graphiqlKey, + apiSecret, } } diff --git a/packages/app/src/cli/services/dev/client-secret.test.ts b/packages/app/src/cli/services/dev/client-secret.test.ts new file mode 100644 index 00000000000..1abe5f7f47f --- /dev/null +++ b/packages/app/src/cli/services/dev/client-secret.test.ts @@ -0,0 +1,72 @@ +import {devClientSecret} from './client-secret.js' +import {testDeveloperPlatformClient, testOrganizationApp} from '../../models/app/app.test-data.js' +import {afterEach, describe, expect, test, vi} from 'vitest' +import {AbortError} from '@shopify/cli-kit/node/error' +import {mockAndCaptureOutput} from '@shopify/cli-kit/node/testing/output' + +function appWithRemoteSecrets(secrets: {secret: string}[]) { + const appClientSecrets = vi.fn().mockResolvedValue(secrets) + const remoteApp = testOrganizationApp({ + apiSecretKeys: [], + developerPlatformClient: testDeveloperPlatformClient({appClientSecrets}), + }) + return {remoteApp, appClientSecrets} +} + +describe('devClientSecret', () => { + afterEach(() => { + vi.unstubAllEnvs() + mockAndCaptureOutput().clear() + }) + + test('fetches the secret for an app with webs when an automation token can read it', async () => { + // Given + vi.stubEnv('SHOPIFY_SERVICE_ACCOUNT_TOKEN', 'automation-token') + const {remoteApp, appClientSecrets} = appWithRemoteSecrets([{secret: 'fetched-secret'}]) + + // When + const secret = await devClientSecret({remoteApp, hasWebs: true, graphiqlEnabled: true}) + + // Then + expect(secret).toEqual('fetched-secret') + expect(appClientSecrets).toHaveBeenCalledWith(remoteApp) + }) + + test('fails for an app with webs when the App Management API returns no secret', async () => { + // Given + vi.stubEnv('SHOPIFY_SERVICE_ACCOUNT_TOKEN', 'automation-token') + const {remoteApp} = appWithRemoteSecrets([]) + + // When + const secret = devClientSecret({remoteApp, hasWebs: true, graphiqlEnabled: false}) + + // Then + await expect(secret).rejects.toThrow(AbortError) + await expect(secret).rejects.toMatchObject({tryMessage: expect.stringContaining('shopify auth login')}) + }) + + test('warns and continues without GraphiQL for an extension-only app without a secret', async () => { + // Given + const output = mockAndCaptureOutput() + const {remoteApp} = appWithRemoteSecrets([]) + + // When + const secret = await devClientSecret({remoteApp, hasWebs: false, graphiqlEnabled: true}) + + // Then + expect(secret).toBeUndefined() + expect(output.warn()).toContain("GraphiQL isn't available") + }) + + test("doesn't ask for the secret for an extension-only app with GraphiQL disabled", async () => { + // Given + const {remoteApp, appClientSecrets} = appWithRemoteSecrets([{secret: 'fetched-secret'}]) + + // When + const secret = await devClientSecret({remoteApp, hasWebs: false, graphiqlEnabled: false}) + + // Then + expect(secret).toBeUndefined() + expect(appClientSecrets).not.toHaveBeenCalled() + }) +}) diff --git a/packages/app/src/cli/services/dev/client-secret.ts b/packages/app/src/cli/services/dev/client-secret.ts new file mode 100644 index 00000000000..1b9b4ae029a --- /dev/null +++ b/packages/app/src/cli/services/dev/client-secret.ts @@ -0,0 +1,36 @@ +import { + OrganizationApp, + appClientSecret, + fetchAppClientSecret, + missingClientSecretTryMessage, +} from '../../models/organization.js' +import {outputWarn} from '@shopify/cli-kit/node/output' + +/** + * Gets the client secret that dev needs, if any. Only the web processes and GraphiQL authenticate as the app. + * + * Web processes can't run without it, so dev fails. GraphiQL is optional, so dev warns and runs without it. + * Resolve it before dev changes anything remotely, such as the app URLs. + * + * @returns The client secret, or undefined when nothing needs it or it's unavailable for an app without webs. + */ +export async function devClientSecret({ + remoteApp, + hasWebs, + graphiqlEnabled, +}: { + remoteApp: OrganizationApp + hasWebs: boolean + graphiqlEnabled: boolean +}): Promise { + if (hasWebs) return appClientSecret(remoteApp) + if (!graphiqlEnabled) return undefined + + const secret = await fetchAppClientSecret(remoteApp) + if (!secret) { + outputWarn( + `GraphiQL isn't available because the App Management API didn't return the app's client secret for your credentials. ${missingClientSecretTryMessage()}`, + ) + } + return secret +} diff --git a/packages/app/src/cli/services/dev/processes/setup-dev-processes.test.ts b/packages/app/src/cli/services/dev/processes/setup-dev-processes.test.ts index bbbf4e47fa3..19b5ad12620 100644 --- a/packages/app/src/cli/services/dev/processes/setup-dev-processes.test.ts +++ b/packages/app/src/cli/services/dev/processes/setup-dev-processes.test.ts @@ -20,7 +20,7 @@ import { testOrganizationStore, testProject, } from '../../../models/app/app.test-data.js' -import {WebType} from '../../../models/app/app.js' +import {Web, WebType} from '../../../models/app/app.js' import {DeveloperPlatformClient} from '../../../utilities/developer-platform-client.js' import {AppEventWatcher} from '../app-events/app-event-watcher.js' import * as loader from '../../../models/app/loader.js' @@ -76,6 +76,69 @@ const appContextResult = { } describe('setup-dev-processes', () => { + function setupDevProcessesForApp({webs, apiSecret}: {webs: Web[]; apiSecret: string | undefined}) { + const developerPlatformClient = testDeveloperPlatformClient() + const localApp = testAppWithConfig({config: {}, app: {webs}}) + vi.spyOn(loader, 'reloadApp').mockResolvedValue(localApp) + + return setupDevProcesses({ + localApp, + commandOptions: { + ...appContextResult, + directory: '', + update: false, + commandConfig: new Config({root: ''}), + skipDependenciesInstallation: false, + tunnel: {mode: 'auto'}, + }, + network: { + proxyUrl: 'https://example.com/proxy', + proxyPort: 444, + backendPort: 111, + frontendPort: 222, + currentUrls: {applicationUrl: 'https://example.com/application', redirectUrlWhitelist: []}, + }, + remoteApp: testOrganizationApp({apiSecretKeys: [], developerPlatformClient}), + remoteAppUpdated: true, + storeFqdn: 'store.myshopify.io', + storeId: '123456789', + developerPlatformClient, + partnerUrlsUpdated: false, + graphiqlPort: 1234, + apiSecret, + }) + } + + test('runs an extension-only app without web processes or GraphiQL when there is no client secret', async () => { + // When + const {processes, graphiqlUrl} = await setupDevProcessesForApp({webs: [], apiSecret: undefined}) + + // Then + const types = processes.map((process) => process.type) + expect(types).toContain('dev-session') + expect(types).not.toContain('web') + expect(types).not.toContain('graphiql') + expect(types).not.toContain('send-webhook') + expect(graphiqlUrl).toBeUndefined() + }) + + test('gives web processes and GraphiQL the client secret fetched on demand', async () => { + // Given + const webs: Web[] = [{directory: 'web', configuration: {roles: [WebType.Backend], commands: {dev: 'npm run dev'}}}] + + // When + const {processes, graphiqlUrl} = await setupDevProcessesForApp({webs, apiSecret: 'fetched-secret'}) + + // Then + expect(processes.find((process) => process.type === 'web')).toMatchObject({ + options: {apiSecret: 'fetched-secret'}, + }) + expect(processes.find((process) => process.type === 'graphiql')).toMatchObject({ + options: {apiSecret: 'fetched-secret'}, + }) + expect(graphiqlUrl).toBeDefined() + }) + test('can create a process list', async () => { const developerPlatformClient: DeveloperPlatformClient = testDeveloperPlatformClient() const storeFqdn = 'store.myshopify.io' @@ -150,6 +213,7 @@ describe('setup-dev-processes', () => { commandOptions, network, remoteApp, + apiSecret: 'api-secret', remoteAppUpdated, storeFqdn, storeId, @@ -330,6 +394,7 @@ describe('setup-dev-processes', () => { commandOptions, network, remoteApp, + apiSecret: 'api-secret', remoteAppUpdated, storeFqdn, storeId, @@ -393,6 +458,7 @@ describe('setup-dev-processes', () => { commandOptions, network, remoteApp, + apiSecret: 'api-secret', remoteAppUpdated, storeFqdn, storeId, @@ -491,6 +557,7 @@ describe('setup-dev-processes', () => { commandOptions, network, remoteApp, + apiSecret: 'api-secret', remoteAppUpdated, storeFqdn, storeId, @@ -589,6 +656,7 @@ describe('setup-dev-processes', () => { commandOptions, network, remoteApp, + apiSecret: 'api-secret', remoteAppUpdated, storeFqdn, storeId, diff --git a/packages/app/src/cli/services/dev/processes/setup-dev-processes.ts b/packages/app/src/cli/services/dev/processes/setup-dev-processes.ts index ae22fbec4a4..473535164c0 100644 --- a/packages/app/src/cli/services/dev/processes/setup-dev-processes.ts +++ b/packages/app/src/cli/services/dev/processes/setup-dev-processes.ts @@ -11,7 +11,7 @@ import {DevSessionStatusManager} from './dev-session/dev-session-status-manager. import {environmentVariableNames} from '../../../constants.js' import {AppLinkedInterface, getAppScopes, WebType} from '../../../models/app/app.js' -import {OrganizationApp} from '../../../models/organization.js' +import {OrganizationApp, appClientSecret} from '../../../models/organization.js' import {DevOptions} from '../../dev.js' import {LocalhostCert, getProxyingWebServer} from '../../../utilities/app/http-reverse-proxy.js' import {buildAppURLForAdmin} from '../../../utilities/app/app-url.js' @@ -68,6 +68,8 @@ export interface DevConfig { partnerUrlsUpdated: boolean graphiqlPort: number graphiqlKey?: string + /** The app's client secret, or undefined when dev doesn't need it or the App Management API didn't return it. */ + apiSecret: string | undefined } export async function setupDevProcesses({ @@ -81,6 +83,7 @@ export async function setupDevProcesses({ network, graphiqlPort, graphiqlKey, + apiSecret: resolvedApiSecret, }: DevConfig): Promise<{ processes: DevProcesses previewUrl: string @@ -88,22 +91,27 @@ export async function setupDevProcesses({ devSessionStatusManager: DevSessionStatusManager }> { const apiKey = remoteApp.apiKey - const apiSecret = remoteApp.apiSecretKeys[0]?.secret ?? '' const env = getEnvironmentVariables() - const shouldRenderGraphiQL = !isTruthy(env[environmentVariableNames.disableGraphiQLExplorer]) + const graphiqlEnabled = !isTruthy(env[environmentVariableNames.disableGraphiQLExplorer]) // At this point, the toml file has changed, we need to reload the app before actually starting dev const reloadedApp = await reloadApp(localApp) + + // The reload can pick up webs that weren't there when dev resolved the secret, and they can't run without it. + const apiSecret = resolvedApiSecret ?? (reloadedApp.webs.length > 0 ? await appClientSecret(remoteApp) : undefined) + const shouldRenderGraphiQL = graphiqlEnabled && apiSecret !== undefined const appWatcher = new AppEventWatcher(reloadedApp, network.proxyUrl) const adminDomain = await adminFqdn() const appPreviewUrl = buildAppURLForAdmin(storeFqdn, apiKey, adminDomain) const previewURL = appPreviewUrl - const resolvedGraphiqlKey = resolveGraphiQLKey(graphiqlKey, apiSecret, storeFqdn) - const graphiqlURL = shouldRenderGraphiQL - ? `http://localhost:${graphiqlPort}/graphiql?key=${encodeURIComponent(resolvedGraphiqlKey)}` - : undefined + const resolvedGraphiqlKey = + apiSecret === undefined ? undefined : resolveGraphiQLKey(graphiqlKey, apiSecret, storeFqdn) + const graphiqlURL = + shouldRenderGraphiQL && resolvedGraphiqlKey + ? `http://localhost:${graphiqlPort}/graphiql?key=${encodeURIComponent(resolvedGraphiqlKey)}` + : undefined const appEmbedded = reloadedApp.configuration.embedded const hasExtensions = reloadedApp.nonConfigExtensions.length > 0 @@ -116,16 +124,18 @@ export async function setupDevProcesses({ }) const processes = [ - ...(await setupWebProcesses({ - webs: reloadedApp.webs, - proxyUrl: network.proxyUrl, - frontendPort: network.frontendPort, - backendPort: network.backendPort, - apiKey, - apiSecret, - scopes: getAppScopes(reloadedApp.configuration), - })), - shouldRenderGraphiQL + ...(apiSecret === undefined + ? [] + : await setupWebProcesses({ + webs: reloadedApp.webs, + proxyUrl: network.proxyUrl, + frontendPort: network.frontendPort, + backendPort: network.backendPort, + apiKey, + apiSecret, + scopes: getAppScopes(reloadedApp.configuration), + })), + shouldRenderGraphiQL && apiSecret !== undefined ? await setupGraphiQLServerProcess({ appName: remoteApp.title, appUrl: appPreviewUrl, @@ -172,16 +182,18 @@ export async function setupDevProcesses({ themeExtensionPort: commandOptions.themeExtensionPort, storePassword: commandOptions.storePassword, }), - setupSendUninstallWebhookProcess({ - webs: reloadedApp.webs, - backendPort: network.backendPort, - frontendPort: network.frontendPort, - organizationId: remoteApp.organizationId, - developerPlatformClient, - storeFqdn, - apiSecret, - remoteAppUpdated, - }), + apiSecret === undefined + ? undefined + : setupSendUninstallWebhookProcess({ + webs: reloadedApp.webs, + backendPort: network.backendPort, + frontendPort: network.frontendPort, + organizationId: remoteApp.organizationId, + developerPlatformClient, + storeFqdn, + apiSecret, + remoteAppUpdated, + }), await setupAppLogsPollingProcess({ developerPlatformClient, subscription: { diff --git a/packages/app/src/cli/services/generate/shop-import/declarative-definitions.test.ts b/packages/app/src/cli/services/generate/shop-import/declarative-definitions.test.ts index 56478ef6638..ae8f84fbc9d 100644 --- a/packages/app/src/cli/services/generate/shop-import/declarative-definitions.test.ts +++ b/packages/app/src/cli/services/generate/shop-import/declarative-definitions.test.ts @@ -5,6 +5,7 @@ import { paginatedQuery, importDeclarativeDefinitions, } from './declarative-definitions.js' +import {testOrganizationAppWithoutClientSecret} from '../../../models/app/app.test-data.js' import { MetaobjectDefinitions, MetaobjectDefinitionsQuery, @@ -1143,17 +1144,14 @@ describe('importDeclarativeDefinitions', () => { outputMock.clear() }) - test('throws BugError when app has no API secret keys', async () => { + test('throws an AbortError when the App Management API returns no client secret', async () => { const importPromised = importDeclarativeDefinitions({ - remoteApp: { - apiKey: 'test-api-key', - apiSecretKeys: [], - }, + remoteApp: testOrganizationAppWithoutClientSecret(), store: { shopDomain: 'test-shop.myshopify.com', }, } as any) - await expect(importPromised).rejects.toThrow('No API secret keys found for app') + await expect(importPromised).rejects.toThrow("didn't return one for your credentials") }) test('existing definitions are not included in the output', async () => { diff --git a/packages/app/src/cli/services/generate/shop-import/declarative-definitions.ts b/packages/app/src/cli/services/generate/shop-import/declarative-definitions.ts index 0930bccdb2d..16603235206 100644 --- a/packages/app/src/cli/services/generate/shop-import/declarative-definitions.ts +++ b/packages/app/src/cli/services/generate/shop-import/declarative-definitions.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/prefer-nullish-coalescing */ import {FieldObject, Metafield, MetafieldOwners, MetaObject, ValidationRule} from './dcdd.js' -import {OrganizationApp, OrganizationStore} from '../../../models/organization.js' +import {OrganizationApp, OrganizationStore, appClientSecret} from '../../../models/organization.js' import { MetafieldDefinitions, MetafieldForImportFragment, @@ -19,7 +19,6 @@ import { MetaobjectStorefrontAccess, } from '../../../api/graphql/admin/generated/types.js' import {CurrentAppConfiguration} from '../../../models/app/app.js' -import {BugError} from '@shopify/cli-kit/node/error' import {AdminSession, ensureAuthenticatedAdminAsApp} from '@shopify/cli-kit/node/session' import {outputContent, outputInfo, outputToken} from '@shopify/cli-kit/node/output' import {TypedDocumentNode} from '@graphql-typed-document-node/core' @@ -388,12 +387,7 @@ function appConfigurationContains(appConfiguration: any, path: string[]): boolea async function createAdminApiSessionForShop(options: ImportDeclarativeDefinitionsOptions) { const {remoteApp, store} = options - const appSecret = remoteApp.apiSecretKeys[0]?.secret - - if (!appSecret) { - throw new BugError('No API secret keys found for app') - } - + const appSecret = await appClientSecret(remoteApp) const adminSession = await ensureAuthenticatedAdminAsApp(store.shopDomain, remoteApp.apiKey, appSecret) return adminSession } diff --git a/packages/app/src/cli/services/graphql/common.test.ts b/packages/app/src/cli/services/graphql/common.test.ts index 02257c5d85b..0403cc7906b 100644 --- a/packages/app/src/cli/services/graphql/common.test.ts +++ b/packages/app/src/cli/services/graphql/common.test.ts @@ -7,10 +7,16 @@ import { isMutation, } from './common.js' import {OrganizationApp, OrganizationStore} from '../../models/organization.js' +import { + testDeveloperPlatformClient, + testOrganizationApp, + testOrganizationAppWithoutClientSecret, +} from '../../models/app/app.test-data.js' import {BULK_OPERATIONS_MIN_API_VERSION} from '@shopify/cli-kit/node/api/bulk-operations' import {ensureAuthenticatedAdminAsApp} from '@shopify/cli-kit/node/session' import {fetchApiVersions} from '@shopify/cli-kit/node/api/admin' -import {describe, test, expect, vi, beforeEach} from 'vitest' +import {describe, test, expect, vi, beforeEach, afterEach} from 'vitest' +import {AbortError} from '@shopify/cli-kit/node/error' vi.mock('@shopify/cli-kit/node/session', async () => { const actual = await vi.importActual('@shopify/cli-kit/node/session') @@ -42,6 +48,10 @@ describe('createAdminSessionAsApp', () => { vi.mocked(ensureAuthenticatedAdminAsApp).mockResolvedValue(mockAdminSession) }) + afterEach(() => { + vi.unstubAllEnvs() + }) + test('creates admin session with app credentials', async () => { const session = await createAdminSessionAsApp(mockRemoteApp, storeFqdn) @@ -53,14 +63,27 @@ describe('createAdminSessionAsApp', () => { expect(session).toEqual(mockAdminSession) }) - test('throws BugError when app has no API secret keys', async () => { - const appWithoutSecret = { - ...mockRemoteApp, + test('authenticates with the secret the App Management API returns to an automation token', async () => { + vi.stubEnv('SHOPIFY_SERVICE_ACCOUNT_TOKEN', 'automation-token') + const appClientSecrets = vi.fn().mockResolvedValue([{secret: 'fetched-secret'}]) + const remoteApp = testOrganizationApp({ + apiKey: 'test-api-key', apiSecretKeys: [], - } as OrganizationApp + developerPlatformClient: testDeveloperPlatformClient({appClientSecrets}), + }) + + const session = await createAdminSessionAsApp(remoteApp, storeFqdn) + + expect(appClientSecrets).toHaveBeenCalledWith(remoteApp) + expect(ensureAuthenticatedAdminAsApp).toHaveBeenCalledWith(storeFqdn, 'test-api-key', 'fetched-secret') + expect(session).toEqual(mockAdminSession) + }) + + test('throws an AbortError when the App Management API returns no secret', async () => { + vi.stubEnv('SHOPIFY_SERVICE_ACCOUNT_TOKEN', 'automation-token') - await expect(createAdminSessionAsApp(appWithoutSecret, storeFqdn)).rejects.toThrow( - 'No API secret keys found for app', + await expect(createAdminSessionAsApp(testOrganizationAppWithoutClientSecret(), storeFqdn)).rejects.toThrow( + AbortError, ) expect(ensureAuthenticatedAdminAsApp).not.toHaveBeenCalled() diff --git a/packages/app/src/cli/services/graphql/common.ts b/packages/app/src/cli/services/graphql/common.ts index b9492b2e770..b7b46833a44 100644 --- a/packages/app/src/cli/services/graphql/common.ts +++ b/packages/app/src/cli/services/graphql/common.ts @@ -1,6 +1,6 @@ -import {OrganizationApp, OrganizationStore} from '../../models/organization.js' +import {OrganizationApp, OrganizationStore, appClientSecret} from '../../models/organization.js' import {ensureAuthenticatedAdminAsApp, AdminSession} from '@shopify/cli-kit/node/session' -import {AbortError, BugError} from '@shopify/cli-kit/node/error' +import {AbortError} from '@shopify/cli-kit/node/error' import {isMutation, validateSingleOperation, resolveApiVersion} from '@shopify/cli-kit/node/api/bulk-operations' // Generic GraphQL operation helpers live in the shared cli-kit bulk-operations engine; re-export @@ -15,10 +15,7 @@ export {isMutation, validateSingleOperation, resolveApiVersion} * @returns Admin session for making authenticated API requests. */ export async function createAdminSessionAsApp(remoteApp: OrganizationApp, storeFqdn: string): Promise { - const appSecret = remoteApp.apiSecretKeys[0]?.secret - if (!appSecret) throw new BugError('No API secret keys found for app') - - return ensureAuthenticatedAdminAsApp(storeFqdn, remoteApp.apiKey, appSecret) + return ensureAuthenticatedAdminAsApp(storeFqdn, remoteApp.apiKey, await appClientSecret(remoteApp)) } /** diff --git a/packages/app/src/cli/services/info.test.ts b/packages/app/src/cli/services/info.test.ts index 6f97d950f73..f277674bb26 100644 --- a/packages/app/src/cli/services/info.test.ts +++ b/packages/app/src/cli/services/info.test.ts @@ -4,6 +4,7 @@ import {logMetadataForLoadedContext} from './context.js' import { testAppLinked, testOrganizationApp, + testOrganizationAppWithoutClientSecret, testProject, testUIExtension, testAppConfigExtensions, @@ -79,7 +80,9 @@ test('preserves empty collections, false, and omitted dotenv and dev URLs', asyn }) test.each([true, false])('preserves web environment JSON with secret present: %s', async (hasSecret) => { - const remoteApp = testOrganizationApp({apiSecretKeys: hasSecret ? [{secret: 'secret'}] : []}) + const remoteApp = hasSecret + ? testOrganizationApp({apiSecretKeys: [{secret: 'secret'}]}) + : testOrganizationAppWithoutClientSecret() const result = await info(testAppLinked(), remoteApp, organization, testProject(), {webEnv: true}) expect(appInfoJsonOutputSchema.encode(result)).toBe( hasSecret diff --git a/packages/app/src/cli/services/info.ts b/packages/app/src/cli/services/info.ts index a921f0ec392..7880719f1b3 100644 --- a/packages/app/src/cli/services/info.ts +++ b/packages/app/src/cli/services/info.ts @@ -2,7 +2,7 @@ import {appInfoJsonOutputSchema, remoteAppInfoSchema, type AppInfoResult} from ' import {logMetadataForLoadedContext} from './context.js' import {AppLinkedInterface, getAppScopes} from '../models/app/app.js' import {Project} from '../models/project/project.js' -import {Organization, OrganizationApp} from '../models/organization.js' +import {Organization, OrganizationApp, fetchAppClientSecret, warnClientSecretOmitted} from '../models/organization.js' import {ExtensionInstance} from '../models/extensions/extension-instance.js' import {ExtensionSpecification} from '../models/extensions/specification.js' import {TomlFile} from '@shopify/cli-kit/node/toml/toml-file' @@ -18,9 +18,11 @@ export async function info( ): Promise { if (options.webEnv) { await logMetadataForLoadedContext(remoteApp, organization.source) + const apiSecret = await fetchAppClientSecret(remoteApp) + if (!apiSecret) warnClientSecretOmitted() return { SHOPIFY_API_KEY: remoteApp.apiKey, - ...(remoteApp.apiSecretKeys[0] ? {SHOPIFY_API_SECRET: remoteApp.apiSecretKeys[0].secret} : {}), + ...(apiSecret ? {SHOPIFY_API_SECRET: apiSecret} : {}), SCOPES: getAppScopes(app.configuration), } } diff --git a/packages/app/src/cli/services/webhook/trigger-options.test.ts b/packages/app/src/cli/services/webhook/trigger-options.test.ts index ab8a5afb562..6d00d679403 100644 --- a/packages/app/src/cli/services/webhook/trigger-options.test.ts +++ b/packages/app/src/cli/services/webhook/trigger-options.test.ts @@ -3,7 +3,12 @@ import {requestApiVersions} from './request-api-versions.js' import {requestTopics} from './request-topics.js' import {WebhookTriggerInput} from './trigger.js' import {addressPrompt, apiVersionPrompt, deliveryMethodPrompt, topicPrompt} from '../../prompts/webhook/trigger.js' -import {testAppLinked, testDeveloperPlatformClient, testOrganizationApp} from '../../models/app/app.test-data.js' +import { + testAppLinked, + testDeveloperPlatformClient, + testOrganizationApp, + testOrganizationAppWithoutClientSecret, +} from '../../models/app/app.test-data.js' import {describe, expect, vi, test, afterEach} from 'vitest' import {AbortError} from '@shopify/cli-kit/node/error' import {mockAndCaptureOutput} from '@shopify/cli-kit/node/testing/output' @@ -22,6 +27,7 @@ const organizationId = ORGANIZATION_APP.organizationId afterEach(() => { mockAndCaptureOutput().clear() + vi.unstubAllEnvs() }) describe('collectApiVersion', () => { @@ -170,17 +176,67 @@ describe('collectCredentials', () => { expect(credentials).toEqual({apiKey: API_KEY, clientSecret: SECRET}) }) - test('retrieves the secret from config or remotely when the flag is missing', async () => { + test('fetches the secret from the App Management API when the flag is missing', async () => { // Given - const inputWithoutSecret = {...input, clientSecret: undefined} + const remoteApp = testOrganizationApp() + const inputWithoutSecret = {...input, clientSecret: undefined, remoteApp} // When const credentials = await collectCredentials(inputWithoutSecret, DELIVERY_METHOD) // Then - expect(credentials).toEqual({ - apiKey: ORGANIZATION_APP.apiKey, - clientSecret: ORGANIZATION_APP.apiSecretKeys[0]!.secret, + expect(credentials).toEqual({apiKey: remoteApp.apiKey, clientSecret: 'api-secret'}) + }) + + test('uses the secret flag with the app API key for EventBridge without a client ID', async () => { + // Given + vi.stubEnv('SHOPIFY_SERVICE_ACCOUNT_TOKEN', 'automation-token') + const appClientSecrets = vi.fn() + const remoteApp = testOrganizationApp({ + apiSecretKeys: [], + developerPlatformClient: testDeveloperPlatformClient({appClientSecrets}), + }) + const eventBridgeInput = {...input, clientId: undefined, remoteApp} + + // When + const credentials = await collectCredentials(eventBridgeInput, 'event-bridge') + + // Then + expect(credentials).toEqual({apiKey: remoteApp.apiKey, clientSecret: SECRET}) + expect(appClientSecrets).not.toHaveBeenCalled() + }) + + test('fetches the secret when the secret flag is empty', async () => { + // Given + const appClientSecrets = vi.fn().mockResolvedValue([{secret: 'fetched-secret'}]) + const remoteApp = testOrganizationApp({ + apiSecretKeys: [], + developerPlatformClient: testDeveloperPlatformClient({appClientSecrets}), + }) + + // When + const credentials = await collectCredentials( + {...input, clientSecret: '', clientId: undefined, remoteApp}, + 'event-bridge', + ) + + // Then + expect(credentials).toEqual({apiKey: remoteApp.apiKey, clientSecret: 'fetched-secret'}) + expect(appClientSecrets).toHaveBeenCalledWith(remoteApp) + }) + + test('asks for the secret flag when the App Management API returns no secret', async () => { + // Given + vi.stubEnv('SHOPIFY_SERVICE_ACCOUNT_TOKEN', 'automation-token') + const inputWithoutSecret = {...input, clientSecret: undefined, remoteApp: testOrganizationAppWithoutClientSecret()} + + // When + const credentials = collectCredentials(inputWithoutSecret, DELIVERY_METHOD) + + // Then + await expect(credentials).rejects.toThrow(AbortError) + await expect(collectCredentials(inputWithoutSecret, DELIVERY_METHOD)).rejects.toMatchObject({ + tryMessage: expect.stringContaining('--client-secret'), }) }) @@ -190,7 +246,7 @@ describe('collectCredentials', () => { const app = testAppLinked() // When - await collectCredentials({app, remoteApp: ORGANIZATION_APP}, DELIVERY_METHOD) + await collectCredentials({app, remoteApp: testOrganizationApp()}, DELIVERY_METHOD) // Then expect(outputMock.info()).toMatchInlineSnapshot(` diff --git a/packages/app/src/cli/services/webhook/trigger-options.ts b/packages/app/src/cli/services/webhook/trigger-options.ts index 24c64d82dd2..f9a0242f0a1 100644 --- a/packages/app/src/cli/services/webhook/trigger-options.ts +++ b/packages/app/src/cli/services/webhook/trigger-options.ts @@ -10,6 +10,7 @@ import { import {WebhookTriggerInput} from './trigger.js' import {addressPrompt, apiVersionPrompt, deliveryMethodPrompt, topicPrompt} from '../../prompts/webhook/trigger.js' import {DeveloperPlatformClient} from '../../utilities/developer-platform-client.js' +import {appClientSecret} from '../../models/organization.js' import {renderCurrentlyUsedConfigInfo} from '../context.js' import {basename} from '@shopify/cli-kit/node/path' @@ -46,9 +47,11 @@ export async function collectCredentials( configFile: basename(app.configPath), }) - const clientSecret = remoteApp.apiSecretKeys.find((elm) => elm.secret)!.secret + // An empty --client-secret counts as absent, as in the check above. + if (secret) return {clientSecret: secret, apiKey: remoteApp.apiKey} + return { - clientSecret, + clientSecret: await appClientSecret(remoteApp, 'Pass the secret with the --client-secret flag.'), apiKey: remoteApp.apiKey, } } diff --git a/packages/app/src/cli/utilities/developer-platform-client.ts b/packages/app/src/cli/utilities/developer-platform-client.ts index 81a2a56bc43..9013b8354e8 100644 --- a/packages/app/src/cli/utilities/developer-platform-client.ts +++ b/packages/app/src/cli/utilities/developer-platform-client.ts @@ -209,6 +209,11 @@ export interface DeveloperPlatformClient { unsafeRefreshToken: () => Promise accountInfo: () => Promise appFromIdentifiers: (apiKey: string) => Promise + /** + * Fetches the app's client secrets. App lookups leave them out, so only commands that authenticate as the app ask. + * Returns an empty list when the current credentials can't read them. + */ + appClientSecrets: (app: Pick) => Promise organizations: () => Promise orgFromId: (orgId: string) => Promise orgAndApps: (orgId: string) => Promise> diff --git a/packages/app/src/cli/utilities/developer-platform-client/app-management-client.test.ts b/packages/app/src/cli/utilities/developer-platform-client/app-management-client.test.ts index fe1c84726e5..d0eee18bf6e 100644 --- a/packages/app/src/cli/utilities/developer-platform-client/app-management-client.test.ts +++ b/packages/app/src/cli/utilities/developer-platform-client/app-management-client.test.ts @@ -36,6 +36,9 @@ import {AvailableTopicsQuery} from '../../api/graphql/webhooks/generated/availab import {CliTesting, CliTestingMutation} from '../../api/graphql/webhooks/generated/cli-testing.js' import {SendSampleWebhookVariables} from '../../services/webhook/request-sample.js' import {CreateApp} from '../../api/graphql/app-management/generated/create-app.js' +import {ActiveAppReleaseFromApiKey} from '../../api/graphql/app-management/generated/active-app-release-from-api-key.js' +import {AppClientCredentials} from '../../api/graphql/app-management/generated/app-client-credentials.js' +import {AppVersionById} from '../../api/graphql/app-management/generated/app-version-by-id.js' import {AppVersions, AppVersionsQuery} from '../../api/graphql/app-management/generated/app-versions.js' import {AppVersionsQuerySchema} from '../../api/graphql/get_versions_list.js' import {BrandingSpecIdentifier} from '../../models/extensions/specifications/app_config_branding.js' @@ -45,7 +48,7 @@ import {MinimalAppIdentifiers, OrganizationSource} from '../../models/organizati import {CreateAssetUrl} from '../../api/graphql/app-management/generated/create-asset-url.js' import {SourceExtension} from '../../api/graphql/app-management/generated/types.js' import {fetchOrganizationById, fetchOrganizations} from '@shopify/organizations' -import {describe, expect, test, vi, beforeEach} from 'vitest' +import {describe, expect, test, vi, beforeEach, afterEach} from 'vitest' import {CLI_KIT_VERSION} from '@shopify/cli-kit/common/version' import {fetch, shopifyFetch} from '@shopify/cli-kit/node/http' import { @@ -703,7 +706,7 @@ describe('createApp', () => { vi.mocked(webhooksRequestDoc).mockResolvedValueOnce(mockedApiVersionResult) vi.mocked(appManagementRequestDoc).mockResolvedValueOnce({ appCreate: { - app: {id: '1', key: 'key', activeRoot: {clientCredentials: {secrets: [{key: 'secret'}]}}}, + app: {id: '1', key: 'key'}, userErrors: [], }, }) @@ -755,7 +758,7 @@ describe('createApp', () => { id: '1', key: 'api-key', apiKey: 'api-key', - apiSecretKeys: [{secret: 'secret'}], + apiSecretKeys: [], flags: [], grantedScopes: [], organizationId: '1', @@ -772,11 +775,6 @@ describe('createApp', () => { app: { id: expectedApp.id, key: expectedApp.key, - activeRoot: { - clientCredentials: { - secrets: [{key: 'secret'}], - }, - }, }, userErrors: [], }, @@ -799,7 +797,7 @@ describe('createApp', () => { }) vi.mocked(appManagementRequestDoc).mockResolvedValueOnce({ appCreate: { - app: {id: '1', key: 'key', activeRoot: {clientCredentials: {secrets: [{key: 'secret'}]}}}, + app: {id: '1', key: 'key'}, userErrors: [], }, }) @@ -837,6 +835,140 @@ describe('createApp', () => { }) }) +describe('app client credentials', () => { + afterEach(() => { + vi.unstubAllEnvs() + }) + + const activeAppReleaseResponse = { + app: { + id: 'gid://shopify/App/1', + key: 'api-key', + organizationId: 'gid://shopify/Organization/1', + activeRoot: {grantedShopifyApprovalScopes: ['read_products']}, + activeRelease: {id: 'gid://shopify/Release/1', version: {name: 'my-app', appModules: []}}, + }, + } + + function clientWithToken() { + const client = AppManagementClient.getInstance() + client.token = () => Promise.resolve('token') + return client + } + + test.each([ActiveAppReleaseFromApiKey, CreateApp])( + "app lookups and creation don't select client credentials", + (query) => { + expect(JSON.stringify(query)).not.toContain('clientCredentials') + }, + ) + + test.each([undefined, 'SHOPIFY_SERVICE_ACCOUNT_TOKEN', 'SHOPIFY_APP_AUTOMATION_TOKEN', 'SHOPIFY_CLI_PARTNERS_TOKEN'])( + 'looks up an app without its client secret (automation token: %s)', + async (variable) => { + // Given + if (variable) vi.stubEnv(variable, 'automation-token') + vi.mocked(appManagementRequestDoc).mockResolvedValueOnce(activeAppReleaseResponse) + + // When + const app = await clientWithToken().appFromIdentifiers('api-key') + + // Then + expect(vi.mocked(appManagementRequestDoc)).toHaveBeenCalledTimes(1) + expect(vi.mocked(appManagementRequestDoc)).toHaveBeenCalledWith( + expect.objectContaining({query: ActiveAppReleaseFromApiKey, variables: {apiKey: 'api-key'}}), + ) + expect(app).toMatchObject({id: 'gid://shopify/App/1', apiKey: 'api-key', title: 'my-app', apiSecretKeys: []}) + }, + ) + + test.each([undefined, 'SHOPIFY_SERVICE_ACCOUNT_TOKEN'])( + 'fetches the client secrets the App Management API returns (automation token: %s)', + async (variable) => { + // Given + if (variable) vi.stubEnv(variable, 'automation-token') + vi.mocked(appManagementRequestDoc).mockResolvedValueOnce({ + app: { + id: 'gid://shopify/App/1', + activeRoot: {clientCredentials: {secrets: [{key: 'secret-1'}, {key: 'secret-2'}]}}, + }, + }) + + // When + const secrets = await clientWithToken().appClientSecrets({apiKey: 'api-key'}) + + // Then + expect(vi.mocked(appManagementRequestDoc)).toHaveBeenCalledWith( + expect.objectContaining({query: AppClientCredentials, variables: {apiKey: 'api-key'}}), + ) + expect(secrets).toEqual([{secret: 'secret-1'}, {secret: 'secret-2'}]) + }, + ) + + test.each([ + ['no secrets', {secrets: []}], + ['null credentials', null], + ])('returns no client secrets when the App Management API returns %s', async (_, clientCredentials) => { + // Given + vi.mocked(appManagementRequestDoc).mockResolvedValueOnce({ + app: {id: 'gid://shopify/App/1', activeRoot: {clientCredentials}}, + }) + + // When + const secrets = await clientWithToken().appClientSecrets({apiKey: 'api-key'}) + + // Then + expect(secrets).toEqual([]) + }) + + test('reads the active app version without the client secret', async () => { + // Given + vi.mocked(appManagementRequestDoc).mockResolvedValueOnce(activeAppReleaseResponse) + + // When + const version = await clientWithToken().activeAppVersion(testOrganizationApp({apiKey: 'api-key'})) + + // Then + expect(vi.mocked(appManagementRequestDoc)).toHaveBeenCalledWith( + expect.objectContaining({query: ActiveAppReleaseFromApiKey, variables: {apiKey: 'api-key'}}), + ) + expect(version).toMatchObject({id: 'gid://shopify/Release/1', appModuleVersions: []}) + }) + + test('diffs app versions without the client secret', async () => { + // Given + vi.mocked(appManagementRequestDoc).mockImplementation(async ({query}) => { + if (query === AppVersionById) return {version: {appModules: []}} + return activeAppReleaseResponse + }) + + // When + const diff = await clientWithToken().appVersionsDiff(testOrganizationApp({apiKey: 'api-key'}), { + appVersionId: 1, + versionId: 'gid://shopify/Version/1', + }) + + // Then + expect(vi.mocked(appManagementRequestDoc)).not.toHaveBeenCalledWith( + expect.objectContaining({query: AppClientCredentials}), + ) + expect(diff).toEqual({app: {versionsDiff: {added: [], updated: [], removed: []}}}) + }) + + test('creates an app without its client secret', async () => { + // Given + vi.mocked(webhooksRequestDoc).mockResolvedValueOnce({publicApiVersions: [{handle: '2025-01'}]}) + vi.mocked(appManagementRequestDoc).mockResolvedValueOnce({ + appCreate: {app: {id: '1', key: 'api-key'}, userErrors: []}, + }) + + // When + const app = await clientWithToken().createApp(testOrganization(), {name: 'app-name'}) + + // Then + expect(app).toMatchObject({apiKey: 'api-key', apiSecretKeys: []}) + }) +}) describe('apiVersions', () => { test('fetches available public API versions', async () => { // Given @@ -1536,7 +1668,6 @@ describe('AppManagementClient', () => { organizationId: 'gid://shopify/Organization/2', activeRoot: { grantedShopifyApprovalScopes: ['read_products'], - clientCredentials: {secrets: [{key: 'secret-1'}]}, }, activeRelease: { id: 'gid://shopify/Release/1', @@ -1557,7 +1688,7 @@ describe('AppManagementClient', () => { id: 'gid://shopify/App/1', title: 'My App', apiKey, - apiSecretKeys: [{secret: 'secret-1'}], + apiSecretKeys: [], organizationId: '2', grantedScopes: ['read_products'], applicationUrl: undefined, diff --git a/packages/app/src/cli/utilities/developer-platform-client/app-management-client.ts b/packages/app/src/cli/utilities/developer-platform-client/app-management-client.ts index 1ae6c08e1b7..93797b0e1e5 100644 --- a/packages/app/src/cli/utilities/developer-platform-client/app-management-client.ts +++ b/packages/app/src/cli/utilities/developer-platform-client/app-management-client.ts @@ -88,6 +88,7 @@ import { ReleasedAppModuleFragment, } from '../../api/graphql/app-management/generated/active-app-release.js' import {ActiveAppReleaseFromApiKey} from '../../api/graphql/app-management/generated/active-app-release-from-api-key.js' +import {AppClientCredentials} from '../../api/graphql/app-management/generated/app-client-credentials.js' import {ReleaseVersion} from '../../api/graphql/app-management/generated/release-version.js' import { CreateAppVersion, @@ -368,12 +369,12 @@ export class AppManagementClient implements DeveloperPlatformClient { if (!app) return undefined const {name, appModules} = app.activeRelease.version const appHomeModule = appModules.find((mod) => mod.specification.externalIdentifier === 'app_home') - const apiSecretKeys = app.activeRoot.clientCredentials.secrets.map((secret) => ({secret: secret.key})) return { id: app.id, title: name, apiKey: app.key, - apiSecretKeys, + // Fetched on demand by the commands that need it, with appClientSecrets. + apiSecretKeys: [], organizationId: String(numberFromGid(app.organizationId)), grantedScopes: app.activeRoot.grantedShopifyApprovalScopes, applicationUrl: appHomeModule?.config?.app_url as string | undefined, @@ -383,6 +384,13 @@ export class AppManagementClient implements DeveloperPlatformClient { } } + async appClientSecrets({apiKey}: Pick): Promise { + const {app} = await this.appManagementRequest({query: AppClientCredentials, variables: {apiKey}}) + // The App Management API decides who can read the secret: it can return no secrets, or no credentials at all. + const clientCredentials: {secrets: {key: string}[]} | null | undefined = app?.activeRoot.clientCredentials + return clientCredentials?.secrets.map((secret) => ({secret: secret.key})) ?? [] + } + async organizations(): Promise { const orgs = await fetchOrganizations() return orgs.map((org) => ({ @@ -546,12 +554,12 @@ export class AppManagementClient implements DeveloperPlatformClient { // Need to figure this out still const flags = filterDisabledFlags([]) const createdApp = result.appCreate.app - const apiSecretKeys = createdApp.activeRoot.clientCredentials.secrets.map((secret) => ({secret: secret.key})) return { ...createdApp, title: options.name, apiKey: createdApp.key, - apiSecretKeys, + // Fetched on demand by the commands that need it, with appClientSecrets. + apiSecretKeys: [], grantedScopes: options?.scopesArray ?? [], organizationId: org.id, newApp: true,