Skip to content

Commit ef84803

Browse files
authored
Warn when app security check can't copy the instructions
Copying the coding-agent instructions is the last step of `check`, after the scan finished and its report is shown. A clipboard that isn't available aborted the command, so the exit code no longer reported the scan. `check` now warns with the clipboard tool's message and suggests `--print-instructions` instead, and the exit code follows `--blocking`. `instructions --copy` still fails, because copying is all it does.
1 parent f96789b commit ef84803

3 files changed

Lines changed: 115 additions & 10 deletions

File tree

‎packages/app/src/cli/commands/app/security/check.integration.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import {AbortError} from '@shopify/cli-kit/node/error'
88
import {fileExists, fileRealPath, inTemporaryDirectory} from '@shopify/cli-kit/node/fs'
99
import {unstyled} from '@shopify/cli-kit/node/output'
1010
import {joinPath, normalizePath} from '@shopify/cli-kit/node/path'
11+
import {renderSelectPrompt} from '@shopify/cli-kit/node/ui'
12+
import clipboard from 'clipboardy'
1113
import {describe, expect, test, vi} from 'vitest'
1214
import {mkdir, readFile, writeFile} from 'node:fs/promises'
1315
// eslint-disable-next-line n/prefer-global/console
@@ -33,6 +35,13 @@ vi.mock('../../../services/context.js', async (importOriginal) => ({
3335
...(await importOriginal<typeof import('../../../services/context.js')>()),
3436
appFromIdentifiers: vi.fn(),
3537
}))
38+
// Tests answer the prompts. How a real terminal draws them is checked by hand.
39+
vi.mock('@shopify/cli-kit/node/ui', async (importOriginal) => ({
40+
...(await importOriginal<typeof import('@shopify/cli-kit/node/ui')>()),
41+
renderSelectPrompt: vi.fn(),
42+
}))
43+
// Tests must not replace the clipboard of the machine that runs them.
44+
vi.mock('clipboardy', () => ({default: {write: vi.fn()}}))
3645

3746
async function createApp(directory: string): Promise<{nestedDirectory: string}> {
3847
const routesDirectory = joinPath(directory, 'app', 'routes')
@@ -47,6 +56,13 @@ async function createApp(directory: string): Promise<{nestedDirectory: string}>
4756
return {nestedDirectory: routesDirectory}
4857
}
4958

59+
/** An app whose source holds a Shopify access token, which the deterministic scan reports as a high finding. */
60+
async function createAppWithSecret(directory: string): Promise<void> {
61+
await createApp(directory)
62+
const testToken = ['shpat', '0123456789abcdef0123456789abcdef'].join('_')
63+
await writeFile(joinPath(directory, 'app', 'routes', 'index.ts'), `const access_token = "${testToken}"\n`)
64+
}
65+
5066
async function readJson(path: string): Promise<unknown> {
5167
return JSON.parse(await readFile(path, 'utf8'))
5268
}
@@ -96,6 +112,31 @@ async function runCommand(argv: string[]) {
96112
}
97113
}
98114

