Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SLI-378 Prefer PasswordSafe to PasswordUtil #858

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .cirrus/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ FROM ${CIRRUS_AWS_ACCOUNT}.dkr.ecr.eu-central-1.amazonaws.com/base:j${JDK_VERSIO
USER root

ENV NODE_VERSION=18

# dbus-x11 is for SonarLint token secure storage (required by the IDE)
RUN apt-get update && apt-get install -y metacity xvfb xauth ffmpeg \
dbus-x11 \
nodejs=${NODE_VERSION}.* \
build-essential \
gettext-base \
Expand Down
15 changes: 8 additions & 7 deletions src/main/java/org/sonarlint/intellij/SonarLintIntelliJClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ import org.sonarlint.intellij.analysis.AnalysisSubmitter
import org.sonarlint.intellij.common.ui.ReadActionUtils.Companion.computeReadActionSafely
import org.sonarlint.intellij.common.util.SonarLintUtils
import org.sonarlint.intellij.common.util.SonarLintUtils.getService
import org.sonarlint.intellij.config.Settings.getGlobalSettings
import org.sonarlint.intellij.config.Settings.getSettingsFor
import org.sonarlint.intellij.config.global.ServerConnectionService
import org.sonarlint.intellij.config.global.wizard.ServerConnectionCreator
import org.sonarlint.intellij.core.BackendService
import org.sonarlint.intellij.core.ProjectBindingManager
Expand Down Expand Up @@ -334,7 +334,7 @@ object SonarLintIntelliJClient : SonarLintClient {
return CompletableFuture.supplyAsync {
val connectionId = params.connectionId
val projectKey = params.projectKey
val connection = getGlobalSettings().getServerConnectionByName(connectionId)
val connection = ServerConnectionService.getInstance().getServerConnectionByName(connectionId)
.orElseThrow { IllegalStateException("Unable to find connection '$connectionId'") }
val message = "Cannot automatically find a project bound to:\n" +
" • Project: $projectKey\n" +
Expand Down Expand Up @@ -390,11 +390,12 @@ object SonarLintIntelliJClient : SonarLintClient {
}

override fun getCredentials(params: GetCredentialsParams): CompletableFuture<GetCredentialsResponse> {
return getGlobalSettings().getServerConnectionByName(params.connectionId)
.map { connection -> connection.token?.let { CompletableFuture.completedFuture(GetCredentialsResponse(TokenDto(it))) }
?: connection.login?.let { CompletableFuture.completedFuture(GetCredentialsResponse(UsernamePasswordDto(it, connection.password))) }
?: CompletableFuture.failedFuture(IllegalArgumentException("Invalid credentials for connection: " + params.connectionId))
}.orElse(CompletableFuture.failedFuture(IllegalArgumentException("Unknown connection: " + params.connectionId)))
val connectionId = params.connectionId
return ServerConnectionService.getInstance().getServerCredentialsByName(connectionId)
.map { credentials -> credentials.token?.let { CompletableFuture.completedFuture(GetCredentialsResponse(TokenDto(it))) }
?: credentials.login?.let { CompletableFuture.completedFuture(GetCredentialsResponse(UsernamePasswordDto(it, credentials.password))) }
?: CompletableFuture.failedFuture(IllegalArgumentException("Invalid credentials for connection: $connectionId"))}
.orElseGet { CompletableFuture.failedFuture(IllegalArgumentException("Connection '$connectionId' not found")) }
}

override fun getProxyPasswordAuthentication(params: GetProxyPasswordAuthenticationParams): CompletableFuture<GetProxyPasswordAuthenticationResponse> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class OpenIssueInBrowserAction : AbstractSonarAction(
override fun updatePresentation(e: AnActionEvent, project: Project) {
val serverConnection = serverConnection(project) ?: return
e.presentation.text = "Open in " + serverConnection.productName
e.presentation.icon = serverConnection.productIcon
e.presentation.icon = serverConnection.product.icon
}

override fun actionPerformed(e: AnActionEvent) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class OpenSecurityHotspotInBrowserAction : AbstractSonarAction(
val serverConnection = serverConnection(project) ?: return
e.presentation.text = "Open in " + serverConnection.productName
e.presentation.description = "Open Security Hotspot in browser interface of " + serverConnection.productName
e.presentation.icon = serverConnection.productIcon
e.presentation.icon = serverConnection.product.icon
}

override fun actionPerformed(e: AnActionEvent) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* SonarLint for IntelliJ IDEA
* Copyright (C) 2015-2023 SonarSource
* [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonarlint.intellij.config.global

import org.sonarlint.intellij.common.util.SonarLintUtils
import org.sonarlint.intellij.common.util.SonarLintUtils.SONARCLOUD_URL
import org.sonarlint.intellij.core.BackendService
import org.sonarlint.intellij.core.SonarProduct
import org.sonarlint.intellij.core.server.ServerLinks
import org.sonarlint.intellij.core.server.SonarCloudLinks
import org.sonarlint.intellij.core.server.SonarQubeLinks
import org.sonarsource.sonarlint.core.serverapi.EndpointParams
import org.sonarsource.sonarlint.core.serverapi.ServerApi


sealed class ServerConnection {
abstract val name: String
abstract val notificationsDisabled: Boolean
abstract val hostUrl: String
abstract val product: SonarProduct
abstract val links: ServerLinks
abstract val endpointParams: EndpointParams
fun api() = ServerApi(endpointParams, SonarLintUtils.getService(BackendService::class.java).getHttpClient(name))
override fun toString() = name
val isSonarCloud get() = product == SonarProduct.SONARCLOUD
val isSonarQube get() = product == SonarProduct.SONARQUBE
val productName get() = product.productName
}

data class SonarQubeConnection(override val name: String, override val hostUrl: String, override val notificationsDisabled: Boolean) : ServerConnection() {
override val product = SonarProduct.SONARQUBE
override val links = SonarQubeLinks(hostUrl)
override val endpointParams = EndpointParams(hostUrl, false, null)
}

data class SonarCloudConnection(override val name: String, val organizationKey: String, override val notificationsDisabled: Boolean) : ServerConnection() {
override val product = SonarProduct.SONARCLOUD
override val links = SonarCloudLinks
override val hostUrl: String = SONARCLOUD_URL
override val endpointParams = EndpointParams(hostUrl, true, organizationKey)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* SonarLint for IntelliJ IDEA
* Copyright (C) 2015-2023 SonarSource
* [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonarlint.intellij.config.global

data class ServerConnectionCredentials(val login: String?, val password: String?, val token: String?)
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package org.sonarlint.intellij.config.global

class ServerConnectionCredentialsNotFound(connectionName: String) : RuntimeException("Unable to load credentials for connection '$connectionName'")
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
package org.sonarlint.intellij.config.global;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.ui.Messages;
Expand All @@ -32,13 +33,14 @@
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBList;
import org.sonarlint.intellij.SonarLintIcons;
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Expand All @@ -54,6 +56,8 @@

import static org.sonarlint.intellij.common.util.SonarLintUtils.getService;
import static org.sonarlint.intellij.config.Settings.getSettingsFor;
import static org.sonarlint.intellij.ui.UiUtils.runOnUiThread;
import static org.sonarlint.intellij.util.ThreadUtilsKt.runOnPooledThread;

public class ServerConnectionMgmtPanel implements ConfigurationPanel<SonarLintGlobalSettings> {
private static final String LABEL_NO_SERVERS = "Add a connection to SonarQube or SonarCloud";
Expand All @@ -65,8 +69,10 @@ public class ServerConnectionMgmtPanel implements ConfigurationPanel<SonarLintGl

// Model
private GlobalConfigurationListener connectionChangeListener;
private final List<ServerConnection> connections = new ArrayList<>();
private final Map<String, ServerConnectionWithAuth> updatedConnectionsByName = new HashMap<>();
private final Map<String, ServerConnectionWithAuth> addedConnectionsByName = new HashMap<>();
private final Set<String> deletedServerIds = new HashSet<>();
private CollectionListModel<ServerConnection> listModel;

private void create() {
var app = ApplicationManager.getApplication();
Expand Down Expand Up @@ -105,15 +111,11 @@ public void mouseClicked(MouseEvent evt) {

connectionList.setCellRenderer(new ColoredListCellRenderer<>() {
@Override
protected void customizeCellRenderer(JList list, ServerConnection server, int index, boolean selected, boolean hasFocus) {
if (server.isSonarCloud()) {
setIcon(SonarLintIcons.ICON_SONARCLOUD_16);
} else {
setIcon(SonarLintIcons.ICON_SONARQUBE_16);
}
append(server.getName(), SimpleTextAttributes.REGULAR_ATTRIBUTES);
if (!server.isSonarCloud()) {
append(" (" + server.getHostUrl() + ")", SimpleTextAttributes.GRAYED_ATTRIBUTES, false);
protected void customizeCellRenderer(JList list, ServerConnection connection, int index, boolean selected, boolean hasFocus) {
setIcon(connection.getProduct().getIcon());
append(connection.getName(), SimpleTextAttributes.REGULAR_ATTRIBUTES);
if (connection.isSonarQube()) {
append(" (" + connection.getHostUrl() + ")", SimpleTextAttributes.GRAYED_ATTRIBUTES, false);
}
}
});
Expand Down Expand Up @@ -144,30 +146,35 @@ public JComponent getComponent() {

@Override
public boolean isModified(SonarLintGlobalSettings settings) {
return !connections.equals(settings.getServerConnections());
return !updatedConnectionsByName.isEmpty() || !addedConnectionsByName.isEmpty() || !deletedServerIds.isEmpty();
}

@Override
public void save(SonarLintGlobalSettings newSettings) {
var newConnections = new ArrayList<>(connections);
newSettings.setServerConnections(newConnections);
// use background thread because of credentials save
runOnPooledThread(() -> {
ServerConnectionService.getInstance().updateServerConnections(newSettings, new HashSet<>(deletedServerIds), new ArrayList<>(updatedConnectionsByName.values()),
new ArrayList<>(addedConnectionsByName.values()));
// remove them even if a server with the same name was later added
unbindRemovedServers();
});

// remove them even if a server with the same name was later added
unbindRemovedServers();
}

@Override
public void load(SonarLintGlobalSettings settings) {
connections.clear();
updatedConnectionsByName.clear();
addedConnectionsByName.clear();
deletedServerIds.clear();

var listModel = new CollectionListModel<ServerConnection>(new ArrayList<>());
listModel.add(settings.getServerConnections());
connections.addAll(settings.getServerConnections());
listModel = new CollectionListModel<>(new ArrayList<>());
var serverConnections = ServerConnectionService.getInstance().getConnections();

listModel.add(serverConnections);
connectionList.setModel(listModel);

if (!connections.isEmpty()) {
connectionList.setSelectedValue(connections.get(0), true);
if (!serverConnections.isEmpty()) {
connectionList.setSelectedValue(serverConnections.get(0), true);
}
}

Expand All @@ -177,51 +184,80 @@ private ServerConnection getSelectedConnection() {
}

List<ServerConnection> getConnections() {
return connections;
return listModel.getItems();
}

private void editSelectedConnection() {
var selectedConnection = getSelectedConnection();
int selectedIndex = connectionList.getSelectedIndex();

if (selectedConnection != null) {
var serverEditor = ServerConnectionWizard.forConnectionEdition(selectedConnection);
if (serverEditor.showAndGet()) {
var editedConnection = serverEditor.getConnection();
((CollectionListModel<ServerConnection>) connectionList.getModel()).setElementAt(editedConnection, selectedIndex);
connections.set(connections.indexOf(selectedConnection), editedConnection);
connectionChangeListener.changed(connections);
}
var connectionName = selectedConnection.getName();
runOnPooledThread(() -> {
var previousCredentials = getCredentialsForEdition(connectionName);
runOnUiThread(ModalityState.any(), () -> {
var serverEditor = ServerConnectionWizard.forConnectionEdition(new ServerConnectionWithAuth(selectedConnection, previousCredentials));
if (serverEditor.showAndGet()) {
var editedConnectionWithAuth = serverEditor.getConnectionWithAuth();
listModel.setElementAt(editedConnectionWithAuth.getConnection(), selectedIndex);
if (addedConnectionsByName.containsKey(connectionName)) {
addedConnectionsByName.put(connectionName, editedConnectionWithAuth);
} else {
updatedConnectionsByName.put(connectionName, editedConnectionWithAuth);
}
connectionChangeListener.changed(getConnections());
}
});
});
}
}

private ServerConnectionCredentials getCredentialsForEdition(String connectionName) {
var connection = addedConnectionsByName.get(connectionName);
if (connection != null) {
return connection.getCredentials();
}
connection = updatedConnectionsByName.get(connectionName);
if (connection != null) {
return connection.getCredentials();
}
return ServerConnectionService.getInstance().getServerCredentialsByName(connectionName)
.orElseThrow(() -> new IllegalStateException("Credentials for connection '" + connectionName + "' not found"));
}

private class AddConnectionAction implements AnActionButtonRunnable {
@Override
public void run(AnActionButton anActionButton) {
var existingNames = connections.stream().map(ServerConnection::getName).collect(Collectors.toSet());
var existingNames = getConnections().stream().map(ServerConnection::getName).collect(Collectors.toSet());
var wizard = ServerConnectionWizard.forNewConnection(existingNames);
if (wizard.showAndGet()) {
var created = wizard.getConnection();
connections.add(created);
((CollectionListModel<ServerConnection>) connectionList.getModel()).add(created);
connectionList.setSelectedIndex(connectionList.getModel().getSize() - 1);
connectionChangeListener.changed(connections);
var created = wizard.getConnectionWithAuth();
var connectionName = created.getConnection().getName();
if (deletedServerIds.contains(connectionName)) {
updatedConnectionsByName.put(connectionName, created);
deletedServerIds.remove(connectionName);
} else {
addedConnectionsByName.put(connectionName, created);
}
listModel.add(created.getConnection());
connectionList.setSelectedIndex(listModel.getSize() - 1);
connectionChangeListener.changed(getConnections());
}
}
}

private class RemoveServerAction implements AnActionButtonRunnable {
@Override
public void run(AnActionButton anActionButton) {
var server = getSelectedConnection();
var connection = getSelectedConnection();
var selectedIndex = connectionList.getSelectedIndex();

if (server == null) {
if (connection == null) {
return;
}

var openProjects = ProjectManager.getInstance().getOpenProjects();
var projectsUsingNames = getOpenProjectNames(openProjects, server);
var projectsUsingNames = getOpenProjectNames(openProjects, connection);

if (!projectsUsingNames.isEmpty()) {
var projects = String.join("<br>", projectsUsingNames);
Expand All @@ -234,15 +270,18 @@ public void run(AnActionButton anActionButton) {
}
}

var model = (CollectionListModel<ServerConnection>) connectionList.getModel();
// it's not removed from serverIds and editorList
model.remove(server);
connections.remove(server);
connectionChangeListener.changed(connections);
listModel.remove(connection);
var connectionName = connection.getName();
if (!addedConnectionsByName.containsKey(connectionName)) {
deletedServerIds.add(connectionName);
}
addedConnectionsByName.remove(connectionName);
updatedConnectionsByName.remove(connectionName);
connectionChangeListener.changed(getConnections());

if (model.getSize() > 0) {
var newIndex = Math.min(model.getSize() - 1, Math.max(selectedIndex - 1, 0));
connectionList.setSelectedValue(model.getElementAt(newIndex), true);
if (listModel.getSize() > 0) {
var newIndex = Math.min(listModel.getSize() - 1, Math.max(selectedIndex - 1, 0));
connectionList.setSelectedValue(listModel.getElementAt(newIndex), true);
}
}

Expand Down
Loading
Loading