diff --git a/CHANGELOG.md b/CHANGELOG.md index dbf07f6..4a1378a 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ ## [Unreleased] +- Add scan scope selector: Project, Diff (between two revisions or the local directory) and File +- Increase required CLI version to 3.25.0 - Update extension icon to the new Cycode brand logo ## [3.1.1] - 2026-08-30 diff --git a/README.md b/README.md index 5845316..c194a97 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ The extension provides functionalities such as: * Company’s Custom Remediation Guidelines - If your company has set custom remediation guidelines via the Cycode portal, you'll see a field for "Company Guidelines" that contains those guidelines. * Running a new scan from your IDE even before committing the code. * Triggering a scan automatically whenever a file is saved. +* Choosing the scan scope: the whole project, only the changes between two revisions (Diff), or the open file. * Highlighting vulnerable code in the editor - syntax highlighting for Cycode-specific code and configuration files, making it easy for users to identify and work with these files in their projects. * Removing a detected secret or ignoring it by secret value, rule (type) or by path. @@ -82,6 +83,24 @@ To use the Cycode IntelliJ Platform Plugin, follow these steps: 4. Also applies for auto-save. 5. Wait for the scan to complete and to display a success message. +### Scan Scope + +In the Cycode tool window, choose what the scan buttons and **Scan all** run on: + +* **Project** - scans the entire project. +* **Diff** - scans only what changed. Pick two revisions in **From** and **To** (HEAD, branches, tags or recent + commits), or choose **Local directory** on one side to include your uncommitted changes. The default is + Local directory compared with HEAD. Two different revisions are required. + * Scanning only the changes is faster, but vulnerabilities that need the surrounding code may be less accurate. + * Infrastructure As Code scans do not support diffs and always scan the full project. + * The project must be inside a Git repository (otherwise Diff is disabled). Diff needs Cycode CLI 3.25.0 or later: + with a custom CLI that is older, the plugin shows one notification asking you to upgrade it or to turn + automatic CLI management back on. +* **File** - scans only the file open in the editor. Package vulnerability and Infrastructure As Code scans only run + for the file types they support. + +The scope is remembered for each project between sessions. The selected revisions are kept for the current session only. + ## Viewing Scan Results ### Handling Detected Secrets diff --git a/settings.gradle.kts b/settings.gradle.kts index 9060895..99b4c22 100755 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,5 +1,5 @@ rootProject.name = "Cycode plugin for IntelliJ Platform" plugins { - id("org.gradle.toolchains.foojay-resolver-convention") version("0.7.0") + id("org.gradle.toolchains.foojay-resolver-convention") version("1.0.0") } diff --git a/src/main/kotlin/com/cycode/plugin/Consts.kt b/src/main/kotlin/com/cycode/plugin/Consts.kt index 03efcaa..57783d1 100644 --- a/src/main/kotlin/com/cycode/plugin/Consts.kt +++ b/src/main/kotlin/com/cycode/plugin/Consts.kt @@ -20,7 +20,7 @@ class Consts { companion object { val PLUGIN_PATH = PathManager.getPluginsPath() + "/cycode-intellij-platform-plugin" val DEFAULT_CLI_PATH = getDefaultCliPath() - const val REQUIRED_CLI_VERSION = "3.21.0" + const val REQUIRED_CLI_VERSION = "3.25.0" const val CYCODE_DOMAIN = "cycode.com" diff --git a/src/main/kotlin/com/cycode/plugin/cli/DiffScan.kt b/src/main/kotlin/com/cycode/plugin/cli/DiffScan.kt new file mode 100644 index 0000000..a974182 --- /dev/null +++ b/src/main/kotlin/com/cycode/plugin/cli/DiffScan.kt @@ -0,0 +1,42 @@ +package com.cycode.plugin.cli + +enum class ScanScope { + Project, Diff, File +} + +enum class DiffScanMode { + CommitRange, LocalDiff +} + +/** Describes what a single CLI scan invocation should scan. */ +sealed class ScanTarget { + data class Paths(val paths: List) : ScanTarget() + data class Diff(val mode: DiffScanMode, val ref: String, val path: String) : ScanTarget() +} + +fun ScanTarget.toCliArgs(): Array = when (this) { + is ScanTarget.Paths -> arrayOf("path", *paths.toTypedArray()) + is ScanTarget.Diff -> getDiffScanArgs(mode, ref, path) +} + +// IaC is not supported by the CLI's commit-history and pre-commit diff flavours +fun supportsDiffScan(scanType: CliScanType): Boolean = scanType != CliScanType.Iac + +fun getDiffScanArgs(mode: DiffScanMode, ref: String, path: String): Array { + assertSafeRefArg(ref) + + return when (mode) { + DiffScanMode.CommitRange -> arrayOf("commit-history", "--commit-range", ref, path) + DiffScanMode.LocalDiff -> arrayOf("pre-commit", "--include-unstaged", "--base-ref", ref, "--path", path) + } +} + +/** + * Refs are passed to git and the CLI as separate arguments (no shell), but a value like "--output=x" + * would still be parsed as an option. Reject those and anything containing control characters. + */ +fun assertSafeRefArg(ref: String) { + require(isSafeRefArg(ref)) { "Unsafe revision: must be non-empty, not start with '-' and have no control characters" } +} + +fun isSafeRefArg(ref: String): Boolean = ref.isNotEmpty() && !ref.startsWith("-") && ref.none { it.isISOControl() } diff --git a/src/main/kotlin/com/cycode/plugin/cli/Helpers.kt b/src/main/kotlin/com/cycode/plugin/cli/Helpers.kt index 498eafe..adea8c6 100644 --- a/src/main/kotlin/com/cycode/plugin/cli/Helpers.kt +++ b/src/main/kotlin/com/cycode/plugin/cli/Helpers.kt @@ -102,6 +102,19 @@ fun isSupportedLockFile(filename: String): Boolean { return false } +fun isFileSupportedByScanType(filePath: String, scanType: CliScanType): Boolean { + return when (scanType) { + CliScanType.Sca -> isSupportedPackageFile(filePath) + CliScanType.Iac -> isSupportedIacFile(filePath) + else -> true + } +} + +/** Splits [scanTypes] (keeping their order) into the ones that can scan the file and the ones that cannot. */ +fun partitionByFileSupport(filePath: String, scanTypes: List): Pair, List> { + return scanTypes.partition { isFileSupportedByScanType(filePath, it) } +} + fun getPackageFileForLockFile(filename: String): String { val lowercaseFilename = filename.lowercase() return SCA_CONFIGURATION_SCAN_LOCK_FILE_TO_PACKAGE_FILE.getOrDefault(lowercaseFilename, "package") diff --git a/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/cycodeActionToolBar/actions/RunAllAction.kt b/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/cycodeActionToolBar/actions/RunAllAction.kt index 8509bc4..0e098a5 100644 --- a/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/cycodeActionToolBar/actions/RunAllAction.kt +++ b/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/cycodeActionToolBar/actions/RunAllAction.kt @@ -1,9 +1,8 @@ package com.cycode.plugin.components.toolWindow.components.cycodeActionToolBar.actions import com.cycode.plugin.CycodeBundle -import com.cycode.plugin.cli.CliScanType -import com.cycode.plugin.services.cycode import com.cycode.plugin.services.pluginLocalState +import com.cycode.plugin.services.scanScope import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent @@ -26,21 +25,7 @@ class RunAllAction : // TODO(MarshalX): we should tracks all running scans and use pub-sub messaging to update UI // we can provide "stop" action only after that val project = e.project ?: return - val service = cycode(project) - val pluginLocalState = pluginLocalState(project) - - if (pluginLocalState.isSecretScanningEnabled) { - service.startScanForCurrentProject(CliScanType.Secret) - } - if (pluginLocalState.isScaScanningEnabled) { - service.startScanForCurrentProject(CliScanType.Sca) - } - if (pluginLocalState.isIacScanningEnabled) { - service.startScanForCurrentProject(CliScanType.Iac) - } - if (pluginLocalState.isSastScanningEnabled) { - service.startScanForCurrentProject(CliScanType.Sast) - } + scanScope(project).startAllScansForCurrentScope() } override fun update(e: AnActionEvent) { diff --git a/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/scanContentTab/ScanContentTab.kt b/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/scanContentTab/ScanContentTab.kt index b3b0d1d..ea610f2 100644 --- a/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/scanContentTab/ScanContentTab.kt +++ b/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/scanContentTab/ScanContentTab.kt @@ -2,16 +2,34 @@ package com.cycode.plugin.components.toolWindow.components.scanContentTab import com.cycode.plugin.CycodeBundle import com.cycode.plugin.cli.CliScanType +import com.cycode.plugin.cli.ScanScope import com.cycode.plugin.components.Component import com.cycode.plugin.components.common.createClickableLabel +import com.cycode.plugin.components.toolWindow.updateToolWindowState +import com.cycode.plugin.git.HEAD_REF +import com.cycode.plugin.git.DiffSide +import com.cycode.plugin.git.RefOption import com.cycode.plugin.services.CycodeService +import com.cycode.plugin.services.CycodeTemporaryStateService +import com.cycode.plugin.services.diffRefs import com.cycode.plugin.services.pluginLocalState +import com.cycode.plugin.services.scanScope +import com.intellij.icons.AllIcons +import com.intellij.openapi.ui.ComboBox +import com.intellij.ui.SimpleListCellRenderer +import com.intellij.ui.components.JBLabel +import com.intellij.ui.components.JBRadioButton import com.intellij.util.ui.JBUI +import java.awt.FlowLayout import java.awt.GridBagConstraints import java.awt.GridBagLayout +import javax.swing.Box +import javax.swing.ButtonGroup +import javax.swing.DefaultComboBoxModel import javax.swing.JButton import javax.swing.JComponent import javax.swing.JPanel +import javax.swing.SwingConstants class ScanContentTab : Component() { private val panel = JPanel(GridBagLayout()) @@ -21,6 +39,7 @@ class ScanContentTab : Component() { anchor = GridBagConstraints.NORTHWEST fill = GridBagConstraints.HORIZONTAL } + private var updatingCombos = false private fun addComponentToPanel(component: JComponent) { gbc.gridy++ @@ -32,34 +51,138 @@ class ScanContentTab : Component() { val pluginLocalState = pluginLocalState(service.project) addComponentToPanel(createClickableLabel(CycodeBundle.message("scanTabTitleLabel"))) - addComponentToPanel( - JButton(CycodeBundle.message("scanTabSecretsBtn")).apply { - isEnabled = pluginLocalState.isSecretScanningEnabled - addActionListener { service.startScanForCurrentProject(CliScanType.Secret) } - }, - ) - addComponentToPanel( - JButton(CycodeBundle.message("scanTabScaBtn")).apply { - isEnabled = pluginLocalState.isScaScanningEnabled - addActionListener { service.startScanForCurrentProject(CliScanType.Sca) } - }, - ) - addComponentToPanel( - JButton(CycodeBundle.message("scanTabIacBtn")).apply { - isEnabled = pluginLocalState.isIacScanningEnabled - addActionListener { service.startScanForCurrentProject(CliScanType.Iac) } - }, - ) - addComponentToPanel( - JButton(CycodeBundle.message("scanTabSastBtn")).apply { - isEnabled = pluginLocalState.isSastScanningEnabled - addActionListener { service.startScanForCurrentProject(CliScanType.Sast) } - }, - ) + addScopeControls(service) + CycodeTemporaryStateService.SCAN_TYPES_IN_ORDER.forEach { scanType -> + addComponentToPanel(createScanButton(service, scanType, pluginLocalState.isScanTypeEnabled(scanType))) + } addComponentToPanel(createClickableLabel(CycodeBundle.message("scanTabOnSaveTip"))) addComponentToPanel(createClickableLabel(CycodeBundle.message("howToUseLabel"))) return panel } + + private fun createScanButton(service: CycodeService, scanType: CliScanType, enabled: Boolean): JButton { + val key = when (scanType) { + CliScanType.Secret -> "scanTabSecretsBtn" + CliScanType.Sca -> "scanTabScaBtn" + CliScanType.Iac -> "scanTabIacBtn" + CliScanType.Sast -> "scanTabSastBtn" + } + return JButton(CycodeBundle.message(key)).apply { + isEnabled = enabled + addActionListener { scanScope(service.project).startScanForCurrentScope(scanType) } + } + } + + private fun createNote(text: String, icon: javax.swing.Icon? = null): JBLabel { + return JBLabel("$text").apply { + setAllowAutoWrapping(true) + icon?.let { + this.icon = it + iconTextGap = JBUI.scale(6) + verticalTextPosition = SwingConstants.TOP + } + } + } + + private fun addScopeControls(service: CycodeService) { + val scopeService = scanScope(service.project) + val effectiveScope = scopeService.getEffectiveScanScope() + val diffRefs = diffRefs(service.project) + val isGitRepository = diffRefs.isGitRepository + + // Diff is disabled when this turns out not to be a git repository; the tab is rebuilt if that changes + diffRefs.refreshGitRepositoryState() + + addComponentToPanel(createClickableLabel(CycodeBundle.message("scanScopeLabel"))) + + val group = ButtonGroup() + val radioPanel = JPanel(FlowLayout(FlowLayout.LEFT, 0, 0)) + ScanScope.entries.forEach { scope -> + val radio = JBRadioButton(CycodeBundle.message("scanScope${scope.name}"), scope == effectiveScope).apply { + // Diff cannot work without a git repository + isEnabled = scope != ScanScope.Diff || isGitRepository != false + addActionListener { + if (scope != scopeService.getScanScope()) { + scopeService.setScanScope(scope) + updateToolWindowState(service.project) + } + } + } + group.add(radio) + radioPanel.add(radio) + radioPanel.add(Box.createHorizontalStrut(JBUI.scale(12))) + } + addComponentToPanel(radioPanel) + addComponentToPanel(createNote(CycodeBundle.message("scanScope${effectiveScope.name}Hint"))) + if (isGitRepository == false) { + addComponentToPanel(createNote(CycodeBundle.message("scanScopeDiffNoGitNote"), AllIcons.General.Warning)) + } + + if (effectiveScope != ScanScope.Diff) { + return + } + + val fromCombo = createRefCombo(service, true) + val toCombo = createRefCombo(service, false) + addComponentToPanel(JPanel(GridBagLayout()).apply { + val c = GridBagConstraints().apply { fill = GridBagConstraints.HORIZONTAL; gridy = 0 } + add(JBLabel(CycodeBundle.message("scanScopeDiffFromLabel")), c.apply { gridx = 0; weightx = 0.0 }) + add(fromCombo, c.apply { gridx = 1; weightx = 1.0; insets = JBUI.insets(0, 4, 0, 8) }) + add(JBLabel(CycodeBundle.message("scanScopeDiffToLabel")), c.apply { gridx = 2; weightx = 0.0; insets = JBUI.emptyInsets() }) + add(toCombo, c.apply { gridx = 3; weightx = 1.0; insets = JBUI.insetsLeft(4) }) + }) + addComponentToPanel(createNote(CycodeBundle.message("scanScopeDiffIacNote"), AllIcons.General.Warning)) + + // lists are reloaded in the background and the combos updated in place (never while a popup is open) + diffRefs.refresh { + populateCombo(fromCombo, true, diffRefs.from, diffRefs.refs) + populateCombo(toCombo, false, diffRefs.to, diffRefs.refs) + } + } + + /** A combo entry: the local directory or a revision. */ + private class SideOption(val side: DiffSide, val label: String) { + override fun toString() = label + } + + private fun createRefCombo(service: CycodeService, isFrom: Boolean): ComboBox { + val diffRefs = diffRefs(service.project) + return ComboBox().apply { + // long labels are truncated instead of widening the tool window + setMinimumAndPreferredWidth(JBUI.scale(REF_COMBO_WIDTH)) + maximumRowCount = REF_COMBO_VISIBLE_ROWS + renderer = SimpleListCellRenderer.create("") { it.label } + populateCombo(this, isFrom, if (isFrom) diffRefs.from else diffRefs.to, diffRefs.refs) + addActionListener { + if (updatingCombos) return@addActionListener + val selected = (selectedItem as? SideOption)?.side ?: return@addActionListener + if (isFrom) diffRefs.setSides(selected, diffRefs.to) else diffRefs.setSides(diffRefs.from, selected) + } + } + } + + private fun populateCombo(combo: ComboBox, isFrom: Boolean, selected: DiffSide, known: List) { + // replacing the model closes an open popup + if (combo.isPopupVisible) return + + val refs = known.ifEmpty { listOf(RefOption(HEAD_REF, HEAD_REF)) } + val items = listOf(SideOption(DiffSide.Local, CycodeBundle.message("scanScopeDiffLocalDirectory"))) + + refs.map { SideOption(DiffSide.Rev(it.value), it.label) } + + updatingCombos = true + try { + combo.model = DefaultComboBoxModel(items.toTypedArray()) + combo.selectedItem = items.firstOrNull { it.side == selected } + ?: items.first { it.side == if (isFrom) DiffSide.Local else DiffSide.Rev(HEAD_REF) } + } finally { + updatingCombos = false + } + } + + companion object { + private const val REF_COMBO_WIDTH = 110 + private const val REF_COMBO_VISIBLE_ROWS = 12 + } } diff --git a/src/main/kotlin/com/cycode/plugin/git/DiffScanPlanner.kt b/src/main/kotlin/com/cycode/plugin/git/DiffScanPlanner.kt new file mode 100644 index 0000000..88fc53c --- /dev/null +++ b/src/main/kotlin/com/cycode/plugin/git/DiffScanPlanner.kt @@ -0,0 +1,49 @@ +package com.cycode.plugin.git + +import com.cycode.plugin.cli.CliScanType +import com.cycode.plugin.cli.DiffScanMode +import com.cycode.plugin.cli.ScanTarget +import com.cycode.plugin.cli.supportsDiffScan + +sealed class DiffScanPlan { + data class Run(val target: ScanTarget) : DiffScanPlan() + + /** The scan must not start; [messageKey] is the bundle key of the message to show. */ + data class Refused(val messageKey: String) : DiffScanPlan() +} + +/** + * Decides what a diff scan of [scanType] should run, without touching the IDE. Runs git, so call it on a + * background thread. + */ +fun planDiffScan(scanType: CliScanType, from: DiffSide, to: DiffSide, projectRoot: String, git: GitCli): DiffScanPlan { + if (from == to) { + return DiffScanPlan.Refused("diffSameRevisionNotification") + } + + // IaC does not support diffs in the CLI: run it as a normal project scan + if (!supportsDiffScan(scanType)) { + return DiffScanPlan.Run(ScanTarget.Paths(listOf(projectRoot))) + } + + if (!git.isGitRepository()) { + return DiffScanPlan.Refused("diffNotGitRepositoryNotification") + } + + if (from is DiffSide.Local || to is DiffSide.Local) { + val rev = (if (from is DiffSide.Local) to else from) as DiffSide.Rev + return DiffScanPlan.Run(ScanTarget.Diff(DiffScanMode.LocalDiff, rev.ref, projectRoot)) + } + + // both sides are revisions here (two local sides were caught by the equality check above) + from as DiffSide.Rev + to as DiffSide.Rev + return when (val result = git.getCommitRange(from, to)) { + is CommitRangeResult.Range -> DiffScanPlan.Run(ScanTarget.Diff(DiffScanMode.CommitRange, result.range, projectRoot)) + CommitRangeResult.SameCommit -> DiffScanPlan.Refused("diffSameCommitNotification") + CommitRangeResult.NoCommonHistory -> DiffScanPlan.Refused("diffNoCommonHistoryNotification") + CommitRangeResult.UnknownRevision -> DiffScanPlan.Refused("diffUnknownRevisionNotification") + CommitRangeResult.NotARepository -> DiffScanPlan.Refused("diffNotGitRepositoryNotification") + CommitRangeResult.GitFailure -> DiffScanPlan.Refused("diffGitFailureNotification") + } +} diff --git a/src/main/kotlin/com/cycode/plugin/git/DiffSide.kt b/src/main/kotlin/com/cycode/plugin/git/DiffSide.kt new file mode 100644 index 0000000..e33afb1 --- /dev/null +++ b/src/main/kotlin/com/cycode/plugin/git/DiffSide.kt @@ -0,0 +1,15 @@ +package com.cycode.plugin.git + +import com.cycode.plugin.cli.assertSafeRefArg + +/** One side of a diff scan: the local directory (uncommitted changes) or a revision (branch, tag or commit). */ +sealed interface DiffSide { + object Local : DiffSide + + /** The only place a revision enters the model: an unsafe value (e.g. `--output=x`) can never get further. */ + data class Rev(val ref: String) : DiffSide { + init { + assertSafeRefArg(ref) + } + } +} diff --git a/src/main/kotlin/com/cycode/plugin/git/GitCli.kt b/src/main/kotlin/com/cycode/plugin/git/GitCli.kt new file mode 100644 index 0000000..bca9bfc --- /dev/null +++ b/src/main/kotlin/com/cycode/plugin/git/GitCli.kt @@ -0,0 +1,181 @@ +package com.cycode.plugin.git + +import com.cycode.plugin.cli.isSafeRefArg +import com.intellij.execution.configurations.GeneralCommandLine +import com.intellij.execution.process.CapturingProcessHandler +import com.intellij.openapi.diagnostic.thisLogger +import java.io.File +import java.nio.charset.StandardCharsets + +const val HEAD_REF = "HEAD" +const val LABEL_SEPARATOR = " │ " + +/** [value] is what gets passed to git/CLI; [label] is what the user sees. */ +data class RefOption(val value: String, val label: String) { + override fun toString() = label +} + +sealed class CommitRangeResult { + data class Range(val range: String) : CommitRangeResult() + object SameCommit : CommitRangeResult() + object NoCommonHistory : CommitRangeResult() + object UnknownRevision : CommitRangeResult() + object NotARepository : CommitRangeResult() + object GitFailure : CommitRangeResult() +} + +data class GitOutput(val exitCode: Int, val stdout: String, val stderr: String) + +/** + * Thin wrapper over the git executable. Always run on a background thread. + * Git is invoked with an argv list (never a shell string); exit codes keep their git semantics + * because the user-facing messages depend on them. + */ +class GitCli(private val workDirectory: String) { + fun run(vararg args: String): GitOutput? { + return try { + val commandLine = GeneralCommandLine("git") + .withParameters(*args) + .withWorkDirectory(File(workDirectory)) + .withCharset(StandardCharsets.UTF_8) + val output = CapturingProcessHandler(commandLine).runProcess(GIT_TIMEOUT_MS) + if (output.isTimeout || output.isCancelled) { + thisLogger().warn("git ${args.joinToString(" ")} timed out or was cancelled") + return null + } + GitOutput(output.exitCode, output.stdout.trim(), output.stderr.trim()) + } catch (e: Exception) { + // git is missing or could not be started + thisLogger().warn("Failed to run git ${args.joinToString(" ")}", e) + null + } + } + + fun isGitAvailable(): Boolean { + val output = run("--version") + return output != null && output.exitCode == 0 + } + + /** Only an explicit "not a git repository" answer returns false; other failures are left to later steps. */ + fun isGitRepository(): Boolean { + val output = run("rev-parse", "--is-inside-work-tree") ?: return true + if (output.exitCode == 0) { + return output.stdout == "true" + } + + return !output.stderr.contains("not a git repository", ignoreCase = true) + } + + private fun resolveCommit(rev: String): Pair { + val output = run("rev-parse", "--verify", "--quiet", "$rev^{commit}") + return when { + output == null -> null to CommitRangeResult.GitFailure + output.exitCode == 0 -> output.stdout to null + output.exitCode == 1 -> null to CommitRangeResult.UnknownRevision + output.stderr.contains("not a git repository", ignoreCase = true) -> + null to CommitRangeResult.NotARepository + + else -> null to CommitRangeResult.GitFailure + } + } + + /** + * Resolves a "what did [to] add relative to [from]" range as `..` of full SHAs. + * Plain `from..to` is empty when picked newest-first, and `from...to` would also scan commits + * that landed on the other branch since divergence. + */ + fun getCommitRange(from: DiffSide.Rev, to: DiffSide.Rev): CommitRangeResult { + val (fromSha, fromError) = resolveCommit(from.ref) + if (fromSha == null) return fromError!! + val (toSha, toError) = resolveCommit(to.ref) + if (toSha == null) return toError!! + + if (fromSha == toSha) { + return CommitRangeResult.SameCommit + } + + val mergeBase = run("merge-base", fromSha, toSha) + ?: return CommitRangeResult.GitFailure + if (mergeBase.exitCode == 1) { + return CommitRangeResult.NoCommonHistory + } + if (mergeBase.exitCode != 0 || mergeBase.stdout.isEmpty()) { + return CommitRangeResult.GitFailure + } + + val base = mergeBase.stdout + // "to" is an ancestor of "from": the user picked newest-first + return if (base == toSha) { + CommitRangeResult.Range("$toSha..$fromSha") + } else { + CommitRangeResult.Range("$base..$toSha") + } + } + + /** + * HEAD first, then branches/tags, then recent commits, plus any [pinnedRefs] (the user's selection) + * that scrolled out of the lists but still resolve. The caps are deliberate for now. + */ + fun getAvailableRefs(pinnedRefs: List = emptyList()): List { + val options = mutableListOf() + val listedValues = mutableSetOf() + val listedShas = mutableSetOf() + + fun add(option: RefOption, sha: String? = null) { + if (listedValues.add(option.value)) { + options.add(option) + sha?.let { listedShas.add(it) } + } + } + + add(RefOption(HEAD_REF, HEAD_REF)) + + val branchOutput = run("rev-parse", "--abbrev-ref", "HEAD") + val currentBranch = branchOutput?.takeIf { it.exitCode == 0 && it.stdout != HEAD_REF }?.stdout + + val refs = run( + "for-each-ref", "--sort=-committerdate", "--count=$MAX_REFS", + "--format=%(refname:short)%09%(objectname)%09%(objectname:short)%09%(contents:subject)", + "refs/heads", "refs/tags", "refs/remotes" + ) + if (refs != null && refs.exitCode == 0) { + for (line in refs.stdout.lines().filter { it.isNotBlank() }) { + val parts = line.split("\t", limit = 4) + if (parts.size < 3 || parts[0].endsWith("/HEAD") || !isSafeRefArg(parts[0])) continue + add(RefOption(parts[0], buildLabel(parts[0], parts[2], parts.getOrElse(3) { "" })), parts[1]) + } + } + + val log = run("log", "-n", "$MAX_COMMITS", "--format=%H%x09%h%x09%s") + if (log != null && log.exitCode == 0) { + for (line in log.stdout.lines().filter { it.isNotBlank() }) { + val parts = line.split("\t", limit = 3) + // a commit that is also a branch/tag tip is listed once, under the ref name + if (parts.size < 2 || parts[0] in listedShas) continue + // every commit of `git log` is an ancestor of HEAD, so labelling it with the current branch is accurate + add(RefOption(parts[0], buildLabel(currentBranch, parts[1], parts.getOrElse(2) { "" }))) + } + } + + for ((pinned) in pinnedRefs) { + if (pinned in listedValues) continue + val (sha, _) = resolveCommit(pinned) + if (sha == null) continue + val subject = run("log", "-n", "1", "--format=%h%x09%s", sha)?.stdout?.split("\t", limit = 2) + add(RefOption(pinned, buildLabel(pinned, subject?.getOrNull(0) ?: sha.take(7), subject?.getOrNull(1) ?: ""))) + } + + return options + } + + companion object { + const val MAX_REFS = 20 + const val MAX_COMMITS = 20 + private const val GIT_TIMEOUT_MS = 30_000 + + fun buildLabel(refName: String?, shortHash: String, subject: String): String { + return listOfNotNull(refName?.takeIf { it.isNotEmpty() }, shortHash, subject.takeIf { it.isNotEmpty() }) + .joinToString(LABEL_SEPARATOR) + } + } +} diff --git a/src/main/kotlin/com/cycode/plugin/listeners/FileSaveListener.kt b/src/main/kotlin/com/cycode/plugin/listeners/FileSaveListener.kt index b156e32..abc2fa8 100644 --- a/src/main/kotlin/com/cycode/plugin/listeners/FileSaveListener.kt +++ b/src/main/kotlin/com/cycode/plugin/listeners/FileSaveListener.kt @@ -37,17 +37,17 @@ class FileSaveListener(private val project: Project) : FileDocumentManagerListen return } - if (pluginLocalState.isSecretScanningEnabled && pathsToScan.isNotEmpty()) { + if (pluginLocalState.isScanTypeEnabled(CliScanType.Secret) && pathsToScan.isNotEmpty()) { service.startScan(CliScanType.Secret, pathsToScan, onDemand = false) } val scaPathsToScan = excludeNonScaRelatedPaths(pathsToScan) - if (pluginLocalState.isScaScanningEnabled && scaPathsToScan.isNotEmpty()) { + if (pluginLocalState.isScanTypeEnabled(CliScanType.Sca) && scaPathsToScan.isNotEmpty()) { service.startScan(CliScanType.Sca, scaPathsToScan, onDemand = false) } val iacPathsToScan = excludeNonIacRelatedPaths(pathsToScan) - if (pluginLocalState.isIacScanningEnabled && iacPathsToScan.isNotEmpty()) { + if (pluginLocalState.isScanTypeEnabled(CliScanType.Iac) && iacPathsToScan.isNotEmpty()) { service.startScan(CliScanType.Iac, iacPathsToScan, onDemand = false) } } diff --git a/src/main/kotlin/com/cycode/plugin/services/CliService.kt b/src/main/kotlin/com/cycode/plugin/services/CliService.kt index 7660b0a..3f6bd3d 100644 --- a/src/main/kotlin/com/cycode/plugin/services/CliService.kt +++ b/src/main/kotlin/com/cycode/plugin/services/CliService.kt @@ -1,5 +1,6 @@ package com.cycode.plugin.services +import com.cycode.plugin.Consts import com.cycode.plugin.CycodeBundle import com.cycode.plugin.cli.* import com.cycode.plugin.cli.models.AiRemediationResult @@ -20,6 +21,7 @@ import com.intellij.openapi.components.Service import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project +import com.intellij.util.text.VersionComparatorUtil typealias TaskCancelledCallback = (() -> Boolean)? @@ -30,6 +32,7 @@ class CliService(private val project: Project) { private val pluginLocalState = pluginLocalState(project) private val scanResults = scanResults(project) private val cli = CliWrapper(getProjectRootDirectory()) + private var outdatedCliNotified = false fun getProjectRootDirectory(): String? { val modules = ModuleManager.getInstance(project).modules @@ -112,9 +115,26 @@ class CliService(private val project: Project) { showErrorNotification(CycodeBundle.message("checkAuthErrorNotification")) } + notifyIfCustomCliIsOutdated(processedResult.result.version) + return } + /** A plugin-managed CLI is always at the required version; a user-provided one may be older. */ + private fun notifyIfCustomCliIsOutdated(version: String) { + if (pluginSettings().cliAutoManaged || outdatedCliNotified) { + return + } + + if (VersionComparatorUtil.compare(version, Consts.REQUIRED_CLI_VERSION) < 0) { + outdatedCliNotified = true + CycodeNotifier.notifyInfo( + project, + CycodeBundle.message("customCliOutdatedNotification", Consts.REQUIRED_CLI_VERSION) + ) + } + } + fun startAuth(cancelledCallback: TaskCancelledCallback = null): Boolean { val result: CliResult = cli.executeCommand( @@ -179,8 +199,8 @@ class CliService(private val project: Project) { return options.toTypedArray() } - private inline fun scanPaths( - paths: List, + private inline fun runScan( + target: ScanTarget, scanType: CliScanType, noinline cancelledCallback: TaskCancelledCallback = null ): CliResult? { @@ -191,26 +211,35 @@ class CliService(private val project: Project) { "-t", scanTypeString, *getCliScanOptions(scanType), - "path", - *getPathsAsArguments(paths), + *target.toCliArgs(), cancelledCallback = cancelledCallback ) return processResult(result) } - private fun getPathsAsArguments(paths: List): Array { - return paths.toTypedArray() - } - - fun scanPathsSecrets( - paths: List, + /** + * One runner for every kind of scan (paths, commit range, local diff). + * Do not add one method per mode. + */ + fun scan( + scanType: CliScanType, + target: ScanTarget, onDemand: Boolean = true, cancelledCallback: TaskCancelledCallback = null ) { - val results = scanPaths(paths, CliScanType.Secret, cancelledCallback) + when (scanType) { + CliScanType.Secret -> scanSecrets(target, onDemand, cancelledCallback) + CliScanType.Sca -> scanSca(target, onDemand, cancelledCallback) + CliScanType.Iac -> scanIac(target, onDemand, cancelledCallback) + CliScanType.Sast -> scanSast(target, onDemand, cancelledCallback) + } + } + + private fun scanSecrets(target: ScanTarget, onDemand: Boolean, cancelledCallback: TaskCancelledCallback) { + val results = runScan(target, CliScanType.Secret, cancelledCallback) if (results == null) { - thisLogger().warn("Failed to scan Secret paths: $paths") + thisLogger().warn("Failed to scan Secret: $target") return } @@ -225,10 +254,10 @@ class CliService(private val project: Project) { rerunAnnotators() } - fun scanPathsSca(paths: List, onDemand: Boolean = true, cancelledCallback: TaskCancelledCallback = null) { - val results = scanPaths(paths, CliScanType.Sca, cancelledCallback) + private fun scanSca(target: ScanTarget, onDemand: Boolean, cancelledCallback: TaskCancelledCallback) { + val results = runScan(target, CliScanType.Sca, cancelledCallback) if (results == null) { - thisLogger().warn("Failed to scan SCA paths: $paths") + thisLogger().warn("Failed to scan SCA: $target") return } @@ -255,10 +284,10 @@ class CliService(private val project: Project) { } } - fun scanPathsIac(paths: List, onDemand: Boolean = true, cancelledCallback: TaskCancelledCallback = null) { - var results = scanPaths(paths, CliScanType.Iac, cancelledCallback) + private fun scanIac(target: ScanTarget, onDemand: Boolean, cancelledCallback: TaskCancelledCallback) { + var results = runScan(target, CliScanType.Iac, cancelledCallback) if (results == null) { - thisLogger().warn("Failed to IaC scan paths: $paths") + thisLogger().warn("Failed to IaC scan: $target") return } @@ -281,10 +310,10 @@ class CliService(private val project: Project) { rerunAnnotators() } - fun scanPathsSast(paths: List, onDemand: Boolean = true, cancelledCallback: TaskCancelledCallback = null) { - val results = scanPaths(paths, CliScanType.Sast, cancelledCallback) + private fun scanSast(target: ScanTarget, onDemand: Boolean, cancelledCallback: TaskCancelledCallback) { + val results = runScan(target, CliScanType.Sast, cancelledCallback) if (results == null) { - thisLogger().warn("Failed to SAST scan paths: $paths") + thisLogger().warn("Failed to SAST scan: $target") return } diff --git a/src/main/kotlin/com/cycode/plugin/services/CycodeProjectStateService.kt b/src/main/kotlin/com/cycode/plugin/services/CycodeProjectStateService.kt new file mode 100644 index 0000000..9b6bcc6 --- /dev/null +++ b/src/main/kotlin/com/cycode/plugin/services/CycodeProjectStateService.kt @@ -0,0 +1,24 @@ +package com.cycode.plugin.services + +import com.cycode.plugin.cli.ScanScope +import com.intellij.openapi.components.PersistentStateComponent +import com.intellij.openapi.components.Service +import com.intellij.openapi.components.State +import com.intellij.openapi.components.Storage +import com.intellij.openapi.components.StoragePathMacros +import com.intellij.util.xmlb.XmlSerializerUtil + +/** Settings that belong to one project; stored in the project's workspace file (not shared through VCS). */ +@Service(Service.Level.PROJECT) +@State(name = "CycodeProjectStateService", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)]) +class CycodeProjectStateService : PersistentStateComponent { + var scanScope: String = ScanScope.Project.name + + override fun getState(): CycodeProjectStateService { + return this + } + + override fun loadState(state: CycodeProjectStateService) { + XmlSerializerUtil.copyBean(state, this) + } +} diff --git a/src/main/kotlin/com/cycode/plugin/services/CycodeService.kt b/src/main/kotlin/com/cycode/plugin/services/CycodeService.kt index a8fcd80..64b3ed9 100755 --- a/src/main/kotlin/com/cycode/plugin/services/CycodeService.kt +++ b/src/main/kotlin/com/cycode/plugin/services/CycodeService.kt @@ -1,8 +1,7 @@ package com.cycode.plugin.services import com.cycode.plugin.CycodeBundle -import com.cycode.plugin.cli.CliIgnoreType -import com.cycode.plugin.cli.CliScanType +import com.cycode.plugin.cli.* import com.cycode.plugin.cli.models.AiRemediationResultData import com.cycode.plugin.components.toolWindow.CycodeToolWindowFactory import com.cycode.plugin.components.toolWindow.updateToolWindowState @@ -83,23 +82,25 @@ class CycodeService(val project: Project) : Disposable { } fun startScan(scanType: CliScanType, pathsToScan: List, onDemand: Boolean = true) { + startScan(scanType, onDemand) { ScanTarget.Paths(pathsToScan) } + } + + /** + * [resolveTarget] runs on the background thread once the scan is allowed to start; null means there is nothing + * to scan (the resolver has already told the user why). + */ + fun startScan(scanType: CliScanType, onDemand: Boolean = true, resolveTarget: () -> ScanTarget?) { runBackgroundTask(getBackgroundScanningLabel(scanType)) { indicator -> if (!pluginLocalState.cliAuthed) { CycodeNotifier.notifyInfo(project, CycodeBundle.message("authorizationRequiredNotification")) return@runBackgroundTask } - thisLogger().debug("[$scanType] Start scanning paths: $pathsToScan") - - val cancelledCallback = { indicator.isCanceled } - when (scanType) { - CliScanType.Secret -> cliService.scanPathsSecrets(pathsToScan, onDemand, cancelledCallback) - CliScanType.Sca -> cliService.scanPathsSca(pathsToScan, onDemand, cancelledCallback) - CliScanType.Iac -> cliService.scanPathsIac(pathsToScan, onDemand, cancelledCallback) - CliScanType.Sast -> cliService.scanPathsSast(pathsToScan, onDemand, cancelledCallback) - } + val target = resolveTarget() ?: return@runBackgroundTask - thisLogger().debug("[$scanType] Finish scanning paths: $pathsToScan") + thisLogger().debug("[$scanType] Start scanning: $target") + cliService.scan(scanType, target, onDemand) { indicator.isCanceled } + thisLogger().debug("[$scanType] Finish scanning: $target") } } diff --git a/src/main/kotlin/com/cycode/plugin/services/CycodeTemporaryStateService.kt b/src/main/kotlin/com/cycode/plugin/services/CycodeTemporaryStateService.kt index ad641c7..c603ea5 100755 --- a/src/main/kotlin/com/cycode/plugin/services/CycodeTemporaryStateService.kt +++ b/src/main/kotlin/com/cycode/plugin/services/CycodeTemporaryStateService.kt @@ -1,5 +1,6 @@ package com.cycode.plugin.services +import com.cycode.plugin.cli.CliScanType import com.cycode.plugin.cli.models.StatusResult import com.intellij.openapi.components.Service import com.intellij.openapi.diagnostic.thisLogger @@ -27,10 +28,25 @@ class CycodeTemporaryStateService { val isSastScanningEnabled: Boolean get() = cliStatus?.supportedModules?.sastScanning == true + fun isScanTypeEnabled(type: CliScanType): Boolean = when (type) { + CliScanType.Secret -> isSecretScanningEnabled + CliScanType.Sca -> isScaScanningEnabled + CliScanType.Iac -> isIacScanningEnabled + CliScanType.Sast -> isSastScanningEnabled + } + + /** Scan types enabled for the tenant, in the order the scan buttons are shown. */ + val enabledScanTypes: List + get() = SCAN_TYPES_IN_ORDER.filter { isScanTypeEnabled(it) } + val isAiLargeLanguageModelEnabled: Boolean get() = cliStatus?.supportedModules?.aiLargeLanguageModel == true init { thisLogger().info("CycodeTemporaryStateService init") } + + companion object { + val SCAN_TYPES_IN_ORDER = listOf(CliScanType.Secret, CliScanType.Sca, CliScanType.Iac, CliScanType.Sast) + } } diff --git a/src/main/kotlin/com/cycode/plugin/services/DiffRefsService.kt b/src/main/kotlin/com/cycode/plugin/services/DiffRefsService.kt new file mode 100644 index 0000000..c5e25fd --- /dev/null +++ b/src/main/kotlin/com/cycode/plugin/services/DiffRefsService.kt @@ -0,0 +1,98 @@ +package com.cycode.plugin.services + +import com.cycode.plugin.CycodeBundle +import com.cycode.plugin.components.toolWindow.updateToolWindowState +import com.cycode.plugin.git.DiffSide +import com.cycode.plugin.git.GitCli +import com.cycode.plugin.git.HEAD_REF +import com.cycode.plugin.git.RefOption +import com.cycode.plugin.utils.CycodeNotifier +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.components.Service +import com.intellij.openapi.project.Project +import java.util.concurrent.atomic.AtomicLong + +/** + * Everything about git for the Diff scan scope: whether the project is a git repository, the two selected sides and + * the cached revision lists. All of it is per project and session-only. + */ +@Service(Service.Level.PROJECT) +class DiffRefsService(private val project: Project) { + private val cliService = cli(project) + private val refreshRequestId = AtomicLong() + + // per-repository and therefore session-only; persisting them globally leaks picks between projects + @Volatile + var from: DiffSide = DiffSide.Local + private set + + @Volatile + var to: DiffSide = DiffSide.Rev(HEAD_REF) + private set + + // rebuilt on every refresh: git is fast enough with the capped lists, and it picks up refs created elsewhere + @Volatile + var refs: List = emptyList() + private set + + // null until known; only an explicit "not a git repository" answer makes it false + @Volatile + var isGitRepository: Boolean? = null + private set + + // the "git is not available" message is shown once per session + @Volatile + private var gitUnavailableNotified = false + + fun setSides(from: DiffSide, to: DiffSide) { + this.from = from + this.to = to + } + + /** Checks in the background whether the project is a git repository; rebuilds the scan tab if that changed. */ + fun refreshGitRepositoryState() { + val projectRoot = cliService.getProjectRootDirectory() ?: return + + ApplicationManager.getApplication().executeOnPooledThread { + val isRepository = GitCli(projectRoot).isGitRepository() + if (!project.isDisposed && isRepository != isGitRepository) { + isGitRepository = isRepository + updateToolWindowState(project) + } + } + } + + /** + * Reloads the revision lists in the background and resets stale picks to the defaults. + * A request id drops results of superseded requests. + */ + fun refresh(onDone: (() -> Unit)? = null) { + val projectRoot = cliService.getProjectRootDirectory() ?: return + val requestId = refreshRequestId.incrementAndGet() + val pinned = listOf(from, to).filterIsInstance() + + ApplicationManager.getApplication().executeOnPooledThread { + val git = GitCli(projectRoot) + val refs = git.getAvailableRefs(pinned) + + // nothing but HEAD: git may be missing (a repository without commits would still answer --version) + if (refs.size <= 1 && !gitUnavailableNotified && !git.isGitAvailable()) { + gitUnavailableNotified = true + CycodeNotifier.notifyInfo(project, CycodeBundle.message("diffGitUnavailableNotification")) + } + + if (requestId != refreshRequestId.get() || project.isDisposed) { + return@executeOnPooledThread + } + + val known = refs.map { it.value }.toSet() + if (from is DiffSide.Rev && (from as DiffSide.Rev).ref !in known) from = DiffSide.Local + if (to is DiffSide.Rev && (to as DiffSide.Rev).ref !in known) to = DiffSide.Rev(HEAD_REF) + this.refs = refs + + if (onDone != null) { + ApplicationManager.getApplication().invokeLater({ onDone() }, project.disposed) + } + } + } +} diff --git a/src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt b/src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt new file mode 100644 index 0000000..cab3b0f --- /dev/null +++ b/src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt @@ -0,0 +1,109 @@ +package com.cycode.plugin.services + +import com.cycode.plugin.CycodeBundle +import com.cycode.plugin.cli.ScanScope +import com.cycode.plugin.cli.CliScanType +import com.cycode.plugin.cli.getScanTypeDisplayName +import com.cycode.plugin.cli.partitionByFileSupport +import com.cycode.plugin.git.DiffScanPlan +import com.cycode.plugin.git.GitCli +import com.cycode.plugin.git.planDiffScan +import com.cycode.plugin.utils.CycodeNotifier +import com.intellij.openapi.components.Service +import com.intellij.openapi.fileEditor.FileEditorManager +import com.intellij.openapi.project.Project + +/** + * The scan scope (Project / Diff / File): which scope is selected and starting scans for it. The git side of Diff + * (revisions, repository state) lives in [DiffRefsService]. + */ +@Service(Service.Level.PROJECT) +class ScanScopeService(private val project: Project) { + private val cliService = cli(project) + private val cycodeService = cycode(project) + private val pluginLocalState = pluginLocalState(project) + private val projectState = projectState(project) + private val diffRefs = diffRefs(project) + + fun getScanScope(): ScanScope { + return ScanScope.entries.firstOrNull { it.name == projectState.scanScope } ?: ScanScope.Project + } + + fun setScanScope(scope: ScanScope) { + projectState.scanScope = scope.name + if (scope == ScanScope.Diff) { + diffRefs.refresh() + } + } + + /** Diff needs a git repository. */ + fun isDiffScanAvailable(): Boolean = diffRefs.isGitRepository != false + + /** Without a git repository Diff behaves as Project. */ + fun getEffectiveScanScope(): ScanScope { + val scope = getScanScope() + return if (scope == ScanScope.Diff && !isDiffScanAvailable()) ScanScope.Project else scope + } + + /** + * Scans according to the selected scope. + */ + fun startScanForCurrentScope(scanType: CliScanType) { + when (getEffectiveScanScope()) { + ScanScope.Project -> cycodeService.startScanForCurrentProject(scanType) + ScanScope.File -> startFileScan(listOf(scanType)) + ScanScope.Diff -> startDiffScan(scanType) + } + } + + /** Runs every scan type enabled for the tenant, according to the selected scope. */ + fun startAllScansForCurrentScope() { + val scanTypes = pluginLocalState.enabledScanTypes + when (getEffectiveScanScope()) { + ScanScope.File -> startFileScan(scanTypes) + else -> scanTypes.forEach { startScanForCurrentScope(it) } + } + } + + private fun currentLocalFilePath(): String? { + val file = FileEditorManager.getInstance(project).selectedFiles.firstOrNull() + return file?.takeIf { it.isInLocalFileSystem }?.canonicalPath + } + + /** Scans the open file with the types that support it, with one combined message for the rest. */ + private fun startFileScan(scanTypes: List) { + val filePath = currentLocalFilePath() + if (filePath == null) { + CycodeNotifier.notifyInfo(project, CycodeBundle.message("noOpenFileErrorNotification")) + return + } + + val (supported, unsupported) = partitionByFileSupport(filePath, scanTypes) + supported.forEach { cycodeService.startScan(it, listOf(filePath)) } + if (unsupported.isNotEmpty()) { + val names = unsupported.joinToString(", ") { getScanTypeDisplayName(it) } + CycodeNotifier.notifyInfo(project, CycodeBundle.message("scanFileUnsupportedNotification", names)) + } + } + + private fun startDiffScan(scanType: CliScanType) { + val from = diffRefs.from + val to = diffRefs.to + + val projectRoot = cliService.getProjectRootDirectory() + if (projectRoot == null) { + CycodeNotifier.notifyInfo(project, CycodeBundle.message("noProjectRootErrorNotification")) + return + } + + cycodeService.startScan(scanType) { + when (val plan = planDiffScan(scanType, from, to, projectRoot, GitCli(projectRoot))) { + is DiffScanPlan.Run -> plan.target + is DiffScanPlan.Refused -> { + CycodeNotifier.notifyInfo(project, CycodeBundle.message(plan.messageKey)) + null + } + } + } + } +} diff --git a/src/main/kotlin/com/cycode/plugin/services/Services.kt b/src/main/kotlin/com/cycode/plugin/services/Services.kt index 4800f6a..88b4b7c 100644 --- a/src/main/kotlin/com/cycode/plugin/services/Services.kt +++ b/src/main/kotlin/com/cycode/plugin/services/Services.kt @@ -30,3 +30,9 @@ fun download(project: Project? = null): DownloadService = getCycodeService(proje fun githubReleases(project: Project? = null): GithubReleaseService = getCycodeService(project) fun cycode(project: Project? = null): CycodeService = getCycodeService(project) + +fun projectState(project: Project): CycodeProjectStateService = getCycodeService(project) + +fun scanScope(project: Project? = null): ScanScopeService = getCycodeService(project) + +fun diffRefs(project: Project): DiffRefsService = getCycodeService(project) diff --git a/src/main/resources/messages/CycodeBundle.properties b/src/main/resources/messages/CycodeBundle.properties index 5adb03c..c46cea5 100755 --- a/src/main/resources/messages/CycodeBundle.properties +++ b/src/main/resources/messages/CycodeBundle.properties @@ -26,6 +26,7 @@ violationCardIntentionText=Cycode: {0} ({1}) notificationGroupId=Cycode notificationTitle=Cycode checkAuthErrorNotification=You are not authenticated in Cycode. Please authenticate +customCliOutdatedNotification=The Cycode CLI you configured is older than the required version {0}. Some features may not work. Please upgrade it or enable automatic CLI management in the settings. authErrorNotification=Authentication failed. Please try again missingCStandardLibraryErrorNotification=Plugin requires C standard library (libc/glibc) to be installed. Please install it and restart the IDE. unknownErrorNotification=Unknown error occurred. Please try again @@ -34,6 +35,14 @@ noProjectRootErrorNotification=Cycode scans the project that is currently opened authorizationRequiredNotification=You are not authenticated in Cycode. Please authenticate scanFileResultNotification=Cycode has detected {0} {1} issues in your file. Check out your "Cycode" tab to analyze. scanFileNoResultNotification=No {0} issues were found. +scanFileUnsupportedNotification={0}: scanning is not supported for the open file. +diffSameRevisionNotification=Select two different revisions to compare. +diffSameCommitNotification=The selected revisions point to the same commit, so there is nothing to compare. +diffNoCommonHistoryNotification=The selected revisions have no common history, so they cannot be compared. +diffUnknownRevisionNotification=One of the selected revisions could not be found in the repository. Refresh the list and select it again. +diffNotGitRepositoryNotification=Diff scanning requires the project to be inside a Git repository. +diffGitUnavailableNotification=Git could not be run, so the list of revisions is limited. Check that Git is installed and available in the PATH. +diffGitFailureNotification=Could not compare the selected revisions. See the IDE log for details. aiRemediationNotAvailableNotification=AI remediation is not available for this detection openProblemsTabAction=Open "Cycode" tab # tool window @@ -58,6 +67,18 @@ loadingTabLoadingText=\ authBtn=Authenticate # scan content tab scanTabTitleLabel=Ready to scan. +scanScopeLabel=Scan scope: +scanScopeProject=Project +scanScopeDiff=Diff +scanScopeFile=File +scanScopeProjectHint=Scans the entire project. +scanScopeDiffHint=Compares the two selected revisions. Scanning only the changes is faster but may be less accurate. +scanScopeFileHint=Scans only the file open in the editor. +scanScopeDiffNoGitNote=Diff is disabled because the project is not inside a Git repository. +scanScopeDiffIacNote=Infrastructure As Code does not support diff scans and always scans the full project. +scanScopeDiffFromLabel=From: +scanScopeDiffToLabel=To: +scanScopeDiffLocalDirectory=Local directory scanTabOnSaveTip=To easily scan your edited files, enable Scan on Save in settings (enabled by default). scanTabSecretsBtn=Scan for hardcoded secrets scanTabScaBtn=Scan for package vulnerabilities @@ -137,4 +158,4 @@ toolbarHomeAction=Return to Home Screen toolbarFilterBySeverityAction=Filter by {0} severity toolbarClearAction=Clear results toolbarHelpAction=Open documentation -toolbarRunAllAction=Run all scans types for the entire project +toolbarRunAllAction=Run all scan types for the selected scope diff --git a/src/test/kotlin/com/cycode/plugin/DiffScanPlannerTest.kt b/src/test/kotlin/com/cycode/plugin/DiffScanPlannerTest.kt new file mode 100644 index 0000000..ba01949 --- /dev/null +++ b/src/test/kotlin/com/cycode/plugin/DiffScanPlannerTest.kt @@ -0,0 +1,105 @@ +package com.cycode.plugin + +import com.cycode.plugin.cli.CliScanType +import com.cycode.plugin.cli.DiffScanMode +import com.cycode.plugin.cli.ScanTarget +import com.cycode.plugin.git.DiffScanPlan +import com.cycode.plugin.git.GitCli +import com.cycode.plugin.git.DiffSide +import com.cycode.plugin.git.planDiffScan +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import java.io.File + +class DiffScanPlannerTest : GitTestBase() { + @Before + fun addBranchAndCommit() { + sh("branch", "other") + commit("b") + } + + // a side is either DiffSide.Local or the name of a revision + private fun side(value: Any): DiffSide = value as? DiffSide ?: DiffSide.Rev(value as String) + + private fun plan(type: CliScanType, from: Any, to: Any, repo: GitCli = git) = + planDiffScan(type, side(from), side(to), dir.path, repo) + + private val secret = CliScanType.Secret + + @Test + fun localDiffInBothOrders() { + val expected = DiffScanPlan.Run( + ScanTarget.Diff(DiffScanMode.LocalDiff, "main", dir.path) + ) + assertEquals(expected, plan(secret, DiffSide.Local, "main")) + assertEquals(expected, plan(secret, "main", DiffSide.Local)) + } + + @Test + fun commitRangeIsResolved() { + val plan = plan(secret, "other", "main") as DiffScanPlan.Run + val target = plan.target as ScanTarget.Diff + assertEquals(DiffScanMode.CommitRange, target.mode) + assertTrue(target.ref.matches(Regex("[0-9a-f]{40}\\.\\.[0-9a-f]{40}"))) + } + + @Test + fun iacFallsBackToFullScanEvenOutsideGit() { + val plain = createPlainDirectory() + try { + val expected = DiffScanPlan.Run(ScanTarget.Paths(listOf(dir.path))) + val iac = CliScanType.Iac + assertEquals(expected, plan(iac, DiffSide.Local, "main")) + assertEquals(expected, plan(iac, "other", "main", GitCli(plain.path))) + } finally { + plain.deleteRecursively() + } + } + + @Test + fun sameRevisionIsRefused() { + assertEquals(DiffScanPlan.Refused("diffSameRevisionNotification"), plan(secret, "main", "main")) + assertEquals( + DiffScanPlan.Refused("diffSameRevisionNotification"), + plan(secret, DiffSide.Local, DiffSide.Local) + ) + } + + @Test + fun gitProblemsAreReportedAndStartNoScan() { + assertEquals(DiffScanPlan.Refused("diffUnknownRevisionNotification"), plan(secret, "main", "nope")) + + val plain = createPlainDirectory() + try { + assertEquals( + DiffScanPlan.Refused("diffNotGitRepositoryNotification"), + plan(secret, DiffSide.Local, "main", GitCli(plain.path)) + ) + } finally { + plain.deleteRecursively() + } + } + + @Test + fun sameCommitUnderDifferentNamesIsRefused() { + assertEquals(DiffScanPlan.Refused("diffSameCommitNotification"), plan(secret, "main", "HEAD")) + } + + @Test + fun noCommonHistoryIsRefused() { + sh("checkout", "--orphan", "orphan") + File(dir, "o").writeText("o") + sh("add", "o") + sh("commit", "-m", "o") + assertEquals(DiffScanPlan.Refused("diffNoCommonHistoryNotification"), plan(secret, "main", "orphan")) + } + + @Test + fun everyDiffScanTypeGetsAPlan() { + CliScanType.entries.forEach { + assertTrue(plan(it, DiffSide.Local, "main") is DiffScanPlan.Run) + } + } +} diff --git a/src/test/kotlin/com/cycode/plugin/DiffScanTest.kt b/src/test/kotlin/com/cycode/plugin/DiffScanTest.kt new file mode 100644 index 0000000..97d4851 --- /dev/null +++ b/src/test/kotlin/com/cycode/plugin/DiffScanTest.kt @@ -0,0 +1,66 @@ +package com.cycode.plugin + +import com.cycode.plugin.cli.* +import com.cycode.plugin.git.DiffSide +import org.junit.Assert.* +import org.junit.Test + +class DiffScanTest { + @Test + fun commitRangeArgs() { + assertArrayEquals( + arrayOf("commit-history", "--commit-range", "a..b", "/repo"), + getDiffScanArgs(DiffScanMode.CommitRange, "a..b", "/repo") + ) + } + + @Test + fun localDiffArgs() { + assertArrayEquals( + arrayOf("pre-commit", "--include-unstaged", "--base-ref", "main", "--path", "/repo"), + getDiffScanArgs(DiffScanMode.LocalDiff, "main", "/repo") + ) + } + + @Test + fun optionLikeRefIsRejected() { + assertThrows(IllegalArgumentException::class.java) { + getDiffScanArgs(DiffScanMode.LocalDiff, "--output=x", "/repo") + } + assertFalse(isSafeRefArg("a\nb")) + assertTrue(isSafeRefArg("feature/x")) + } + + @Test + fun iacDoesNotSupportDiff() { + assertFalse(supportsDiffScan(CliScanType.Iac)) + assertTrue(supportsDiffScan(CliScanType.Secret)) + } + + @Test + fun scanTargetArgs() { + assertArrayEquals(arrayOf("path", "/a", "/b"), ScanTarget.Paths(listOf("/a", "/b")).toCliArgs()) + assertArrayEquals( + arrayOf("commit-history", "--commit-range", "x..y", "/repo"), + ScanTarget.Diff(DiffScanMode.CommitRange, "x..y", "/repo").toCliArgs() + ) + } + + @Test + fun unsafeRefsAreRejected() { + assertThrows(IllegalArgumentException::class.java) { assertSafeRefArg("") } + assertThrows(IllegalArgumentException::class.java) { assertSafeRefArg("a\u0000b") } + assertThrows(IllegalArgumentException::class.java) { getDiffScanArgs(DiffScanMode.CommitRange, "-x", "/repo") } + assertThrows(IllegalArgumentException::class.java) { DiffSide.Rev("--output=x") } + assertThrows(IllegalArgumentException::class.java) { DiffSide.Rev("") } + assertFalse(isSafeRefArg("")) + assertFalse(isSafeRefArg("-")) + assertTrue(isSafeRefArg("origin/feature-1")) + assertTrue(isSafeRefArg("HEAD~1")) + } + + @Test + fun everyScanTypeExceptIacSupportsDiff() { + CliScanType.entries.forEach { assertEquals(it != CliScanType.Iac, supportsDiffScan(it)) } + } +} diff --git a/src/test/kotlin/com/cycode/plugin/GitCliTest.kt b/src/test/kotlin/com/cycode/plugin/GitCliTest.kt new file mode 100644 index 0000000..baabae4 --- /dev/null +++ b/src/test/kotlin/com/cycode/plugin/GitCliTest.kt @@ -0,0 +1,164 @@ +package com.cycode.plugin + +import com.cycode.plugin.git.* +import org.junit.Assert.* +import org.junit.Test + +/** Uses real temporary git repositories: the exit-code semantics are the point. */ +class GitCliTest : GitTestBase() { + private fun diverge() { + sh("checkout", "-b", "feature") + commit("feature-1") + sh("checkout", "main") + commit("main-1") + } + + @Test + fun divergedBranchesGiveMergeBaseRangeBothWays() { + diverge() + val base = sh("merge-base", "main", "feature") + val feature = sh("rev-parse", "feature") + val main = sh("rev-parse", "main") + + assertEquals(CommitRangeResult.Range("$base..$feature"), git.range("main", "feature")) + assertEquals(CommitRangeResult.Range("$base..$main"), git.range("feature", "main")) + } + + @Test + fun newestFirstIsSwapped() { + val old = sh("rev-parse", "HEAD") + commit("second") + val new = sh("rev-parse", "HEAD") + + assertEquals(CommitRangeResult.Range("$old..$new"), git.range(old, new)) + assertEquals(CommitRangeResult.Range("$old..$new"), git.range(new, old)) + } + + @Test + fun gitIsAvailable() { + assertTrue(git.isGitAvailable()) + } + + @Test + fun sameCommit() { + assertEquals(CommitRangeResult.SameCommit, git.range("HEAD", "main")) + } + + @Test + fun noCommonHistory() { + sh("checkout", "--orphan", "orphan") + commit("orphan-1") + assertEquals(CommitRangeResult.NoCommonHistory, git.range("main", "orphan")) + } + + @Test + fun unknownRevision() { + assertEquals(CommitRangeResult.UnknownRevision, git.range("main", "nope")) + } + + @Test + fun nonGitFolder() { + val plain = createPlainDirectory() + try { + assertFalse(GitCli(plain.path).isGitRepository()) + assertTrue(git.isGitRepository()) + } finally { + plain.deleteRecursively() + } + } + + @Test + fun refLabelsAndPinning() { + diverge() + val refs = git.getAvailableRefs() + assertEquals(HEAD_REF, refs.first().value) + assertTrue(refs.any { it.value == "feature" && it.label.startsWith("feature$LABEL_SEPARATOR") }) + // a commit that is a branch tip is listed once, under the ref name + assertEquals(1, refs.count { it.label.endsWith("main-1") }) + + val first = sh("rev-list", "--max-parents=0", "HEAD") + assertTrue(git.getAvailableRefs(listOf(DiffSide.Rev(first))).any { it.value == first }) + assertFalse(git.getAvailableRefs(listOf(DiffSide.Rev("nope"))).any { it.value == "nope" }) + } + + @Test + fun labelFormat() { + assertEquals("main │ abc123 │ subject", GitCli.buildLabel("main", "abc123", "subject")) + } + + @Test + fun refListsAreCapped() { + repeat(GitCli.MAX_REFS + 5) { sh("branch", "b$it") } + repeat(GitCli.MAX_COMMITS + 5) { commit("c$it") } + + val refs = git.getAvailableRefs() + val sha = Regex("[0-9a-f]{40}") + val branchesAndTags = refs.count { it.value != HEAD_REF && !sha.matches(it.value) } + assertTrue(branchesAndTags <= GitCli.MAX_REFS) + // HEAD + capped refs + capped commits + assertTrue(refs.size <= 1 + GitCli.MAX_REFS + GitCli.MAX_COMMITS) + } + + @Test + fun tagsAreListed() { + sh("tag", "v1") + assertTrue(git.getAvailableRefs().any { it.value == "v1" }) + } + + @Test + fun commitsAreLabelledWithTheCurrentBranch() { + commit("second") + val commitOption = git.getAvailableRefs().first { it.label.endsWith("base") } + assertTrue(commitOption.label.startsWith("main$LABEL_SEPARATOR")) + } + + @Test + fun detachedHeadCommitsHaveNoBranchPrefix() { + commit("second") + sh("checkout", "--detach", "HEAD~1") + val refs = git.getAvailableRefs() + val baseCommit = refs.first { it.label.endsWith("base") && it.value.length == 40 } + assertFalse(baseCommit.label.contains("main")) + assertEquals(HEAD_REF, refs.first().value) + } + + @Test + fun remoteHeadSymbolicRefIsSkipped() { + sh("update-ref", "refs/remotes/origin/main", "HEAD") + sh("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main") + val refs = git.getAvailableRefs() + assertTrue(refs.any { it.value == "origin/main" }) + assertFalse(refs.any { it.value.endsWith("/HEAD") }) + } + + @Test + fun commitRangeWithTagsAndRelativeRevisions() { + sh("tag", "v1") + commit("second") + val result = git.range("v1", "HEAD") as CommitRangeResult.Range + assertTrue(result.range.matches(Regex("[0-9a-f]{40}\\.\\.[0-9a-f]{40}"))) + assertEquals(result, git.range("v1", "main")) + } + + @Test + fun unknownFromRevision() { + assertEquals(CommitRangeResult.UnknownRevision, git.range("nope", "main")) + } + + @Test + fun pinnedRefThatScrolledOutOfTheListIsKept() { + val oldest = sh("rev-parse", "HEAD") + repeat(GitCli.MAX_COMMITS + 5) { commit("c$it") } + val refs = git.getAvailableRefs(listOf(DiffSide.Rev(oldest), DiffSide.Rev("HEAD"))) + assertEquals(1, refs.count { it.value == oldest }) + assertEquals(1, refs.count { it.value == HEAD_REF }) + } + + @Test + fun labelWithoutRefNameOrSubject() { + assertEquals("abc123", GitCli.buildLabel(null, "abc123", "")) + assertEquals("abc123 │ subject", GitCli.buildLabel("", "abc123", "subject")) + } + + private fun GitCli.range(from: String, to: String) = getCommitRange(DiffSide.Rev(from), DiffSide.Rev(to)) +} diff --git a/src/test/kotlin/com/cycode/plugin/GitTestBase.kt b/src/test/kotlin/com/cycode/plugin/GitTestBase.kt new file mode 100644 index 0000000..2283bd3 --- /dev/null +++ b/src/test/kotlin/com/cycode/plugin/GitTestBase.kt @@ -0,0 +1,50 @@ +package com.cycode.plugin + +import com.cycode.plugin.git.GitCli +import org.junit.After +import org.junit.Before +import java.io.File +import java.nio.file.Files + +/** + * Real temporary git repository with one commit ("base") on `main`: the git semantics are the point of the tests, + * so nothing is mocked. + */ +abstract class GitTestBase { + protected lateinit var dir: File + protected lateinit var git: GitCli + + protected fun sh(vararg args: String): String { + // signing and the user's global config must not influence the tests + val command = listOf( + "git", "-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false", + "-c", "tag.gpgsign=false", *args + ) + val process = ProcessBuilder(command).directory(dir).redirectErrorStream(true).start() + val out = process.inputStream.bufferedReader().readText().trim() + check(process.waitFor() == 0) { "git ${args.toList()} failed: $out" } + return out + } + + protected fun commit(name: String) { + File(dir, name).writeText(name) + sh("add", name) + sh("commit", "-m", name) + } + + protected fun createPlainDirectory(): File = Files.createTempDirectory("cycode-plain").toFile() + + @Before + fun createRepository() { + dir = Files.createTempDirectory("cycode-git").toFile() + sh("init") + sh("symbolic-ref", "HEAD", "refs/heads/main") // `init -b` needs git 2.28 + commit("base") + git = GitCli(dir.path) + } + + @After + fun deleteRepository() { + dir.deleteRecursively() + } +} diff --git a/src/test/kotlin/com/cycode/plugin/ScanScopeLogicTest.kt b/src/test/kotlin/com/cycode/plugin/ScanScopeLogicTest.kt new file mode 100644 index 0000000..de86516 --- /dev/null +++ b/src/test/kotlin/com/cycode/plugin/ScanScopeLogicTest.kt @@ -0,0 +1,45 @@ +package com.cycode.plugin + +import com.cycode.plugin.cli.CliScanType +import com.cycode.plugin.cli.isFileSupportedByScanType +import com.cycode.plugin.cli.partitionByFileSupport +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ScanScopeLogicTest { + private val allTypes = listOf(CliScanType.Secret, CliScanType.Sca, CliScanType.Sast, CliScanType.Iac) + + @Test + fun secretAndSastScanAnyFile() { + assertTrue(isFileSupportedByScanType("/p/Main.kt", CliScanType.Secret)) + assertTrue(isFileSupportedByScanType("/p/Main.kt", CliScanType.Sast)) + } + + @Test + fun scaOnlyScansPackageFiles() { + assertTrue(isFileSupportedByScanType("/p/package.json", CliScanType.Sca)) + assertTrue(isFileSupportedByScanType("/p/requirements.txt", CliScanType.Sca)) + assertFalse(isFileSupportedByScanType("/p/Main.kt", CliScanType.Sca)) + } + + @Test + fun iacOnlyScansInfrastructureFiles() { + assertTrue(isFileSupportedByScanType("/p/main.tf", CliScanType.Iac)) + assertTrue(isFileSupportedByScanType("/p/Dockerfile", CliScanType.Iac)) + assertTrue(isFileSupportedByScanType("/p/deploy.yaml", CliScanType.Iac)) + assertFalse(isFileSupportedByScanType("/p/Main.kt", CliScanType.Iac)) + } + + @Test + fun partitionKeepsTheOrderOfTheScanTypes() { + val (supported, unsupported) = partitionByFileSupport("/p/Main.kt", allTypes) + assertEquals(listOf(CliScanType.Secret, CliScanType.Sast), supported) + assertEquals(listOf(CliScanType.Sca, CliScanType.Iac), unsupported) + + val (all, none) = partitionByFileSupport("/p/package.json", listOf(CliScanType.Secret, CliScanType.Sca)) + assertEquals(listOf(CliScanType.Secret, CliScanType.Sca), all) + assertTrue(none.isEmpty()) + } +}