115+
/**
116+
* Runs the command as if stdin and stderr were a terminal, where it prompts unless `--no-input` is passed. CLI Kit reads
117+
* `--no-input` from the process arguments, not from the arguments given to `run`, so the environment sets it as well.
118+
*/
119+
async function runInTerminal(argv: string[], {noInput = false} = {}) {
120+
vi.stubEnv('CI', '')
121+
if (noInput) vi.stubEnv('SHOPIFY_FLAG_NO_INPUT', '1')
122+
const streams = [process.stdin, process.stderr]
123+
const descriptors = streams.map((stream) => Object.getOwnPropertyDescriptor(stream, 'isTTY'))
124+
for (const stream of streams) Object.defineProperty(stream, 'isTTY', {value: true, configurable: true})
125+
try {
126+
return await runCommand(noInput ? [...argv, '--no-input'] : argv)
127+
} finally {
128+
streams.forEach((stream, index) => {
129+
const descriptor = descriptors[index]
130+
if (descriptor) {
131+
Object.defineProperty(stream, 'isTTY', descriptor)
132+
} else {
133+
Reflect.deleteProperty(stream, 'isTTY')
134+
}
135+
})
136+
vi.unstubAllEnvs()
137+
}
138+
}
139+
99140
describe('app security check command boundary', () => {
100141
test('scans an app from a nested directory and writes deterministic-findings.json and agent-checks.json', async () => {
101142
await inTemporaryDirectory(async (directory) => {
@@ -336,6 +377,32 @@ describe('app security check command boundary', () => {
336377
})
337378
})
338379

380+
test.each([
381+
{blocking: 'none', exitCode: 0},
382+
{blocking: 'high', exitCode: 1},
383+
])(
384+
'warns when the instructions cannot be copied, after the report, and exits as --blocking $blocking requires',
385+
async ({blocking, exitCode}) => {
386+
await inTemporaryDirectory(async (directory) => {
387+
await createAppWithSecret(directory)
388+
vi.mocked(renderSelectPrompt).mockResolvedValue('copy')
389+
vi.mocked(clipboard.write).mockRejectedValue(new Error('Command failed with ENOENT: pbcopy'))
390+
391+
const result = await runInTerminal(['--path', directory, '--blocking', blocking])
392+
393+
expect(result.exitCode).toBe(exitCode)
394+
expect(result.stdout).toBe('')
395+
const stderr = boxText(result.stderr)
396+
expect(stderr).toContain(
397+
"Couldn't copy the app security check instructions to the clipboard: Command failed with ENOENT: pbcopy",
398+
)
399+
expect(stderr).toContain('Run the check again with `--print-instructions` to print them.')
400+
expect(stderr.indexOf('Config file shopify.app.toml')).toBeLessThan(stderr.indexOf("Couldn't copy"))
401+
expect(clipboard.write).toHaveBeenCalledOnce()
402+
})
403+
},
404+
)
405+
339406
test('looks up --client-id, not the TOML client ID', async () => {
340407
await inTemporaryDirectory(async (directory) => {
341408
await createApp(directory)

‎packages/app/src/cli/services/security-check/result.test.ts‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -402,13 +402,30 @@ describe('renderSecurityCheckResult for a scan', () => {
402402
expect(stdout).toBe('')
403403
})
404404

405-
test('aborts when the instructions cannot be copied', async () => {
406-
vi.mocked(clipboard.write).mockRejectedValue(new Error('Command failed with ENOENT: pbcopy'))
407-
408-
await expect(present(scanned(), {}, testDependencies('copy', true))).rejects.toMatchObject({
409-
code: 'clipboard-unavailable',
410-
})
411-
})
405+
test.each([
406+
{level: 'none', blockedChecks: 0, exitCode: undefined},
407+
{level: 'high', blockedChecks: 1, exitCode: 1},
408+
] as const)(
409+
'warns instead of aborting when the instructions cannot be copied, and exits as --blocking $level requires',
410+
async ({level, blockedChecks, exitCode}) => {
411+
process.exitCode = undefined
412+
vi.mocked(clipboard.write).mockRejectedValue(new Error('Command failed with ENOENT: pbcopy'))
413+
const execution = {...scanExecution, scan: {...scan, issues: [committedSecretIssue]}}
414+
const check = scanned({execution, blocking: {level, blockedChecks}})
415+
416+
const {stdout, stderr} = await present(check, {}, testDependencies('copy', true))
417+
418+
const warning = boxText(stderr)
419+
expect(warning).toContain(
420+
"Couldn't copy the app security check instructions to the clipboard: Command failed with ENOENT: pbcopy",
421+
)
422+
expect(warning).toContain('Run the check again with `--print-instructions` to print them.')
423+
expect(warning.indexOf('1 security issue found.')).toBeLessThan(warning.indexOf("Couldn't copy"))
424+
expect(warning).not.toContain('Copied app security check instructions')
425+
expect(stdout).toBe('')
426+
expect(process.exitCode).toBe(exitCode)
427+
},
428+
)
412429

413430
test('sets exit code 1 after the output when the scan breaches --blocking', async () => {
414431
process.exitCode = undefined

‎packages/app/src/cli/services/security-check/result.ts‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import {
22
appSecurityInstructions,
3+
ClipboardUnavailableError,
34
deliverAppSecurityInstructions,
45
renderAppSecurityInstructions,
56
} from '../app-security-instructions.js'
@@ -95,14 +96,34 @@ export async function renderSecurityCheckResult(
9596
commands: check.commands,
9697
scanScope: check.scope,
9798
})
98-
const delivery = {copy: destination === 'copy'}
99-
await deliverAppSecurityInstructions(instructions, delivery)
100-
renderAppSecurityInstructions(instructions, delivery)
99+
if (destination === 'print') {
100+
renderAppSecurityInstructions(instructions, {copy: false})
101+
} else if (await copyInstructions(instructions)) {
102+
renderAppSecurityInstructions(instructions, {copy: true})
103+
}
101104
}
102105

103106
if (check.blocking.blockedChecks > 0) process.exitCode = 1
104107
}
105108

109+
/**
110+
* Copies the instructions to the clipboard, and returns whether they're on it. The scan has already finished and its
111+
* report is shown, so a clipboard that isn't available only warns.
112+
*/
113+
async function copyInstructions(instructions: string): Promise<boolean> {
114+
try {
115+
await deliverAppSecurityInstructions(instructions, {copy: true})
116+
return true
117+
} catch (error) {
118+
if (!(error instanceof ClipboardUnavailableError)) throw error
119+
renderWarning({
120+
headline: error.message,
121+
body: ['Run the check again with', {command: '--print-instructions'}, 'to print them.'],
122+
})
123+
return false
124+
}
125+
}
126+
106127
async function instructionsDestination(
107128
options: SecurityCheckPresentationOptions,
108129
agentCheckCount: number,

0 commit comments

Comments
 (0)