From 05a85930c90968c19dff1706138a8e1fe49512e3 Mon Sep 17 00:00:00 2001 From: James Date: Mon, 7 Apr 2025 21:31:21 +0200 Subject: [PATCH 1/5] add skip-check setting and prevent skipChecks from overriding config file --- package.json | 9 +++++++-- src/checkov/checkovRunner.ts | 13 +++++++++---- src/configuration.ts | 6 ++++++ src/extension.ts | 9 +++++---- 4 files changed, 27 insertions(+), 10 deletions(-) diff --git a/package.json b/package.json index 5d0a085..1538657 100644 --- a/package.json +++ b/package.json @@ -89,12 +89,17 @@ }, "checkov-prismaless.skipFrameworks": { "title": "Skip Frameworks", - "markdownDescription": "Filter scan to skip specific frameworks (e.g., 'arm json secrets serverless').\nAdd multiple frameworks using spaces.\nSee [Checkov Frameworks](https://www.checkov.io/2.Basics/CLI%20Command%20Reference.html) for more information.\nYou may need to run the extension command 'Clear Checkov results cache' after modifying this setting.", + "markdownDescription": "Filter scan to skip specific frameworks (e.g., 'arm json secrets serverless'). Add multiple frameworks using spaces. See [Checkov Frameworks](https://www.checkov.io/2.Basics/CLI%20Command%20Reference.html) for more information. \nYou may need to run the extension command 'Clear Checkov results cache' after modifying this setting. \nSetting this configuration property will overide any `skip-framework` entry defined in your [checkov config file](https://github.com/bridgecrewio/checkov?tab=readme-ov-file#configuration-using-a-config-file).", "type": "string" }, "checkov-prismaless.frameworks": { "title": "Frameworks", - "markdownDescription": "Filter scan to run only on specific frameworks (e.g., 'arm json secrets serverless').\nAdd multiple frameworks using spaces.\nSee [Checkov Frameworks](https://www.checkov.io/2.Basics/CLI%20Command%20Reference.html) for more information.\nYou may need to run the extension command 'Clear Checkov results cache' after modifying this setting.", + "markdownDescription": "Filter scan to run only on specific frameworks (e.g., 'arm json secrets serverless'). Add multiple frameworks using spaces. \nSee [Checkov Frameworks](https://www.checkov.io/2.Basics/CLI%20Command%20Reference.html) for more information. \nYou may need to run the extension command 'Clear Checkov results cache' after modifying this setting. \nSetting this configuration property will overide any `framework` entry defined in your [checkov config file](https://github.com/bridgecrewio/checkov?tab=readme-ov-file#configuration-using-a-config-file).", + "type": "string" + }, + "checkov-prismaless.skipChecks": { + "title": "Skip Checks", + "markdownDescription": "Filter scan to run all checks except those listed (deny list). Add multiple checks using comma separated values \nSetting this configuration property will overide any `skip-check` entry defined in your [checkov config file](https://github.com/bridgecrewio/checkov?tab=readme-ov-file#configuration-using-a-config-file). ", "type": "string" } } diff --git a/src/checkov/checkovRunner.ts b/src/checkov/checkovRunner.ts index 4d8602a..d834c3d 100644 --- a/src/checkov/checkovRunner.ts +++ b/src/checkov/checkovRunner.ts @@ -14,7 +14,7 @@ const dockerMountDir = '/checkovScan'; const configMountDir = '/checkovConfig'; const caMountDir = '/checkovCert'; const externalChecksMountDir = '/checkovExternalChecks'; -const skipChecks: string[] = ['BC_LIC*']; +const skipChecksDefault: string[] = ['BC_LIC*']; const getDockerFileMountParams = (mountDir: string, filePath: string | undefined): string[] => { if (!filePath) { @@ -61,7 +61,7 @@ const cleanupStdout = (stdout: string) => stdout.replace(/.\[0m/g,''); // Clean export const runCheckovScan = (logger: Logger, checkovInstallation: CheckovInstallation, extensionVersion: string, fileName: string, certPath: string | undefined, useBcIds: boolean | undefined, debugLogs: boolean | undefined, noCertVerify: boolean | undefined, cancelToken: vscode.CancellationToken, - configPath: string | undefined, externalChecksDir: string | undefined, skipFrameworks: string[] | undefined, frameworks: string[] | undefined): Promise => { + configPath: string | undefined, externalChecksDir: string | undefined, skipFrameworks: string[] | undefined, frameworks: string[] | undefined, skipChecks: string[] | undefined): Promise => { return new Promise((resolve, reject) => { const { checkovInstallationMethod, checkovPath } = checkovInstallation; const timestamp = Date.now(); @@ -77,7 +77,12 @@ export const runCheckovScan = (logger: Logger, checkovInstallation: CheckovInsta const certificateParams: string[] = certPath && checkovInstallationMethod !== 'docker' ? ['-ca', `"${certPath}"`] : []; const bcIdParam: string[] = useBcIds ? ['--output-bc-ids'] : []; const noCertVerifyParam: string[] = noCertVerify ? ['--no-cert-verify'] : []; - const skipCheckParam: string[] = skipChecks.length ? ['--skip-check', skipChecks.join(',')] : []; + const skipCheckParam: string[] = skipChecks + ? ['--skip-check', [...skipChecks, ...skipChecksDefault].join(',')] + : (pipRunParams.length === 0 ? ['--skip-check', skipChecksDefault.join(',')] : []); + // If the user has set specific skip-check in the extension configuration, they will override the config file (checkov does not support both). + // If the user has not set skip-check in the extension configuration but has a checkov config file, the config file skip-check will be evaluated. + // If the user has not set neither specific skip checks nor config file, the skipChecksDefault will be applied to prevent breaking changes. const externalChecksParams: string[] = externalChecksDir && checkovInstallationMethod !== 'docker' ? ['--external-checks-dir', externalChecksDir] : []; const frameworkParams: string[] = frameworks ? ['--framework', frameworks.join(' ')] : []; const skipFrameworkParams: string[] = skipFrameworks ? ['--skip-framework', skipFrameworks.join(' ')] : []; @@ -85,7 +90,7 @@ export const runCheckovScan = (logger: Logger, checkovInstallation: CheckovInsta getGitRepoName(logger, vscode.window.activeTextEditor?.document.fileName).then((repoName) => { const repoIdParams = repoName ? ['--repo-id', repoName] : ['--repo-id', 'vscode/default']; const checkovArguments: string[] = [...dockerRunParams, ...certificateParams, ...bcIdParam, ...noCertVerifyParam, '-s', - ...repoIdParams, ...filePathParams, ...skipCheckParam, '-o', 'json', ...pipRunParams, ...externalChecksParams, ...frameworkParams, ...skipFrameworkParams]; + ...repoIdParams, ...filePathParams, '-o', 'json', ...pipRunParams, ...externalChecksParams, ...frameworkParams, ...skipFrameworkParams, ...skipCheckParam]; logger.info('Running checkov:'); logger.info(`${checkovPath} ${checkovArguments.join(' ')}`); diff --git a/src/configuration.ts b/src/configuration.ts index 60c1001..9dca3a6 100644 --- a/src/configuration.ts +++ b/src/configuration.ts @@ -36,6 +36,12 @@ export const getSkipFrameworks = (): string[] | undefined => { return skipFrameworks ? skipFrameworks.split(' ').map(entry => entry.trim()) : undefined; }; +export const getSkipChecks = (): string[] | undefined => { + const configuration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration('checkov-prismaless'); + const skipChecks = configuration.get('skipChecks'); + return skipChecks ? skipChecks.split(' ').map(entry => entry.trim()) : undefined; +}; + export const getFrameworks = (): string[] | undefined => { const configuration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration('checkov-prismaless'); const frameworks = configuration.get('frameworks'); diff --git a/src/extension.ts b/src/extension.ts index ca23f3a..41a2d88 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -6,7 +6,7 @@ import { applyDiagnostics } from './diagnostics'; import { fixCodeActionProvider, providedCodeActionKinds } from './suggestFix'; import { getLogger, saveCheckovResult, isSupportedFileType, extensionVersion, runVersionCommand, getFileHash, saveCachedResults, getCachedResults, clearCache, checkovVersionKey } from './utils'; import { initializeStatusBarItem, setErrorStatusBarItem, setPassedStatusBarItem, setReadyStatusBarItem, setSyncingStatusBarItem, showAboutCheckovMessage, showContactUsDetails } from './userInterface'; -import { getCheckovVersion, shouldDisableErrorMessage, getPathToCert, getUseBcIds, getUseDebugLogs, getExternalChecksDir, getNoCertVerify, getSkipFrameworks, getFrameworks } from './configuration'; +import { getCheckovVersion, shouldDisableErrorMessage, getPathToCert, getUseBcIds, getUseDebugLogs, getExternalChecksDir, getNoCertVerify, getSkipFrameworks, getFrameworks, getSkipChecks } from './configuration'; import { CLEAR_RESULTS_CACHE, GET_INSTALLATION_DETAILS_COMMAND, INSTALL_OR_UPDATE_CHECKOV_COMMAND, OPEN_CHECKOV_LOG, OPEN_CONFIGURATION_COMMAND, OPEN_EXTERNAL_COMMAND, REMOVE_DIAGNOSTICS_COMMAND, RUN_FILE_SCAN_COMMAND } from './commands'; import { getConfigFilePath } from './parseCheckovConfig'; import { clearVersionCache } from './checkov/checkovInstaller'; @@ -157,6 +157,7 @@ export function activate(context: vscode.ExtensionContext): void { const noCertVerify = getNoCertVerify(); const externalChecksDir = getExternalChecksDir(); const skipFrameworks = getSkipFrameworks(); + const skipChecks = getSkipChecks(); const frameworks = getFrameworks(); vscode.commands.executeCommand(REMOVE_DIAGNOSTICS_COMMAND); if (!fileUri && vscode.window.activeTextEditor && !isSupportedFileType(vscode.window.activeTextEditor.document.fileName, true)) @@ -175,11 +176,11 @@ export function activate(context: vscode.ExtensionContext): void { logger.debug(`useCache is true, but did not find cached results for file: ${vscode.window.activeTextEditor.document.fileName}, hash: ${hash}`); } } - await runScan(vscode.window.activeTextEditor, certPath, useBcIds, debugLogs, noCertVerify, checkovRunCancelTokenSource.token, externalChecksDir, fileUri, skipFrameworks, frameworks); + await runScan(vscode.window.activeTextEditor, certPath, useBcIds, debugLogs, noCertVerify, checkovRunCancelTokenSource.token, externalChecksDir, fileUri, skipFrameworks, frameworks, skipChecks); } }; - const runScan = debounce(async (editor: vscode.TextEditor, certPath: string | undefined, useBcIds: boolean | undefined, debugLogs: boolean | undefined, noCertVerify: boolean | undefined, cancelToken: vscode.CancellationToken, externalChecksDir: string | undefined, fileUri?: vscode.Uri, skipFrameworks?: string[] | undefined, frameworks?: string[] | undefined): Promise => { + const runScan = debounce(async (editor: vscode.TextEditor, certPath: string | undefined, useBcIds: boolean | undefined, debugLogs: boolean | undefined, noCertVerify: boolean | undefined, cancelToken: vscode.CancellationToken, externalChecksDir: string | undefined, fileUri?: vscode.Uri, skipFrameworks?: string[] | undefined, frameworks?: string[] | undefined, skipChecks?: string[] | undefined): Promise => { logger.info('Starting to scan.'); try { setSyncingStatusBarItem(checkovInstallation?.actualVersion, 'Checkov scanning'); @@ -191,7 +192,7 @@ export function activate(context: vscode.ExtensionContext): void { return; } - const checkovResponse = await runCheckovScan(logger, checkovInstallation, extensionVersion, filePath, certPath, useBcIds, debugLogs, noCertVerify, cancelToken, configPath, externalChecksDir, skipFrameworks, frameworks); + const checkovResponse = await runCheckovScan(logger, checkovInstallation, extensionVersion, filePath, certPath, useBcIds, debugLogs, noCertVerify, cancelToken, configPath, externalChecksDir, skipFrameworks, frameworks, skipChecks); handleScanResults(filePath, editor, context.workspaceState, checkovResponse.results.failedChecks, logger); } catch (error) { if (cancelToken.isCancellationRequested) { From 624b6e3577fc53739bb2ed4285aa64ca94dc2f98 Mon Sep 17 00:00:00 2001 From: James Date: Mon, 7 Apr 2025 21:55:55 +0200 Subject: [PATCH 2/5] update documentation --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 7896276..d6e7975 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [Checkov](https://github.com/bridgecrewio/checkov) is an open-source static code analysis tool for infrastructure-as-code, secrets, and software composition analysis. -This extension is a fork of the original Bridgecrew extension, with the removal of the PrismaCloud API dependencies. This forked extension can be found on the [Visual Studio Extension Marketplace](https://marketplace.visualstudio.com/items?itemName=XargsUK.checkov-prismaless) and its source code is available in an [Apache 2.0 licensed repository](https://github.com/XargsUK/checkov-prismaless-vscode). The original extension can be found on the [Visual Studio Extension Marketplace](https://marketplace.visualstudio.com/items?itemName=Bridgecrew.checkov) and its source code is available in an [Apache 2.0 licensed repository](https://github.com/bridgecrewio/checkov-vscode). This extension is downstream from the original extension. +This extension is a fork of the original Bridgecrew extension, with the removal of the PrismaCloud API dependencies. This forked extension can be found on the [Visual Studio Extension Marketplace](https://marketplace.visualstudio.com/items?itemName=XargsUK.checkov-prismaless) and its source code is available in an [Apache 2.0 licensed repository](https://github.com/XargsUK/checkov-prismaless-vscode). The original extension can be found on the [Visual Studio Extension Marketplace](https://marketplace.visualstudio.com/items?itemName=Bridgecrew.checkov) and its source code is available in an [Apache 2.0 licensed repository](https://github.com/bridgecrewio/checkov-vscode). This extension is downstream from the original extension. The Checkov Extension for Visual Studio Code enables developers to get real-time scan results, as well as inline fix suggestions as they develop cloud infrastructure. @@ -23,7 +23,7 @@ Extension features include: ### Install -Open the CheckovPrismaless Extension for Visual Studio Code in the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=XargsUK.checkov-prismaless) and install. +Open the CheckovPrismaless Extension for Visual Studio Code in the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=XargsUK.checkov-prismaless) and install. ### Dependencies @@ -31,7 +31,6 @@ Open the CheckovPrismaless Extension for Visual Studio Code in the [Visual Studi The Checkov extension will invoke the latest version of ```Checkov```. - ### Usage * Open a file you wish to scan with checkov in VSCode. @@ -40,11 +39,14 @@ The Checkov extension will invoke the latest version of ```Checkov```. * Click a scan to see its details. Details will include the violating policy and a link to step-by-step fix guidelines. * In most cases, the Details will include a fix option. This will either add, remove or replace an unwanted configuration, based on the Checkov fix dictionaries. * You can skip checks by adding an inline skip annotation ```checkov:skip=:```. -* The extension will continue to scan file modifications and highlight errors in your editor upon every material resource modification. +* You can skip checks for the whole workspace by adding a `.checkov.yaml` in your workspace folder (see [Checkov Configuration file](https://github.com/bridgecrewio/checkov?tab=readme-ov-file#configuration-using-a-config-file)). +* You can override certain configuration values by using the extension settings (`framework`, `skip-framework`, `skip-check`). +* The extension will continue *to* scan file modifications and highlight errors in your editor upon every material resource modification. ### Troubleshooting logs To access the checkov-prismaless-vscode logs directory, open the VS Code Command Palette `(Ctrl+Shift+P)` or `(Command+Shift+P)`, and run the command `Open Checkov Log`. It is helpful to delete the log file and then retry whichever operation failed to produce clean logs. ### Why Create this Fork? + I detailed the reasons for creating this fork in a [Medium Article](https://medium.com/aws-in-plain-english/checkov-de-prismafying-the-vscode-extension-for-local-security-scans-c33aa35f5b35). The main reasons were to remove the PrismaCloud API dependencies once the Bridgecrew API was deprecated. Checkov is an excellent tool and I wanted to ensure that the Visual Studio Code extension was still available for the community to use. From 2525d1c0780ddb41011c56c694f7775351486ba4 Mon Sep 17 00:00:00 2001 From: James Date: Mon, 7 Apr 2025 21:56:05 +0200 Subject: [PATCH 3/5] fix typo in logs --- src/utils.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils.ts b/src/utils.ts index 8036cda..52b065b 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -148,9 +148,9 @@ export const getGitRepoName = async (logger: winston.Logger, filename: string | if (line.startsWith('origin')) { // remove the upstream name from the front and ' (fetch)' or ' (push)' from the back const repoUrl = line.split('\t')[1].split(' ')[0]; - logger.info('repo url' + repoUrl); + logger.info('repo url ' + repoUrl); const repoName = parseRepoName(repoUrl); - logger.info('repo name' + repoName); + logger.info('repo name ' + repoName); if (repoName) { return repoName; } From c18e0e7c796d2934b3f73f549d6262a1450e46ca Mon Sep 17 00:00:00 2001 From: James Date: Mon, 7 Apr 2025 22:46:51 +0200 Subject: [PATCH 4/5] add automatically clearing cache upon config update --- README.md | 5 ++--- package.json | 10 ++++++++-- src/configuration.ts | 6 ++++++ src/extension.ts | 22 +++++++++++++++++++++- 4 files changed, 37 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index d6e7975..95ef164 100644 --- a/README.md +++ b/README.md @@ -39,9 +39,8 @@ The Checkov extension will invoke the latest version of ```Checkov```. * Click a scan to see its details. Details will include the violating policy and a link to step-by-step fix guidelines. * In most cases, the Details will include a fix option. This will either add, remove or replace an unwanted configuration, based on the Checkov fix dictionaries. * You can skip checks by adding an inline skip annotation ```checkov:skip=:```. -* You can skip checks for the whole workspace by adding a `.checkov.yaml` in your workspace folder (see [Checkov Configuration file](https://github.com/bridgecrewio/checkov?tab=readme-ov-file#configuration-using-a-config-file)). -* You can override certain configuration values by using the extension settings (`framework`, `skip-framework`, `skip-check`). -* The extension will continue *to* scan file modifications and highlight errors in your editor upon every material resource modification. +* You can skip checks for the whole workspace by adding a `.checkov.yaml` in your workspace folder (see [Checkov Configuration file](https://github.com/bridgecrewio/checkov?tab=readme-ov-file#configuration-using-a-config-file)). You can also override certain configuration values by using the extension settings (`framework`, `skip-framework`, `skip-check`). By default, whenever you edit your checkov config file or override the values using the extension settings, the checkov cache will be cleared - this behaviour can be deisable . +* The extension will continue to scan file modifications and highlight errors in your editor upon every material resource modification. ### Troubleshooting logs diff --git a/package.json b/package.json index 1538657..ce39542 100644 --- a/package.json +++ b/package.json @@ -77,6 +77,12 @@ "type": "boolean", "default": false }, + "checkov-prismaless.clearCacheUponConfigUpdate": { + "title": "Clear cache upon config update", + "markdownDescription": "Clear the Checkov extension results cache when the Checkov configuration is updated. This ensures consistant results but will require Checkov to re-scan all files.", + "type": "boolean", + "default": true + }, "checkov-prismaless.useDebugLogs": { "title": "Use debug logs", "markdownDescription": "Whether to print debug logs from Checkov for troubleshooting", @@ -89,12 +95,12 @@ }, "checkov-prismaless.skipFrameworks": { "title": "Skip Frameworks", - "markdownDescription": "Filter scan to skip specific frameworks (e.g., 'arm json secrets serverless'). Add multiple frameworks using spaces. See [Checkov Frameworks](https://www.checkov.io/2.Basics/CLI%20Command%20Reference.html) for more information. \nYou may need to run the extension command 'Clear Checkov results cache' after modifying this setting. \nSetting this configuration property will overide any `skip-framework` entry defined in your [checkov config file](https://github.com/bridgecrewio/checkov?tab=readme-ov-file#configuration-using-a-config-file).", + "markdownDescription": "Filter scan to skip specific frameworks (e.g., 'arm json secrets serverless'). Add multiple frameworks using spaces. See [Checkov Frameworks](https://www.checkov.io/2.Basics/CLI%20Command%20Reference.html) for more information. \nSetting this configuration property will overide any `skip-framework` entry defined in your [checkov config file](https://github.com/bridgecrewio/checkov?tab=readme-ov-file#configuration-using-a-config-file).", "type": "string" }, "checkov-prismaless.frameworks": { "title": "Frameworks", - "markdownDescription": "Filter scan to run only on specific frameworks (e.g., 'arm json secrets serverless'). Add multiple frameworks using spaces. \nSee [Checkov Frameworks](https://www.checkov.io/2.Basics/CLI%20Command%20Reference.html) for more information. \nYou may need to run the extension command 'Clear Checkov results cache' after modifying this setting. \nSetting this configuration property will overide any `framework` entry defined in your [checkov config file](https://github.com/bridgecrewio/checkov?tab=readme-ov-file#configuration-using-a-config-file).", + "markdownDescription": "Filter scan to run only on specific frameworks (e.g., 'arm json secrets serverless'). Add multiple frameworks using spaces. \nSee [Checkov Frameworks](https://www.checkov.io/2.Basics/CLI%20Command%20Reference.html) for more information. \nSetting this configuration property will overide any `framework` entry defined in your [checkov config file](https://github.com/bridgecrewio/checkov?tab=readme-ov-file#configuration-using-a-config-file).", "type": "string" }, "checkov-prismaless.skipChecks": { diff --git a/src/configuration.ts b/src/configuration.ts index 9dca3a6..6496a92 100644 --- a/src/configuration.ts +++ b/src/configuration.ts @@ -102,6 +102,12 @@ export const shouldDisableErrorMessage = (): boolean => { return disableErrorMessageFlag; }; +export const shouldClearCacheUponConfigUpdate = (): boolean => { + const configuration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration('checkov-prismaless'); + const clearCacheUponConfigUpdateFlag = configuration.get('clearCacheUponConfigUpdate', true); + return clearCacheUponConfigUpdateFlag; +}; + export const getExternalChecksDir = (): string | undefined => { const configuration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration('checkov-prismaless'); const externalChecksDir = configuration.get('externalChecksDir'); diff --git a/src/extension.ts b/src/extension.ts index 41a2d88..45821db 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -6,7 +6,7 @@ import { applyDiagnostics } from './diagnostics'; import { fixCodeActionProvider, providedCodeActionKinds } from './suggestFix'; import { getLogger, saveCheckovResult, isSupportedFileType, extensionVersion, runVersionCommand, getFileHash, saveCachedResults, getCachedResults, clearCache, checkovVersionKey } from './utils'; import { initializeStatusBarItem, setErrorStatusBarItem, setPassedStatusBarItem, setReadyStatusBarItem, setSyncingStatusBarItem, showAboutCheckovMessage, showContactUsDetails } from './userInterface'; -import { getCheckovVersion, shouldDisableErrorMessage, getPathToCert, getUseBcIds, getUseDebugLogs, getExternalChecksDir, getNoCertVerify, getSkipFrameworks, getFrameworks, getSkipChecks } from './configuration'; +import { getCheckovVersion, shouldDisableErrorMessage, shouldClearCacheUponConfigUpdate, getPathToCert, getUseBcIds, getUseDebugLogs, getExternalChecksDir, getNoCertVerify, getSkipFrameworks, getFrameworks, getSkipChecks } from './configuration'; import { CLEAR_RESULTS_CACHE, GET_INSTALLATION_DETAILS_COMMAND, INSTALL_OR_UPDATE_CHECKOV_COMMAND, OPEN_CHECKOV_LOG, OPEN_CONFIGURATION_COMMAND, OPEN_EXTERNAL_COMMAND, REMOVE_DIAGNOSTICS_COMMAND, RUN_FILE_SCAN_COMMAND } from './commands'; import { getConfigFilePath } from './parseCheckovConfig'; import { clearVersionCache } from './checkov/checkovInstaller'; @@ -130,6 +130,9 @@ export function activate(context: vscode.ExtensionContext): void { setReadyStatusBarItem(checkovInstallation?.actualVersion); return; } + if ((saveEvent.fileName.endsWith('.checkov.yaml') || saveEvent.fileName.endsWith('.checkov.yml') && shouldClearCacheUponConfigUpdate())) { + vscode.commands.executeCommand(CLEAR_RESULTS_CACHE); + } vscode.commands.executeCommand(RUN_FILE_SCAN_COMMAND); }), vscode.window.onDidChangeActiveTextEditor(changeViewEvent => { @@ -140,6 +143,23 @@ export function activate(context: vscode.ExtensionContext): void { return; } vscode.commands.executeCommand(RUN_FILE_SCAN_COMMAND); + }), + vscode.workspace.onDidChangeConfiguration(event => { + const cache_affected = [ + 'checkov-prismaless.skipFrameworks', + 'checkov-prismaless.frameworks', + 'checkov-prismaless.skipChecks' + ]; + if (cache_affected.some(key => event.affectsConfiguration(key)) && shouldClearCacheUponConfigUpdate()) { + vscode.commands.executeCommand(CLEAR_RESULTS_CACHE); + } + + const version_affected = [ + 'checkov-prismaless.checkovVersion', + ]; + if (version_affected.some(key => event.affectsConfiguration(key)) && shouldClearCacheUponConfigUpdate()) { + vscode.commands.executeCommand(CLEAR_VERSION_CACHE); + } }) ); From b2fa02e4a2f239c517733cfdd6305733e202f2ee Mon Sep 17 00:00:00 2001 From: James Date: Tue, 8 Apr 2025 01:49:40 +0200 Subject: [PATCH 5/5] fix errors 'ENOENT: no such file or directory, open 'Untitled-1'' and 'ENOENT: no such file or directory, open 'exthost' --- src/extension.ts | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/extension.ts b/src/extension.ts index 45821db..53d312f 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -77,7 +77,7 @@ export function activate(context: vscode.ExtensionContext): void { vscode.window.showWarningMessage('Still installing/updating Checkov, please wait a few seconds and try again.', 'Got it'); return; } - resetCancelTokenSource(); + resetCancelTokenSource(); // Stop any previous scan await startScan(fileUri, true); }), vscode.commands.registerCommand(REMOVE_DIAGNOSTICS_COMMAND, () => { @@ -137,14 +137,20 @@ export function activate(context: vscode.ExtensionContext): void { }), vscode.window.onDidChangeActiveTextEditor(changeViewEvent => { if (!extensionReady) return; - if (changeViewEvent && !isSupportedFileType(changeViewEvent.document.fileName)) { - resetCancelTokenSource(); + if (changeViewEvent && (!isSupportedFileType(changeViewEvent.document.fileName) || changeViewEvent.document.uri.toString().startsWith('output:'))) { + // Ignore files not supported + // Ignore output channels (e.g. output:exthost, output:ptyhost, etc.) + resetCancelTokenSource(); // Stop scan setReadyStatusBarItem(checkovInstallation?.actualVersion); return; } + if (changeViewEvent && changeViewEvent.document.isUntitled) { + return; // Ignore untitled documents (e.g. untitled:Untitled-1, etc.), as Checkov requires a file saved to disk. + } vscode.commands.executeCommand(RUN_FILE_SCAN_COMMAND); }), vscode.workspace.onDidChangeConfiguration(event => { + if (!extensionReady) return; const cache_affected = [ 'checkov-prismaless.skipFrameworks', 'checkov-prismaless.frameworks', @@ -185,8 +191,14 @@ export function activate(context: vscode.ExtensionContext): void { if (vscode.window.activeTextEditor) { if (useCache) { const fileToScan = fileUri?.fsPath || vscode.window.activeTextEditor.document.fileName; - const hash = getFileHash(fileToScan); - // fileUri will be non-null if we are scanning a temp (unsaved) file, so use the active editor filename for caching in this case + let hash: string; + try { + hash = getFileHash(fileToScan); + } catch (error) { + // getFileHash fails for unsaved files or output channels + logger.error('Error occurred while generating file hash', { error }); + return; + } const cachedResults = getCachedResults(context, hash, vscode.window.activeTextEditor.document.fileName, logger); if (cachedResults) { logger.debug(`Found cached results for file: ${vscode.window.activeTextEditor.document.fileName}, hash: ${hash}`);