Skip to content

Commit

Permalink
fix: legacy scan under windows (#47)
Browse files Browse the repository at this point in the history
* fix: launch of legacy scan under Windows

* fix: linux/mac launching of cli (without sh)

* chore: update CHANGELOG.md

* refactor: rename cli params from `command` to `params`
  • Loading branch information
bastiandoetsch authored Jun 10, 2022
1 parent e37cfec commit 63b0ecc
Show file tree
Hide file tree
Showing 5 changed files with 145 additions and 77 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@

## [2.0.0] - Unreleased


### Fixes
- fixed legacy Snyk View scan under Windows
- fixed passing of --insecure and --org parameters if empty

### Changes
- ⬆️ update jackson dependencies to 2.13.3

## [2.0.0] - v20220525.165232
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
package io.snyk.eclipse.plugin.runner;

import io.snyk.eclipse.plugin.properties.Preferences;
import static io.snyk.eclipse.plugin.utils.FileSystemUtil.getCliFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.eclipse.core.runtime.ILog;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
Expand All @@ -9,11 +18,8 @@
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Optional;
import io.snyk.eclipse.plugin.properties.Preferences;
import io.snyk.eclipse.plugin.utils.SnykLogger;

public class ProcessRunner {

Expand All @@ -27,7 +33,8 @@ public class ProcessRunner {
private static final String ENV_SNYK_INTEGRATION_VERSION = "SNYK_INTEGRATION_VERSION";

private static final String HOME = System.getProperty("user.home");
private static final String DEFAULT_MAC_PATH = "/usr/local/bin:/usr/bin:/bin:/sbin:/usr/sbin:" + HOME + "/bin:" + HOME + "/.cargo/bin:" + System.getenv("GOPATH") + "/bin" + System.getenv("GOROOT") + "/bin";
private static final String DEFAULT_MAC_PATH = "/usr/local/bin:/usr/bin:/bin:/sbin:/usr/sbin:" + HOME + "/bin:"
+ HOME + "/.cargo/bin:" + System.getenv("GOPATH") + "/bin" + System.getenv("GOROOT") + "/bin";
private static final String DEFAULT_LINUX_PATH = DEFAULT_MAC_PATH;
private static final String DEFAULT_WIN_PATH = "";

Expand Down Expand Up @@ -66,20 +73,26 @@ public ProcessResult run(ProcessBuilder pb, Optional<File> navigatePath) {
return new ProcessResult(content.toString(), error.toString());

} catch (IOException e) {
e.printStackTrace();
SnykLogger.logError(e);
return new ProcessResult("", e.getMessage());
}
}

public ProcessBuilder createLinuxProcessBuilder(String command, Optional<String> path) {
return getProcessBuilder(command, path, DEFAULT_LINUX_PATH);
public ProcessBuilder createLinuxProcessBuilder(List<String> params, Optional<String> path) {
return getProcessBuilder(params, path, DEFAULT_LINUX_PATH);
}

private ProcessBuilder getProcessBuilder(String command, Optional<String> path, String defaultLinuxPath) {
ProcessBuilder pb = new ProcessBuilder("sh", "-c", command);
private ProcessBuilder getProcessBuilder(List<String> params, Optional<String> path, String defaultPathForOS) {
var cmd = new ArrayList<String>(params.size() + 2);
cmd.add(getCliFile().getAbsolutePath());
cmd.addAll(params);

ProcessBuilder pb = new ProcessBuilder(cmd);
setupProcessBuilderBase(pb);
if (path.isPresent()) {
pb.environment().put("PATH", path.map(p -> p + ":" + defaultLinuxPath).orElse(defaultLinuxPath) + File.pathSeparator + System.getenv("PATH"));
if (path.isPresent() && !path.get().isBlank()) {
pb.environment().put("PATH",
path.map(p -> p + File.pathSeparator + defaultPathForOS).orElse(defaultPathForOS)
+ File.pathSeparator + System.getenv("PATH"));
}
return pb;
}
Expand All @@ -91,16 +104,18 @@ private void setupProcessBuilderBase(ProcessBuilder pb) {
}

String organization = preferences.getPref(Preferences.ORGANIZATION_KEY);
if (organization != null) {
if (organization != null && !organization.isBlank()) {
pb.environment().put(Preferences.ORGANIZATION_KEY, organization);
pb.command().add("--org=" + organization);
}

String token = preferences.getAuthToken();
if (token != null) pb.environment().put(ENV_SNYK_TOKEN, preferences.getAuthToken());
if (token != null)
pb.environment().put(ENV_SNYK_TOKEN, preferences.getAuthToken());

String insecure = preferences.getPref(Preferences.INSECURE_KEY);
if (insecure != null) pb.command().add("--insecure");
if (insecure != null && insecure.equalsIgnoreCase("true"))
pb.command().add("--insecure");

String enableTelemetry = preferences.getPref(Preferences.ENABLE_TELEMETRY);
if (!enableTelemetry.isBlank() && Boolean.parseBoolean(enableTelemetry)) {
Expand All @@ -113,19 +128,29 @@ private void setupProcessBuilderBase(ProcessBuilder pb) {
pb.environment().put(ENV_SNYK_INTEGRATION_VERSION, getVersion());
}

public ProcessBuilder createMacProcessBuilder(String command, Optional<String> path) {
return getProcessBuilder(command, path, DEFAULT_MAC_PATH);
public ProcessBuilder createMacProcessBuilder(List<String> params, Optional<String> path) {
return getProcessBuilder(params, path, DEFAULT_MAC_PATH);
}

public ProcessBuilder createWinProcessBuilder(String command, Optional<String> path) {
if (command.startsWith("\"/")) command = command.replaceFirst("/", "");
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c ", command);
public ProcessBuilder createWinProcessBuilder(List<String> params, Optional<String> path) {
var cmd = new ArrayList<String>(params.size() + 2);
cmd.add("cmd.exe");
cmd.add("/c");
cmd.add(getCliFile().getAbsolutePath());
cmd.addAll(params);

ProcessBuilder pb = new ProcessBuilder(cmd);
setupProcessBuilderBase(pb);
pb.environment().put("PATH", path.map(p -> p + ";" + DEFAULT_WIN_PATH).orElse(DEFAULT_WIN_PATH) + File.pathSeparator + System.getenv("PATH"));
pb.environment().put("PATH", path.map(p -> p + ";" + DEFAULT_WIN_PATH).orElse(DEFAULT_WIN_PATH)
+ File.pathSeparator + System.getenv("PATH"));

// debug logging on windows machines
IStatus[] statuses = new IStatus[]{new Status(Status.INFO, bundle.getSymbolicName(), "env.PATH = " + pb.environment().get("PATH")), new Status(Status.INFO, bundle.getSymbolicName(), "path = " + path), new Status(Status.INFO, bundle.getSymbolicName(), "command = " + command),};
MultiStatus multiStatusCommand = new MultiStatus(bundle.getSymbolicName(), Status.INFO, statuses, "Snyk command execution", null);
IStatus[] statuses = new IStatus[]{
new Status(Status.INFO, bundle.getSymbolicName(), "env.PATH = " + pb.environment().get("PATH")),
new Status(Status.INFO, bundle.getSymbolicName(), "path = " + path),
new Status(Status.INFO, bundle.getSymbolicName(), "params = " + params),};
MultiStatus multiStatusCommand = new MultiStatus(bundle.getSymbolicName(), Status.INFO, statuses,
"Snyk params execution", null);
log.log(multiStatusCommand);

return pb;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,6 @@ private ProcessResult snykRun(List<String> arguments) {

private ProcessResult snykRun(List<String> arguments, Optional<File> navigatePath) {
try {
if (PREFERENCES.isInsecure()) {
arguments = new ArrayList<>(arguments);
arguments.add(INSECURE);
}

ProcessBuilder processBuilder = createProcessBuilderByOS(arguments, PREFERENCES.getPath());
return processRunner.run(processBuilder, navigatePath);
} catch (Exception e) {
Expand All @@ -78,16 +73,14 @@ private ProcessResult snykRun(List<String> arguments, Optional<File> navigatePat
}

private ProcessBuilder createProcessBuilderByOS(List<String> params, Optional<String> path) throws Exception {
String runnable = getCliFile().getAbsolutePath();
ProcessBuilder processbuilder;
String paramsString = params.stream().collect(Collectors.joining("\" \"", "\"", "\""));


if (SystemUtils.IS_OS_MAC) {
processbuilder = processRunner.createMacProcessBuilder("\"" + runnable + "\" " + paramsString, path);
processbuilder = processRunner.createMacProcessBuilder(params, path);
} else if (SystemUtils.IS_OS_LINUX) {
processbuilder = processRunner.createLinuxProcessBuilder(runnable + " " + paramsString, path);
processbuilder = processRunner.createLinuxProcessBuilder(params, path);
} else if (SystemUtils.IS_OS_WINDOWS) {
processbuilder = processRunner.createWinProcessBuilder("\"" + runnable + "\" " + paramsString, path);
processbuilder = processRunner.createWinProcessBuilder(params, path);
} else {
throw new NotSupportedException("This operating system is not supported");
}
Expand Down
86 changes: 46 additions & 40 deletions plugin/src/main/java/io/snyk/eclipse/plugin/views/SnykView.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,17 +50,15 @@ public class SnykView extends ViewPart {
*/
public static final String ID = "io.snyk.eclipse.plugin.views.SnykView";

public static final Image CRITICAL_SEVERITY =
Activator.getImageDescriptor("/icons/severity-critical.png").createImage();
public static final Image CRITICAL_SEVERITY = Activator.getImageDescriptor("/icons/severity-critical.png")
.createImage();

public static final Image HIGH_SEVERITY =
Activator.getImageDescriptor("/icons/severity-high.png").createImage();
public static final Image HIGH_SEVERITY = Activator.getImageDescriptor("/icons/severity-high.png").createImage();

public static final Image MEDIUM_SEVERITY =
Activator.getImageDescriptor("/icons/severity-medium.png").createImage();
public static final Image MEDIUM_SEVERITY = Activator.getImageDescriptor("/icons/severity-medium.png")
.createImage();

public static final Image LOW_SEVERITY =
Activator.getImageDescriptor("/icons/severity-low.png").createImage();
public static final Image LOW_SEVERITY = Activator.getImageDescriptor("/icons/severity-low.png").createImage();

@Inject
IWorkbench workbench;
Expand All @@ -78,15 +76,13 @@ public class SnykView extends ViewPart {
private boolean alreadyRunning = false;
private final Preferences prefs = new Preferences();


public SnykView() {
rootModel = new DisplayModel();
DisplayModel init = new DisplayModel();
init.description = "";
rootModel.children.add(init);
}


@Override
public void createPartControl(Composite parent) {
createViewer(parent);
Expand All @@ -105,7 +101,6 @@ private void createViewer(Composite parent) {
table.setHeaderVisible(true);
table.setLinesVisible(true);


viewer.setContentProvider(new TreeContentProvider());
getSite().setSelectionProvider(viewer);

Expand Down Expand Up @@ -138,12 +133,17 @@ private void createColumns() {

private Image findSeverityImage(DisplayModel model) {
String severity = model.severity;
if (severity == null) return null;

if (severity.equalsIgnoreCase("critical")) return CRITICAL_SEVERITY;
if (severity.equalsIgnoreCase("high")) return HIGH_SEVERITY;
if (severity.equalsIgnoreCase("medium")) return MEDIUM_SEVERITY;
if (severity.equalsIgnoreCase("low")) return LOW_SEVERITY;
if (severity == null)
return null;

if (severity.equalsIgnoreCase("critical"))
return CRITICAL_SEVERITY;
if (severity.equalsIgnoreCase("high"))
return HIGH_SEVERITY;
if (severity.equalsIgnoreCase("medium"))
return MEDIUM_SEVERITY;
if (severity.equalsIgnoreCase("low"))
return LOW_SEVERITY;

return null;
}
Expand Down Expand Up @@ -200,18 +200,19 @@ private void makeActions() {

@Override
public void run() {
PreferenceDialog pref = PreferencesUtil.createPreferenceDialogOn(
getShell(), "io.snyk.eclipse.plugin.properties.preferencespage",
null, null);
if (pref != null) pref.open();
PreferenceDialog pref = PreferencesUtil.createPreferenceDialogOn(getShell(),
"io.snyk.eclipse.plugin.properties.preferencespage", null, null);
if (pref != null)
pref.open();
}
};
openPrefPage.setText("Preferences");

scanWorkspace = new Action() {
@Override
public void run() {
if (alreadyRunning) return;
if (alreadyRunning)
return;
showMessage(RUNNING);
scanWorkspace.setEnabled(false);
abortScanning.setEnabled(true);
Expand Down Expand Up @@ -251,11 +252,11 @@ public void run() {

private static Shell getShell() {
var activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (activeWorkbenchWindow == null) return SHELL;
if (activeWorkbenchWindow == null)
return SHELL;
return activeWorkbenchWindow.getShell();
}


public void enableScanBasedOnConfig() {
try {
boolean cliFound = getCliFile().exists();
Expand All @@ -265,7 +266,8 @@ public void enableScanBasedOnConfig() {
String init = "Click play to run Snyk Test";
String msg = "";
if (!cliFound) {
msg = "No Snyk CLI found. Please place a CLI file in " + FileSystemUtil.getCliFile().getAbsolutePath() + ". ";
msg = "No Snyk CLI found. Please place a CLI file in " + FileSystemUtil.getCliFile().getAbsolutePath()
+ ". ";
}
if (!tokenFound) {
msg += "No token found. Please add a Snyk Token in Snyk Preferences.";
Expand All @@ -280,7 +282,8 @@ public void enableScanBasedOnConfig() {
}

public void testProject(String projectName) {
if (alreadyRunning) return;
if (alreadyRunning)
return;
showMessage(RUNNING);
scanWorkspace.setEnabled(false);
abortScanning.setEnabled(true);
Expand All @@ -307,14 +310,16 @@ public void run() {
return action;
}


private Action monitorAction(String projectName) {
Action action = new Action() {
@Override
public void run() {
if (alreadyRunning) return;
MessageDialog.openInformation(getShell(), "Snyk monitor", "Snyk monitor for project " + projectName + " in progress...");
CompletableFuture.runAsync(() -> handleMonitorOutput(DataProvider.INSTANCE.monitorProject(projectName)));
if (alreadyRunning)
return;
MessageDialog.openInformation(getShell(), "Snyk monitor",
"Snyk monitor for project " + projectName + " in progress...");
CompletableFuture
.runAsync(() -> handleMonitorOutput(DataProvider.INSTANCE.monitorProject(projectName)));
}
};
action.setText("Snyk monitor " + projectName);
Expand Down Expand Up @@ -343,10 +348,12 @@ private void handleMonitorOutput(MonitorResult result) {
var shell = getShell();
if (result.hasError())
executeInUIThread(() -> MessageDialog.openError(shell, "Snyk Monitor Failed", result.getError()));
else shell.getDisplay().asyncExec(() -> {
LinkDialog dialog = new LinkDialog(shell, "Snyk Monitor Succesful", "Monitoring " + result.getPath() + " \n\nExplore this snapshot at: ", result.getUri());
dialog.open();
});
else
shell.getDisplay().asyncExec(() -> {
LinkDialog dialog = new LinkDialog(shell, "Snyk Monitor Succesful",
"Monitoring " + result.getPath() + " \n\nExplore this snapshot at: ", result.getUri());
dialog.open();
});
alreadyRunning = false;

}
Expand Down Expand Up @@ -382,15 +389,14 @@ public static void displayMessage(String message) {
}

public static SnykView getInstance() throws PartInitException {
return (SnykView) PlatformUI
.getWorkbench()
.getActiveWorkbenchWindow()
.getActivePage()
.showView(ID);
return (SnykView) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(ID);
}

@Override
public void setFocus() {
getShell().getDisplay().asyncExec(() -> viewer.getControl().setFocus());
getShell().getDisplay().asyncExec(() -> {
if (!viewer.getControl().isDisposed())
viewer.getControl().setFocus();
});
}
}
Loading

0 comments on commit 63b0ecc

Please sign in to comment.